@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\Sector;
|
||||
use App\Policies\ExistingBusinessPolicy;
|
||||
use App\Services\BusinessFormSchema;
|
||||
use App\Services\CountryCatalogue;
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
@@ -35,6 +36,7 @@ class ExistingBusinessController extends Controller
|
||||
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', [
|
||||
'submitted', 'triage', 'in_review', 'needs_information', 'approval_l1', 'approval_l2', 'approved',
|
||||
]);
|
||||
app(ExistingBusinessPolicy::class)->scopeReviewQueue($query, $request->user());
|
||||
} else {
|
||||
$query->where('owner_user_id', $request->user()->id);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use App\Services\VerifiedDocumentBinary;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
@@ -55,8 +56,17 @@ class LandAssistanceController extends Controller
|
||||
|
||||
public function create(Request $request): Response
|
||||
{
|
||||
$context = $request->validate(['context' => ['nullable', 'uuid']])['context'] ?? null;
|
||||
$dossier = null;
|
||||
if ($context !== null) {
|
||||
$case = app(\App\Services\VirtualDesk::class)->case($request->user(), $context);
|
||||
abort_unless(config('investor-path.enabled') && (int) $case->user_id === $request->user()->id && ! $case->closed_at && $case->journey_id
|
||||
&& DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists(), 403);
|
||||
$dossier = ['id' => $case->id, 'title' => $case->title, 'url' => '/investimentos/'.$case->id];
|
||||
}
|
||||
return Inertia::render('land-assistance/form', [
|
||||
'case' => null,
|
||||
'returnDossier' => $dossier,
|
||||
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
|
||||
'disclaimer' => self::DISCLAIMER,
|
||||
'modelVersion' => 'land-assistance-v1',
|
||||
@@ -71,6 +81,7 @@ class LandAssistanceController extends Controller
|
||||
|
||||
return Inertia::render('land-assistance/form', [
|
||||
'case' => $case->only(['id', 'reference', 'version', 'status', 'payload']),
|
||||
'returnDossier' => $this->dossierContext($case),
|
||||
'user' => ['name' => $request->user()->name, 'email' => $request->user()->email],
|
||||
'disclaimer' => self::DISCLAIMER,
|
||||
'modelVersion' => 'land-assistance-v1',
|
||||
@@ -152,8 +163,11 @@ class LandAssistanceController extends Controller
|
||||
$submittedPayload = $request->payload();
|
||||
$case = DB::transaction(function () use ($request, $id, $data, $submission, $submittedPayload): LandAssistanceCase {
|
||||
$case = $this->owned($request, $id, true);
|
||||
abort_unless(in_array($case->status, ['draft', 'waiting_applicant'], true), 409, 'Este pedido já não pode ser submetido neste estado.');
|
||||
$this->checkVersion($case, (int) $data['version']);
|
||||
$replaying = $case->status === 'support_requested';
|
||||
abort_unless(in_array($case->status, ['draft', 'waiting_applicant', 'support_requested'], true), 409, 'Este pedido já não pode ser submetido neste estado.');
|
||||
if (! $replaying) {
|
||||
$this->checkVersion($case, (int) $data['version']);
|
||||
}
|
||||
$payload = [...$case->payload, ...$submittedPayload];
|
||||
$payload['full_name'] = $payload['full_name'] ?? $request->user()->name;
|
||||
if (! array_key_exists('email', $payload)) {
|
||||
@@ -161,6 +175,14 @@ class LandAssistanceController extends Controller
|
||||
}
|
||||
$payload['email'] = is_string($payload['email']) && trim($payload['email']) !== '' ? strtolower(trim($payload['email'])) : null;
|
||||
abort_if(empty($payload['email']) && empty($payload['phone']), 422, 'Indique pelo menos um contacto valido.');
|
||||
if ($replaying) {
|
||||
// A retry of the same accepted attempt recovers its original receipt.
|
||||
// Changed data, another version or a missing receipt must not reopen the case.
|
||||
abort_unless((int) $case->version === (int) $data['version'] + 1 && $case->interest_request_id
|
||||
&& hash_equals(hash('sha256', json_encode(Arr::sortRecursive($case->payload), JSON_THROW_ON_ERROR)),
|
||||
hash('sha256', json_encode(Arr::sortRecursive($payload), JSON_THROW_ON_ERROR))),
|
||||
409, 'O pedido mudou; recupere o estado atual antes de voltar a enviar.');
|
||||
}
|
||||
$message = trim(($payload['request_description'] ?? 'Pedido de apoio sobre Terra e DUAT.')."\nReferência interna: {$case->reference}. Tipo: ".($payload['support_kind'] ?? 'não indicado').'.');
|
||||
$interest = $submission->receive([
|
||||
'kind' => 'support', 'fullName' => $payload['full_name'], 'email' => $payload['email'],
|
||||
@@ -172,13 +194,25 @@ class LandAssistanceController extends Controller
|
||||
], $case->crm_submission_key, fn () => InterestRequest::create([
|
||||
'reference' => 'AP-'.now()->year.'-'.Str::ulid(), 'full_name' => $payload['full_name'],
|
||||
'email' => $payload['email'], 'phone' => $payload['phone'] ?? null,
|
||||
'country' => $payload['country'] ?? 'Não indicado', 'investor_type' => 'individual',
|
||||
'country' => $payload['country'] ?? 'Não indicado',
|
||||
// Use the existing intake vocabulary; retain the more specific declared category.
|
||||
// This factory only runs for a new receipt. Older submissions/replay hashes stay intact.
|
||||
'investor_type' => match ($payload['applicant_category'] ?? null) {
|
||||
'individual' => 'individual', 'entity' => 'empresa', default => 'outro',
|
||||
},
|
||||
'sector_interest' => 'Terra e DUAT', 'message' => mb_substr($message, 0, 2000),
|
||||
'privacy_consent' => true, 'consented_at' => now(), 'status' => 'received', 'source_page' => '/terra-duat',
|
||||
'metadata' => ['kind' => 'support', 'portal_user_id' => $request->user()->id,
|
||||
'land_case_id' => $case->id, 'land_case_reference' => $case->reference,
|
||||
'applicant_category' => $payload['applicant_category'] ?? null,
|
||||
'declared_origin_country_code' => $payload['declared_origin_country_code'] ?? null],
|
||||
]));
|
||||
if ($replaying) {
|
||||
abort_unless((int) $interest->getKey() === (int) $case->interest_request_id && ! $interest->trashed(),
|
||||
409, 'O recibo original não está disponível; recupere o estado do pedido.');
|
||||
|
||||
return $case;
|
||||
}
|
||||
$case->forceFill([
|
||||
'payload' => $payload,
|
||||
'status' => 'support_requested',
|
||||
@@ -287,7 +321,13 @@ class LandAssistanceController extends Controller
|
||||
|
||||
public function download(Request $request, string $id, string $attachment): \Illuminate\Http\Response|BinaryFileResponse
|
||||
{
|
||||
$case = $this->owned($request, $id);
|
||||
// Management uses its existing explicit permission; the owner URL stays owner-only.
|
||||
if ($request->routeIs('land-assistance.manage.download')) {
|
||||
abort_unless($request->user()->can('manage-portal'), 403);
|
||||
$case = LandAssistanceCase::whereKey($id)->firstOrFail();
|
||||
} else {
|
||||
$case = $this->owned($request, $id);
|
||||
}
|
||||
$document = DB::table('land_assistance_documents as link')->join('documents as document', 'document.id', '=', 'link.document_id')
|
||||
->where('link.case_id', $id)->where('link.id', $attachment)->where('document.status', 'active')->whereNull('document.deleted_at')
|
||||
->where('document.malware_scan_status', 'clean')->whereColumn('document.malware_scanned_sha256', 'document.sha256')
|
||||
@@ -327,7 +367,18 @@ class LandAssistanceController extends Controller
|
||||
}
|
||||
|
||||
return ['countryName' => $country['code'] !== null ? $country['name'] : ($payload['country'] ?? 'Não informado'),
|
||||
'declaredOrigin' => $countries->describe($payload['declared_origin_country_code'] ?? null), 'territoryPaths' => $paths];
|
||||
'declaredOrigin' => $countries->describe($payload['declared_origin_country_code'] ?? null), 'territoryPaths' => $paths, 'returnDossier' => $this->dossierContext($case)];
|
||||
}
|
||||
|
||||
private function dossierContext(LandAssistanceCase $case): ?array
|
||||
{
|
||||
$id = $case->payload['investor_path_case_id'] ?? null;
|
||||
$actor = request()->user();
|
||||
if (! $actor || (int) $case->user_id !== $actor->id || ! is_string($id) || ! Str::isUuid($id) || ! config('investor-path.enabled')) {
|
||||
return null;
|
||||
}
|
||||
$dossier = DB::table('desk_cases')->where('id', $id)->where('user_id', $actor->id)->first();
|
||||
return $dossier ? ['id' => $dossier->id, 'title' => $dossier->title, 'url' => '/investimentos/'.$dossier->id] : null;
|
||||
}
|
||||
|
||||
public function manage(Request $request): Response
|
||||
|
||||
@@ -126,6 +126,8 @@ class OpportunityManagementController extends Controller
|
||||
Inertia::share(['basePath' => str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities',
|
||||
'canonicalOptions' => ($record?->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades')) ? app(OpportunityCanonicalContract::class)->options($request->user(), $record) : null,
|
||||
'workflowState' => $record ? $access->state($record) : null,
|
||||
'profileReauthenticationRequired' => $record && $record->owner_user_id !== null
|
||||
? app(OpportunityProfileWorkflow::class)->reauthenticationRequired($request->user(), $record) : false,
|
||||
'publicationState' => $record?->publicationPresentation(),
|
||||
'canonicalResponse' => $record?->owner_user_id !== null ? app(OpportunityCanonicalResponse::class)->read($request->user(), $record) : null,
|
||||
'canEditDraft' => $record ? $access->canEdit($request->user(), $record) : false,
|
||||
|
||||
@@ -66,7 +66,8 @@ class PortalManagementController extends Controller
|
||||
'id', 'reference', 'full_name', 'email', 'country', 'metadata', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
|
||||
]);
|
||||
if ($country = $filters['country'] ?? null) {
|
||||
$query->where('country', $country);
|
||||
$values = app(CountryCatalogue::class)->filterValues($country);
|
||||
$query->whereIn(DB::raw('LOWER(BTRIM(country))'), $values);
|
||||
}
|
||||
if ($origin = $filters['origin'] ?? null) {
|
||||
if ($origin === 'unknown') {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Services\InvestorPath;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\OpportunityManagement;
|
||||
@@ -56,6 +57,8 @@ class HandleInertiaRequests extends Middleware
|
||||
'educationEnabled' => (bool) config('education.enabled', false),
|
||||
'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
|
||||
'existingBusinessEnabled' => (bool) config('existing-business.enabled', false),
|
||||
'businessReviewUrl' => config('existing-business.enabled') && $request->user()?->can('reviewQueue', ExistingBusiness::class)
|
||||
? '/management/negocios' : null,
|
||||
'investorPathEnabled' => app(InvestorPath::class)->available(),
|
||||
'opportunityManagement' => config('portal.opportunity_dashboard_access_enabled') && $request->user() && app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()) ? [
|
||||
'installed' => app(OpportunityManagement::class)->installed(),
|
||||
|
||||
@@ -29,10 +29,11 @@ class StoreLandAssistanceCaseRequest extends FormRequest
|
||||
{
|
||||
return [
|
||||
'version' => [$this->isMethod('post') && ! $this->routeIs('land-assistance.support') ? 'nullable' : 'required', 'integer', 'min:1'],
|
||||
'payload' => ['required', 'array:support_kind,request_description,project_reference,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,declared_origin_country_code,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'],
|
||||
'payload' => ['required', 'array:support_kind,request_description,project_reference,investor_path_case_id,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,declared_origin_country_code,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'],
|
||||
'payload.support_kind' => ['nullable', 'in:investment,home,family_exploitation,recognition,regularization,delimitation,change_of_use,transfer,existing_process,conflict_guidance,other'],
|
||||
'payload.request_description' => ['nullable', 'string', 'max:4000'],
|
||||
'payload.project_reference' => ['nullable', 'string', 'max:160'],
|
||||
'payload.investor_path_case_id' => ['nullable', 'uuid'],
|
||||
'payload.applicant_category' => ['nullable', 'in:individual,entity,community,other'],
|
||||
'payload.full_name' => ['nullable', 'string', 'max:150'],
|
||||
'payload.contact_person' => ['nullable', 'string', 'max:200'],
|
||||
@@ -117,6 +118,23 @@ class StoreLandAssistanceCaseRequest extends FormRequest
|
||||
{
|
||||
$validator->after(function (Validator $validator): void {
|
||||
$payload = $this->input('payload', []);
|
||||
$context = is_array($payload) ? ($payload['investor_path_case_id'] ?? null) : null;
|
||||
$previous = $this->route('id') ? \App\Models\LandAssistanceCase::whereKey($this->route('id'))->where('user_id', $this->user()->id)->first() : null;
|
||||
$bound = $previous?->payload['investor_path_case_id'] ?? null;
|
||||
if ($context !== null) {
|
||||
$case = is_string($context) && \Illuminate\Support\Str::isUuid($context)
|
||||
? \Illuminate\Support\Facades\DB::table('desk_cases')->where('id', $context)->first() : null;
|
||||
if ((! config('investor-path.enabled') && $bound !== $context) || ! $case || (int) $case->user_id !== $this->user()->id
|
||||
|| ($case->closed_at && $bound !== $context) || ! $case->journey_id
|
||||
|| ! \Illuminate\Support\Facades\DB::table('investor_journeys')->where('id', $case->journey_id)->whereNotNull('path_definition_id')->whereNull('deleted_at')->exists()) {
|
||||
$validator->errors()->add('payload.investor_path_case_id', 'Use um dossier do seu percurso disponível para preparação. O acesso direto a Terra e DUAT continua disponível.');
|
||||
}
|
||||
}
|
||||
if ($this->route('id')) {
|
||||
if ($bound !== null && $context !== $bound) {
|
||||
$validator->errors()->add('payload.investor_path_case_id', 'Preserve o vínculo deste pedido ao dossier original.');
|
||||
}
|
||||
}
|
||||
if (is_array($payload) && is_array($payload['parcels'] ?? null)) {
|
||||
$geography = app(InvestmentGeography::class);
|
||||
$levels = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
||||
|
||||
@@ -29,6 +29,17 @@ class Opportunity extends Model
|
||||
|
||||
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once', 'owner_user_id', 'organization_id', 'workflow_context'];
|
||||
|
||||
protected $appends = ['maturity_catalogue_version'];
|
||||
|
||||
public function getMaturityCatalogueVersionAttribute(): ?string
|
||||
{
|
||||
// Only published metadata is public; never expose the current private draft.
|
||||
$version = data_get($this->workflow_context, 'publication.maturity.catalogue_version');
|
||||
|
||||
return in_array($version, [\App\Services\OpportunityMaturity::VERSION, \App\Services\OpportunityMaturity::LEGACY], true)
|
||||
? $version : null;
|
||||
}
|
||||
|
||||
protected $fillable = [
|
||||
'sector_id', 'reference', 'title', 'slug', 'summary', 'description',
|
||||
'province', 'district', 'promoter_name', 'promoter_type',
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace App\Policies;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\User;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class ExistingBusinessPolicy
|
||||
{
|
||||
@@ -24,9 +26,14 @@ class ExistingBusinessPolicy
|
||||
return true;
|
||||
}
|
||||
|
||||
$reviewedStates = ['rejected', 'published', 'suspended', 'cancelled', 'archived'];
|
||||
if (app(PortalProfileAccess::class)->available()) {
|
||||
$reviewedStates[] = 'approved';
|
||||
}
|
||||
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['rejected', 'published', 'suspended', 'cancelled', 'archived'], true)
|
||||
&& $this->reviewQueue($user);
|
||||
&& in_array($business->status, $reviewedStates, true)
|
||||
&& $this->designatedAny($user, $business);
|
||||
}
|
||||
|
||||
public function delete(User $user, ExistingBusiness $business): bool
|
||||
@@ -43,41 +50,56 @@ class ExistingBusinessPolicy
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['triage', 'in_review', 'needs_information'], true)
|
||||
&& $this->designated($user, 'reviewers');
|
||||
&& $this->designated($user, 'reviewers', $business);
|
||||
}
|
||||
|
||||
public function triage(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['submitted', 'triage'], true)
|
||||
&& $this->designated($user, 'triagers');
|
||||
&& $this->designated($user, 'triagers', $business);
|
||||
}
|
||||
|
||||
public function approveLevelOne(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approval_l1'
|
||||
&& $this->designated($user, 'approvers_l1');
|
||||
&& $this->designated($user, 'approvers_l1', $business);
|
||||
}
|
||||
|
||||
public function approveLevelTwo(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approval_l2'
|
||||
&& $this->designated($user, 'approvers_l2');
|
||||
&& $this->designated($user, 'approvers_l2', $business);
|
||||
}
|
||||
|
||||
public function publish(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approved'
|
||||
&& $this->designated($user, 'publishers');
|
||||
&& $this->designated($user, 'publishers', $business);
|
||||
}
|
||||
|
||||
public function reviewQueue(User $user): bool
|
||||
{
|
||||
return $this->designatedAny($user);
|
||||
}
|
||||
|
||||
/** Filter before projecting or decrypting private fields in the review queue. */
|
||||
public function scopeReviewQueue(Builder $query, User $user): void
|
||||
{
|
||||
if (app(PortalProfileAccess::class)->available()) {
|
||||
$query->where('modality', 'company_sale');
|
||||
$ids = (clone $query)->get()->filter(fn (ExistingBusiness $business) => $this->view($user, $business))->modelKeys();
|
||||
$query->whereKey($ids);
|
||||
}
|
||||
}
|
||||
|
||||
private function designatedAny(User $user, ?ExistingBusiness $business = null): bool
|
||||
{
|
||||
foreach (['reviewers', 'triagers', 'approvers_l1', 'approvers_l2', 'publishers'] as $designation) {
|
||||
if ($this->designated($user, $designation)) {
|
||||
if ($this->designated($user, $designation, $business)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -85,9 +107,32 @@ class ExistingBusinessPolicy
|
||||
return false;
|
||||
}
|
||||
|
||||
private function designated(User $user, string $designation): bool
|
||||
private function designated(User $user, string $designation, ?ExistingBusiness $business = null): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail() && $user->can('manage-portal')
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($access->available()) {
|
||||
// Only the existing company-sale consumer is reconciled in this increment.
|
||||
// Do not translate other modalities or invent an organization from free text.
|
||||
if (($business !== null && $business->modality !== 'company_sale') || ! $access->mfa($user)) {
|
||||
return false;
|
||||
}
|
||||
$role = $designation === 'publishers' ? 'publisher' : 'validator';
|
||||
if (! $access->operational($user, $role === 'publisher' ? 'publish' : 'validate')) {
|
||||
return false;
|
||||
}
|
||||
foreach ($access->grants($user, $role) as $grant) {
|
||||
if ($grant->organization_id === null
|
||||
&& in_array('business_sale', json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR), true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Legacy-only environments retain their explicit lists; a revoked/scoped v1
|
||||
// assignment must never regain wider permissions through that allowlist.
|
||||
return $user->hasVerifiedEmail() && $access->legacyWriteAllowed($user)
|
||||
&& (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
||||
&& in_array(strtolower($user->email), config('existing-business.'.$designation, []), true);
|
||||
}
|
||||
|
||||
@@ -46,6 +46,31 @@ final class CountryCatalogue
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact catalogue labels for reading legacy free-text country values.
|
||||
* Does not infer request origin, alter stored values or classify unmatched text.
|
||||
* Only labels belonging to one ISO country are included.
|
||||
*
|
||||
* @return list<string> Case-folded country code and catalogue labels.
|
||||
*/
|
||||
public function filterValues(string $code): array
|
||||
{
|
||||
$countries = $this->all();
|
||||
$owners = [];
|
||||
$selected = [];
|
||||
foreach ($countries as $country) {
|
||||
foreach (array_unique([$country['code'], $country['name'], $country['name_en']]) as $label) {
|
||||
$key = mb_strtolower(trim($label), 'UTF-8');
|
||||
$owners[$key][$country['code']] = true;
|
||||
if ($country['code'] === $code) {
|
||||
$selected[$key] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_filter(array_keys($selected), fn ($key) => count($owners[$key]) === 1));
|
||||
}
|
||||
|
||||
/** @return array{code:string|null,name:string} */
|
||||
public function describe(?string $code): array
|
||||
{
|
||||
|
||||
@@ -37,6 +37,7 @@ final class ExistingBusinessIntake
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent, $confirmationCode) {
|
||||
$business = app(BusinessRepository::class)->find($id, true);
|
||||
$profileWorkflow = $business->modality === 'company_sale' && app(PortalProfileAccess::class)->available();
|
||||
$ability = match ($action) {
|
||||
OpportunityStatus::Submitted->value, OpportunityStatus::Withdrawn->value => 'owns',
|
||||
OpportunityStatus::Triage->value => 'triage',
|
||||
@@ -117,7 +118,7 @@ final class ExistingBusinessIntake
|
||||
if ($action === OpportunityStatus::Approved->value) {
|
||||
$levelOneActor = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
||||
->where('to_status', OpportunityStatus::ApprovalL2->value)->orderByDesc('created_at')->value('actor_id');
|
||||
abort_unless($levelOneActor !== null && (int) $levelOneActor !== (int) $actor->id, 403,
|
||||
abort_unless($levelOneActor !== null && ($profileWorkflow || (int) $levelOneActor !== (int) $actor->id), 403,
|
||||
'A aprovação de nível 2 deve ser feita por uma pessoa diferente da aprovação de nível 1.');
|
||||
}
|
||||
if ($action === OpportunityStatus::Published->value) {
|
||||
@@ -146,7 +147,8 @@ final class ExistingBusinessIntake
|
||||
'actor_id' => $actor->id,
|
||||
'reason' => Crypt::encryptString($note),
|
||||
'correlation_id' => $correlationId,
|
||||
'metadata' => json_encode(['version_no' => $business->version_no, 'source' => 'portal-intake'], JSON_THROW_ON_ERROR),
|
||||
'metadata' => json_encode(['version_no' => $business->version_no, 'source' => 'portal-intake',
|
||||
'authorization_mode' => $profileWorkflow ? 'profiles-v1-company-sale' : 'legacy-designations'], JSON_THROW_ON_ERROR),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
if ($action === OpportunityStatus::Submitted->value) {
|
||||
|
||||
@@ -26,7 +26,7 @@ class InvestmentCatalogue
|
||||
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
|
||||
'zee_id' => ['nullable', 'uuid'], 'zfi_id' => ['nullable', 'uuid'], 'park_id' => ['nullable', 'uuid'],
|
||||
'dimension' => ['nullable', 'in:cluster,corridor,zee,zfi'], 'view' => ['nullable', 'in:grid,list,map,combined'],
|
||||
'maturity_level' => ['nullable', 'integer', 'between:1,6'], 'facets' => ['nullable', 'array', 'max:20'], 'facets.*' => ['integer', 'min:1'],
|
||||
'maturity_level' => ['nullable', 'integer', 'between:1,8'], 'facets' => ['nullable', 'array', 'max:20'], 'facets.*' => ['integer', 'min:1'],
|
||||
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
||||
'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])],
|
||||
'currency' => ['nullable', 'required_with:min_amount,max_amount', 'in:MZN,USD,EUR,ZAR'],
|
||||
@@ -179,7 +179,9 @@ class InvestmentCatalogue
|
||||
public function references(bool $management = false, array $territoryFilters = []): array
|
||||
{
|
||||
$result = ['options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
||||
'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'slug'])];
|
||||
'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'slug']),
|
||||
'maturityCatalogue' => ['version'=>OpportunityMaturity::VERSION, 'stages'=>OpportunityMaturity::STAGES,
|
||||
'legacyVersion'=>OpportunityMaturity::LEGACY, 'legacyLabels'=>OpportunityMaturity::LEGACY_LABELS]];
|
||||
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
||||
$query = DB::table($table)->whereNull('deleted_at');
|
||||
if (! $management) {
|
||||
|
||||
@@ -117,8 +117,14 @@ class InvestmentRelations
|
||||
/** @return array<string,mixed> */
|
||||
public function dossier(InvestmentDossier $dossier, bool $management = false): array
|
||||
{
|
||||
$sourceEvidence = [];
|
||||
if ($dossier->project_id) {
|
||||
$sourceEvidence = app(InvestmentTerritorialTraceability::class)->sources('projects', $dossier->project_id);
|
||||
} elseif ($dossier->cluster_id) {
|
||||
$sourceEvidence = app(InvestmentTerritorialTraceability::class)->sources('economic_clusters', $dossier->cluster_id);
|
||||
}
|
||||
$result = ['locations' => [], 'members' => [], 'clusters' => [], 'chainLinks' => [], 'chains' => [],
|
||||
'source_evidence' => app(InvestmentTerritorialTraceability::class)->sources($dossier->project_id ? 'projects' : 'economic_clusters', $dossier->project_id ?? $dossier->cluster_id ?? '')];
|
||||
'source_evidence' => $sourceEvidence];
|
||||
if ($dossier->project_id) {
|
||||
$result['locations'] = $this->projectLocations($dossier->project_id, $management);
|
||||
$memberships = $this->memberships()->where('cp.project_id', $dossier->project_id)->get(['cp.cluster_id', 'cp.role', 'cp.validation_status', 'cp.source_reference']);
|
||||
|
||||
@@ -125,6 +125,10 @@ final class InvestorPath
|
||||
$results = (int) $case->user_id === $actor->id ? ($path['results'] ?? []) : [];
|
||||
$next = collect($steps)->first(fn ($step) => $step['preparation_allowed'] && ! in_array($step['state'], ['completed', 'approved', 'waiting_external', 'submitted', 'reviewing'], true));
|
||||
|
||||
$landCase = (int) $case->user_id === $actor->id
|
||||
? \App\Models\LandAssistanceCase::where('user_id', $actor->id)->latest('updated_at')->get()
|
||||
->first(fn ($land) => ($land->payload['investor_path_case_id'] ?? null) === $id) : null;
|
||||
|
||||
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
|
||||
'journey_id' => $journey->id, 'definition_id' => $version->id, 'definition_version' => $version->version_no, 'source_sha256' => $definition['source_sha256'],
|
||||
'phases' => $definition['phases'], 'steps' => $steps, 'facts' => $facts, 'fact_reasons' => $path['fact_reasons'] ?? [],
|
||||
@@ -140,7 +144,8 @@ final class InvestorPath
|
||||
->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title']]),
|
||||
'tools' => ['simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '') : null,
|
||||
'desk' => '/balcao-virtual/dossiers/'.$id, 'guidance' => '/balcao-virtual/dossiers/'.$id.'/orientacao',
|
||||
'library' => '/documentos?context='.$id, 'opportunities' => '/oportunidades?context='.$id, 'territory' => '/zonas?context='.$id, 'partners' => '/parcerias/painel?context='.$id]];
|
||||
'library' => '/documentos?context='.$id, 'opportunities' => '/oportunidades?context='.$id, 'territory' => '/zonas?context='.$id, 'partners' => '/parcerias/painel?context='.$id,
|
||||
'land' => (int) $case->user_id === $actor->id ? ($landCase ? '/investidor/terra-duat/'.$landCase->id : '/investidor/terra-duat/novo?context='.$id) : null]];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
|
||||
@@ -148,24 +148,64 @@ class OpportunityCanonicalContract
|
||||
$data = $this->schemaData($payload, $schema['$defs']['opportunityCreate'], $schema['$defs']);
|
||||
$result = $validator->validate($data, json_decode(json_encode($schema, JSON_THROW_ON_ERROR)));
|
||||
if ($error = $result->error()) {
|
||||
$errors = [];
|
||||
foreach ((new ErrorFormatter)->format($error) as $path => $messages) {
|
||||
$errors['canonical'.str_replace('/', '.', $path)] = $messages;
|
||||
throw ValidationException::withMessages($this->schemaValidationErrors($error));
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,list<string>> */
|
||||
private function schemaValidationErrors(ValidationError $error): array
|
||||
{
|
||||
$errors = [];
|
||||
$formatter = new ErrorFormatter;
|
||||
$collect = function (ValidationError $node) use (&$collect, &$errors, $formatter): void {
|
||||
if ($node->subErrors() !== []) {
|
||||
foreach ($node->subErrors() as $child) {
|
||||
$collect($child);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
$required = function (ValidationError $node) use (&$required, &$errors): void {
|
||||
if ($node->keyword() === 'required') {
|
||||
$prefix = 'canonical.'.implode('.', $node->data()->fullPath());
|
||||
foreach ($node->args()['missing'] ?? [] as $field) {
|
||||
$errors[rtrim($prefix, '.').'.'.$field] = ['Preencha este campo antes de submeter.'];
|
||||
$prefix = rtrim('canonical.'.implode('.', $node->data()->fullPath()), '.');
|
||||
$args = $node->args();
|
||||
if ($node->keyword() === 'required') {
|
||||
foreach ($args['missing'] ?? [] as $field) {
|
||||
$errors[$prefix.'.'.$field][] = 'Preencha este campo antes de submeter.';
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
if ($node->keyword() === 'additionalProperties') {
|
||||
$definition = $node->schema()->info()->data();
|
||||
$declared = is_object($definition) ? (array) ($definition->properties ?? []) : [];
|
||||
foreach ($args['properties'] ?? [] as $field) {
|
||||
// Opis can report declared properties as unchecked after a sibling field fails.
|
||||
// Keep real unknown-property errors without turning valid fields into errors.
|
||||
if (! array_key_exists($field, $declared)) {
|
||||
$errors[$prefix.'.'.$field][] = 'Campo não previsto no contrato desta categoria.';
|
||||
}
|
||||
}
|
||||
foreach ($node->subErrors() as $child) {
|
||||
$required($child);
|
||||
}
|
||||
};
|
||||
$required($error);
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
if ($node->keyword() === 'minLength') {
|
||||
$errors[$prefix][] = 'Preencha este campo com pelo menos '.$args['min'].' caracteres; tem '.$args['length'].'.';
|
||||
|
||||
return;
|
||||
}
|
||||
if ($node->keyword() === 'maxLength') {
|
||||
$errors[$prefix][] = 'Este campo admite até '.$args['max'].' caracteres; tem '.$args['length'].'.';
|
||||
|
||||
return;
|
||||
}
|
||||
foreach ($formatter->format($node) as $path => $messages) {
|
||||
$key = rtrim('canonical'.str_replace('/', '.', $path), '.');
|
||||
$errors[$key] = array_values(array_unique([...($errors[$key] ?? []), ...$messages]));
|
||||
}
|
||||
};
|
||||
$collect($error);
|
||||
|
||||
// Formatting must never make an invalid schema result acceptable.
|
||||
return $errors ?: ['canonical' => ['Não foi possível validar o contrato. Reveja os campos preenchidos.']];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $node
|
||||
@@ -246,6 +286,13 @@ class OpportunityCanonicalContract
|
||||
}
|
||||
} else {
|
||||
$location = $row->payload;
|
||||
// §10.2 area/unit consistency applies at submission. Resource drafts may
|
||||
// retain incomplete measurements; never invent a unit or convert values.
|
||||
$hasArea = isset($location['area_value']);
|
||||
$hasUnit = isset($location['area_unit']) && $location['area_unit'] !== '';
|
||||
$check(! $hasArea || $hasUnit, "locations.$index.area_unit", 'Indique a unidade da área antes de submeter; a preparação incompleta continua guardada nos recursos.');
|
||||
$check(! $hasUnit || $hasArea, "locations.$index.area_value", 'Indique o valor da área antes de submeter; a unidade não determina o valor.');
|
||||
$check(! $hasUnit || in_array($location['area_unit'], OpportunityResources::AREA_UNITS, true), "locations.$index.area_unit", 'Use uma unidade do catálogo existente: sqm, ha ou sqkm.');
|
||||
$check(! empty($location['district_id']) && ! empty($location['role']) && array_key_exists('is_primary', $location), "locations.$index", 'Localização requer distrito, papel e indicação de principal.');
|
||||
app(InvestmentGeography::class)->selection($location, true);
|
||||
$country = $location['country_code'] ?? null;
|
||||
@@ -492,10 +539,13 @@ class OpportunityCanonicalContract
|
||||
->orWhereExists(fn ($i) => $i->selectRaw('1')->from('investor_contacts as ic')->join('investors as inv', 'inv.id', '=', 'ic.investor_id')->whereColumn('ic.contact_id', 'contacts.id')->whereIn('inv.organization_id', $orgs)->whereNull('inv.deleted_at'));
|
||||
})->get(['id', 'full_name']);
|
||||
|
||||
$submissionProperties = $this->schema(false)['$defs']['opportunityCreate']['properties'];
|
||||
|
||||
return ['version' => self::VERSION, 'modularProfiles' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::PROFILES : [],
|
||||
'historyVersion' => app(OpportunityModularProfiles::class)->enabled() ? OpportunityModularProfiles::HISTORY_VERSION : null,
|
||||
'schema' => $this->schema(true)['$defs']['opportunityCreate'],
|
||||
'definitions' => $this->schema(true)['$defs'],
|
||||
'submissionTextLimits' => ['demand_statement' => array_intersect_key($submissionProperties['demand_statement'], array_flip(['minLength', 'maxLength']))],
|
||||
'activities' => DB::table('economic_activities')->where('status', 'published')->get(['id', 'parent_id', 'sector_id', 'label_pt_mz', 'catalog_version_id']),
|
||||
'contacts' => $contacts, 'contactInvestors' => $record?->organization_id ? DB::table('investors')->where('organization_id', $record->organization_id)->whereNull('deleted_at')->whereIn('status', ['prospect', 'active'])->get(['id', 'legal_name']) : [],
|
||||
'countries' => app(CountryCatalogue::class)->all(),
|
||||
|
||||
@@ -82,6 +82,9 @@ class OpportunityCategoryFields
|
||||
$lr['community_consultation'] = $this->object(['status' => $s, 'minutes_document_id' => $d, 'participants' => $strings, 'map_document_id' => $d, 'commitments' => $s, 'date' => $date], ['status', 'minutes_document_id', 'participants', 'map_document_id', 'commitments', 'date']);
|
||||
$lr['consideration'] = $this->object(['object' => ['enum' => ['improvements', 'assets', 'operation', 'partnership']], 'amount' => $n, 'currency' => ['type' => 'string', 'pattern' => '^[A-Z]{3}$']], ['object', 'amount', 'currency']);
|
||||
$lr += ['holder_document_id' => $d, 'communities_affected' => $bool, 'exploitation_plan_required' => $bool];
|
||||
// Explicit optional unit of the parcel's existing area. Older versions stay unknown;
|
||||
// do not assign the location's unit or convert the recorded numeric area.
|
||||
$defs['parcelCreate']['properties']['area_unit'] = ['enum' => [...OpportunityResources::AREA_UNITS, null]];
|
||||
$defs['landRightsCreate']['required'] = [...$defs['landRightsCreate']['required'], 'holder_document_id', 'communities_affected', 'exploitation_plan_required'];
|
||||
$bt = &$defs['businessTransactionCreate']['properties'];
|
||||
$bt['valuation'] = $valuation;
|
||||
|
||||
@@ -20,6 +20,14 @@ class OpportunityContacts
|
||||
$record = Opportunity::withTrashed()->findOrFail($id);
|
||||
$access->authorize($actor, 'edit', $record);
|
||||
abort_unless($access->mfa($actor), 403, 'Confirme a autenticação multifator nesta sessão.');
|
||||
// Validate the persisted form of names/email, rather than padding.
|
||||
// Non-string input stays with the validator and cannot cause a TypeError.
|
||||
if (is_string($input['full_name'] ?? null)) {
|
||||
$input['full_name'] = trim(preg_replace('/\s+/u', ' ', $input['full_name']));
|
||||
}
|
||||
if (is_string($input['email'] ?? null)) {
|
||||
$input['email'] = strtolower(trim($input['email']));
|
||||
}
|
||||
$data = Validator::make($input, [
|
||||
'etag' => 'required|string|size:64',
|
||||
'full_name' => 'required|string|min:2|max:150',
|
||||
@@ -28,8 +36,6 @@ class OpportunityContacts
|
||||
'investor_id' => 'nullable|uuid',
|
||||
'investor_type' => ['nullable', Rule::in(['domestic', 'foreign', 'institutional', 'individual'])],
|
||||
])->validate();
|
||||
$data['email'] = strtolower(trim($data['email']));
|
||||
$data['full_name'] = trim(preg_replace('/\s+/u', ' ', $data['full_name']));
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data, $access) {
|
||||
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
|
||||
@@ -11,6 +11,8 @@ use Illuminate\Validation\ValidationException;
|
||||
|
||||
class OpportunityProfileWorkflow
|
||||
{
|
||||
private const PROMOTER_ACTIONS = ['submit', 'request_archive', 'appeal', 'request_revision'];
|
||||
|
||||
public function __construct(private PortalProfileAccess $access, private OpportunityManagement $management,
|
||||
private OpportunityCanonicalContract $contract, private OpportunityWorkflowTasks $tasks) {}
|
||||
|
||||
@@ -38,7 +40,9 @@ class OpportunityProfileWorkflow
|
||||
$actions[] = 'appeal';
|
||||
}
|
||||
}
|
||||
if ($this->access->mfa($actor) && ! $this->access->conflict($actor, $record)) {
|
||||
// List scoped capabilities; the page disables execution until MFA is fresh.
|
||||
// authorizeAction still verifies MFA for every review/publication request.
|
||||
if (! $this->access->conflict($actor, $record)) {
|
||||
if ($this->access->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category) && $this->access->operational($actor, 'validate', $record->id)) {
|
||||
if ($state === 'approved' && count(array_filter($record->workflow_context['conditions'] ?? [], fn ($condition) => $condition['status'] === 'open' && $condition['blocking_action'] === 'publish')) > 0) {
|
||||
$actions[] = 'review_gate';
|
||||
@@ -90,6 +94,12 @@ class OpportunityProfileWorkflow
|
||||
return $actions;
|
||||
}
|
||||
|
||||
public function reauthenticationRequired(User $actor, Opportunity $record): bool
|
||||
{
|
||||
return ! $this->access->mfa($actor)
|
||||
&& array_diff($this->actions($actor, $record), self::PROMOTER_ACTIONS) !== [];
|
||||
}
|
||||
|
||||
/** Scoped names/IDs only; no secrets or implicit assignees.
|
||||
* @return array<string,mixed> */
|
||||
public function participants(User $actor, Opportunity $record): array
|
||||
@@ -317,7 +327,9 @@ class OpportunityProfileWorkflow
|
||||
abort_unless(in_array($p['business_transaction']['due_diligence_status'], ['data_room_ready', 'in_progress', 'completed', 'exceptions'], true), 422, 'Data room mínimo não preparado.');
|
||||
}
|
||||
if (isset($context['publication'])) {
|
||||
$context['publication_history'][] = $context['publication'];
|
||||
$context['publication_history'][] = [...$context['publication'],
|
||||
'public_maturity_before_republication' => ['level' => $record->maturity_level, 'label' => $record->maturity_label,
|
||||
'catalogue_version' => $context['publication']['maturity']['catalogue_version'] ?? null]];
|
||||
}
|
||||
$context['publication'] = [...$decision, 'hash' => $snapshot['hash'], 'visibility' => $p['visibility'],
|
||||
'public_fields' => ['title', 'summary', 'description', 'sector_id', 'province', 'district']];
|
||||
@@ -327,6 +339,16 @@ class OpportunityProfileWorkflow
|
||||
$record->summary = $projection['summary'];
|
||||
$record->description = $projection['description'];
|
||||
$record->sector_id = $p['sector_id'];
|
||||
if (! empty($p['maturity_stage'])) {
|
||||
// Project only the explicitly selected, approved V2 stage.
|
||||
// Existing legacy positions/labels are retained in publication history.
|
||||
$maturity = app(OpportunityMaturity::class)->normalize(['maturity_stage' => $p['maturity_stage'],
|
||||
'maturity_catalogue_version' => OpportunityMaturity::VERSION]);
|
||||
$record->maturity_level = $maturity['maturity_level'];
|
||||
$record->maturity_label = $maturity['maturity_label'];
|
||||
$context['publication']['maturity'] = ['catalogue_version' => $maturity['maturity_catalogue_version'],
|
||||
'stage' => $maturity['maturity_stage'], 'level' => $maturity['maturity_level'], 'label' => $maturity['maturity_label']];
|
||||
}
|
||||
$locations = array_values(array_filter($snapshot['resources']['locations'], fn ($location) => $location['payload']['is_primary'] ?? false));
|
||||
$location = $locations[0]; // The contract requires exactly one primary location.
|
||||
$path = app(InvestmentGeography::class)->selection($location['payload'], true);
|
||||
@@ -475,13 +497,17 @@ class OpportunityProfileWorkflow
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
$promoter = $this->access->promoterRecordScope($actor, $record)
|
||||
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id);
|
||||
if (in_array($action, ['submit', 'request_archive', 'appeal', 'request_revision'], true)) {
|
||||
if (in_array($action, self::PROMOTER_ACTIONS, true)) {
|
||||
abort_unless($promoter && $this->access->operational($actor, 'edit', $record->id), 403);
|
||||
} else {
|
||||
$role = in_array($action, ['publish', 'assign_publication', 'suspend', 'archive'], true) ? 'publisher' : 'validator';
|
||||
$operation = $role === 'publisher' ? (in_array($action, ['publish', 'assign_publication'], true) ? 'publish' : 'archive') : 'validate';
|
||||
abort_unless($this->access->scoped($actor, $role, $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->mfa($actor) && $this->access->operational($actor, $operation, $record->id) && ! $this->access->conflict($actor, $record), 403, 'Papel, MFA e independência necessários.');
|
||||
$eligible = $this->access->scoped($actor, $role, $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->operational($actor, $operation, $record->id) && ! $this->access->conflict($actor, $record);
|
||||
if ($eligible && ! $this->access->mfa($actor)) {
|
||||
abort(403, 'A confirmação MFA desta janela precisa de renovação. Entre novamente nesta janela com o seu autenticador; os dados já guardados foram preservados.', ['X-Portal-Reauthentication' => 'required']);
|
||||
}
|
||||
abort_unless($eligible && $this->access->mfa($actor), 403, 'Papel, MFA e independência necessários.');
|
||||
if ($action === 'publish') {
|
||||
abort_if((int) ($record->workflow_context['approval']['actor_id'] ?? 0) === $actor->id, 403, 'O aprovador não publica a mesma versão.');
|
||||
abort_if(isset($record->workflow_context['publication_assignment']['assignee_user_id']) && (int) $record->workflow_context['publication_assignment']['assignee_user_id'] !== $actor->id, 403, 'Publicação atribuída a outro Publicador; requer reatribuição explícita.');
|
||||
|
||||
@@ -20,6 +20,9 @@ class OpportunityResources
|
||||
{
|
||||
public const KINDS = ['documents', 'images', 'locations'];
|
||||
|
||||
// Existing §10.2 catalogue; shared with the compatibility editor, no inferred conversions.
|
||||
public const AREA_UNITS = ['sqm', 'ha', 'sqkm'];
|
||||
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasTable('opportunity_images');
|
||||
@@ -213,7 +216,7 @@ class OpportunityResources
|
||||
$rules = ['title' => 'nullable|string|max:120', 'source_reference' => 'nullable|string|max:2000', 'source_date' => 'nullable|date_format:Y-m-d', 'visibility' => 'nullable|in:internal,authenticated,public'];
|
||||
if ($kind === 'locations') {
|
||||
$rules += ['country_code' => ['nullable', app(CountryCatalogue::class)->rule()]];
|
||||
$rules += ['province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid', 'role' => 'nullable|in:headquarters,production,raw_material,storage,logistics,market,support,other', 'role_description' => 'nullable|string|max:1000', 'operational_unit' => 'nullable|string|max:120', 'is_primary' => 'nullable|boolean', 'address' => 'nullable|string|max:300', 'geometry' => 'nullable|array', 'area_value' => 'nullable|numeric|gt:0', 'area_unit' => 'nullable|in:sqm,ha,sqkm', 'allocation_percentage' => 'nullable|numeric|between:0,100', 'territorial_purpose' => 'nullable|in:implementation,context,impact,coverage', 'multi_district_rationale' => 'nullable|string|max:1000'];
|
||||
$rules += ['province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid', 'role' => 'nullable|in:headquarters,production,raw_material,storage,logistics,market,support,other', 'role_description' => 'nullable|string|max:1000', 'operational_unit' => 'nullable|string|max:120', 'is_primary' => 'nullable|boolean', 'address' => 'nullable|string|max:300', 'geometry' => 'nullable|array', 'area_value' => 'nullable|numeric|gt:0', 'area_unit' => ['nullable', Rule::in(self::AREA_UNITS)], 'allocation_percentage' => 'nullable|numeric|between:0,100', 'territorial_purpose' => 'nullable|in:implementation,context,impact,coverage', 'multi_district_rationale' => 'nullable|string|max:1000'];
|
||||
} elseif ($kind === 'images') {
|
||||
$rules += ['role' => 'nullable|in:cover,gallery,location,asset,product,plan,rendering,evidence,other', 'role_description' => 'nullable|string|max:1000', 'is_cover' => 'nullable|boolean', 'caption' => 'nullable|string|max:300', 'alt_text' => 'nullable|string|max:250', 'location_id' => ['nullable', 'uuid', Rule::exists('opportunity_location_drafts', 'id')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')], 'captured_at' => 'nullable|date_format:Y-m-d|before_or_equal:today', 'author_source' => 'nullable|string|max:150', 'rights_status' => 'nullable|in:owned,licensed,authorized,public_domain', 'rights_document_id' => ['nullable', 'uuid', Rule::exists('opportunity_documents', 'id')->where('opportunity_id', $opportunityId)->whereNull('deleted_at')], 'rights_valid_until' => 'nullable|date_format:Y-m-d', 'sort_order' => 'nullable|integer|min:0'];
|
||||
} else {
|
||||
|
||||
@@ -7,13 +7,16 @@ use Illuminate\Support\Arr;
|
||||
/** §28.1: preserve signed decisions; only changed review scopes need new decisions. */
|
||||
class OpportunityReviewMateriality
|
||||
{
|
||||
public const VERSION = 'review-scopes-20261011-v3';
|
||||
public const VERSION = 'review-scopes-20261012-v4';
|
||||
|
||||
// Preserve the projections used by earlier signed reviews.
|
||||
public const BEFORE_FRANCHISE_FINANCE_VERSION = 'review-scopes-20261011-v3';
|
||||
|
||||
public const PREVIOUS_VERSION = 'review-scopes-20261011-v2';
|
||||
|
||||
/** @param array<string,mixed> $snapshot
|
||||
* @return array<string,mixed> */
|
||||
private function scope(array $snapshot, string $gate, bool $extended = true): array
|
||||
private function scope(array $snapshot, string $gate, bool $extended = true, bool $franchiseFinance = true): array
|
||||
{
|
||||
$p = $snapshot['payload'] ?? [];
|
||||
$common = ['opportunity_category', 'promoter_id', 'promoter_type', 'sector_id', 'subsector_id', 'economic_activity_id', 'demand_statement', 'executive_summary'];
|
||||
@@ -49,6 +52,11 @@ class OpportunityReviewMateriality
|
||||
default => [],
|
||||
}];
|
||||
}
|
||||
if ($franchiseFinance && $gate === 'financial_review' && ($p['opportunity_category'] ?? '') === 'franchise') {
|
||||
// Existing canonical monetary obligations affect the existing financial review.
|
||||
// No rates, calculations, reviewers or external decisions are introduced here.
|
||||
$fields = [...$fields, 'business_transaction.franchise_terms.initial_fee', 'business_transaction.franchise_terms.royalties'];
|
||||
}
|
||||
$data = [];
|
||||
foreach ([...$common, ...$fields] as $field) {
|
||||
if (! is_string($field)) {
|
||||
@@ -88,8 +96,10 @@ class OpportunityReviewMateriality
|
||||
* @param array<string,mixed> $review */
|
||||
public function hash(array $snapshot, string $gate, array $review = [], bool $legacy = false, ?string $rule = null): string
|
||||
{
|
||||
$extended = ! $legacy && ($rule ?? self::VERSION) !== self::PREVIOUS_VERSION;
|
||||
$data = $this->scope($snapshot, $gate, $extended);
|
||||
$effectiveRule = $rule ?? self::VERSION;
|
||||
$extended = ! $legacy && $effectiveRule !== self::PREVIOUS_VERSION;
|
||||
$franchiseFinance = ! $legacy && ! in_array($effectiveRule, [self::PREVIOUS_VERSION, self::BEFORE_FRANCHISE_FINANCE_VERSION], true);
|
||||
$data = $this->scope($snapshot, $gate, $extended, $franchiseFinance);
|
||||
$locationGates = ['registry_urban_review', 'cadastral_screening', 'legal_territorial_review', 'property_review'];
|
||||
if (! $legacy) {
|
||||
$locationGates = [...$locationGates, 'land_legal_review', 'community_environment_review', 'competent_authority_clearance'];
|
||||
@@ -130,7 +140,7 @@ class OpportunityReviewMateriality
|
||||
return true; // Caller must independently verify the original signed submission hash.
|
||||
}
|
||||
$rule = $review['scope_rule'] ?? '';
|
||||
$legacy = ! in_array($rule, [self::VERSION, self::PREVIOUS_VERSION], true);
|
||||
$legacy = ! in_array($rule, [self::VERSION, self::PREVIOUS_VERSION, self::BEFORE_FRANCHISE_FINANCE_VERSION], true);
|
||||
$expected = $this->hash($snapshot, $gate, $review, $legacy, $rule);
|
||||
|
||||
return hash_equals($review['scope_hash'], $expected);
|
||||
|
||||
Reference in New Issue
Block a user