+500
@@ -0,0 +1,500 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Opis\JsonSchema\CompliantValidator;
|
||||
use Opis\JsonSchema\Errors\ErrorFormatter;
|
||||
use Opis\JsonSchema\Errors\ValidationError;
|
||||
|
||||
/** Explicit adapter of §25/26 to existing IDs and resource collections; never renumbers records. */
|
||||
class OpportunityCanonicalContract
|
||||
{
|
||||
public const BASE_CATEGORIES = ['investment_project', 'real_estate', 'land_rights', 'business_sale', 'business_partnership', 'franchise'];
|
||||
|
||||
/** Availability of this bounded base-category delivery, without rewriting existing contracts/data. */
|
||||
public function deliveryBlockers(array $payload): array
|
||||
{
|
||||
$errors = [];
|
||||
if (! in_array($payload['opportunity_category'] ?? '', self::BASE_CATEGORIES, true) && ! app(OpportunityModularProfiles::class)->enabled()) {
|
||||
$errors['canonical.opportunity_category'] = 'Categoria fora desta entrega: concessão, financiamento, fornecimento e outros permanecem indisponíveis. Os registos anteriores são preservados.';
|
||||
}
|
||||
if (($payload['opportunity_category'] ?? '') === 'real_estate') {
|
||||
$property = $payload['real_estate'] ?? [];
|
||||
foreach (['construction_status' => ['completed'], 'occupancy_status' => ['vacant'], 'transaction_type' => ['sale', 'lease']] as $field => $values) {
|
||||
if (! empty($property[$field]) && ! in_array($property[$field], $values, true)) {
|
||||
$errors['canonical.real_estate.'.$field] = 'Variante indisponível para submissão nesta entrega. Pode guardar e recuperar a preparação; estão incluídas venda e arrendamento de imóvel concluído e desocupado.';
|
||||
}
|
||||
}
|
||||
if (array_filter($property['encumbrances'] ?? [], fn ($row) => ! empty($row['type']) && $row['type'] !== 'none')) {
|
||||
$errors['canonical.real_estate.encumbrances'] = 'Imóvel com encargos: pode preparar e guardar; a submissão deste ramo não está incluída nesta entrega.';
|
||||
}
|
||||
if (! empty($property['max_built_area']) || ! empty($property['urban_limit_document_id'])) {
|
||||
$errors['canonical.real_estate.max_built_area'] = 'Limitações urbanísticas adicionais: preparação disponível; este ramo de submissão aguarda demonstração própria.';
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
public const VERSION = 'opportunity-canonical-adapter-20261010-semantic1';
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function schema(bool $draft = false): array
|
||||
{
|
||||
$bytes = file_get_contents(resource_path('data/investmoz-opportunity-modular.schema.json'));
|
||||
if ($bytes === false) {
|
||||
throw new \RuntimeException('Opportunity schema unavailable.');
|
||||
}
|
||||
$schema = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
// The original conditions were omitted from the extracted Create/Patch definitions.
|
||||
foreach (['opportunity', 'realEstate', 'landRights', 'businessTransaction'] as $name) {
|
||||
$schema['$defs'][$name.'Create']['allOf'] = $schema['$defs'][$name]['allOf'] ?? [];
|
||||
}
|
||||
$schema = app(OpportunityCategoryFields::class)->enrich($schema);
|
||||
$schema = app(OpportunityModularProfiles::class)->extend($schema);
|
||||
$schema = $this->writeSchema($schema, $draft);
|
||||
$properties = &$schema['$defs']['opportunityCreate']['properties'];
|
||||
unset($properties['mutation_context']); // Actor, audit reason and revision are server-owned.
|
||||
$properties['sector_id'] = ['type' => 'integer', 'minimum' => 1];
|
||||
$properties['promoter_id'] = ['type' => ['string', 'integer']];
|
||||
// References point to the existing collections; their metadata is recovered on the server.
|
||||
foreach (['locations', 'documents', 'images'] as $field) {
|
||||
$properties[$field]['items'] = ['type' => 'string', 'format' => 'uuid'];
|
||||
}
|
||||
$properties['evidences'] = ['type' => 'array', 'items' => ['$ref' => '#/$defs/evidenceCreate']];
|
||||
if (! $draft) {
|
||||
$properties['evidences']['minItems'] = 1;
|
||||
}
|
||||
$properties['evidences']['items'] = ['type' => 'object', 'additionalProperties' => false,
|
||||
'properties' => ['title' => ['type' => 'string'], 'evidence_type' => ['type' => 'string'],
|
||||
'document_id' => ['type' => 'string', 'format' => 'uuid'], 'description' => ['type' => 'string']],
|
||||
...($draft ? [] : ['required' => ['title', 'evidence_type', 'document_id']])];
|
||||
$schema['$ref'] = '#/$defs/opportunityCreate';
|
||||
$schema['$id'] = 'urn:investmoz:'.self::VERSION.($draft ? ':draft' : ':submit');
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $node
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function writeSchema(array $node, bool $draft): array
|
||||
{
|
||||
if (isset($node['$ref']) && preg_match('~^#/\$defs/(.+)$~', $node['$ref'], $match)) {
|
||||
// Collections in the normative Create still referenced response definitions.
|
||||
$defs = ['product', 'asset', 'input', 'market', 'impact', 'moneyItem', 'milestone', 'license', 'risk', 'relation', 'employment', 'environmentalSocial', 'localizedPublication', 'realEstate', 'landRights', 'businessTransaction', 'parcel', 'improvement', 'community'];
|
||||
if (in_array($match[1], $defs, true)) {
|
||||
$node['$ref'] .= 'Create';
|
||||
}
|
||||
}
|
||||
if ($draft) {
|
||||
unset($node['required'], $node['minItems'], $node['minProperties'], $node['contains'], $node['allOf']);
|
||||
if (isset($node['type'])) {
|
||||
$node['type'] = array_values(array_unique([...(array) $node['type'], 'null']));
|
||||
}
|
||||
if (isset($node['enum']) && ! in_array(null, $node['enum'], true)) {
|
||||
$node['enum'][] = null;
|
||||
}
|
||||
if (isset($node['minLength'])) {
|
||||
$node['minLength'] = 0;
|
||||
}
|
||||
if (($node['const'] ?? null) === true) {
|
||||
unset($node['const']);
|
||||
$node['type'] = 'boolean';
|
||||
}
|
||||
}
|
||||
foreach ($node as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
if (in_array($key, ['properties', '$defs'], true)) {
|
||||
foreach ($value as $name => $child) {
|
||||
$value[$name] = $this->writeSchema($child, $draft);
|
||||
}
|
||||
$node[$key] = $value;
|
||||
} elseif (in_array($key, ['items', 'if', 'then', 'else'], true)) {
|
||||
$node[$key] = $this->writeSchema($value, $draft);
|
||||
} elseif (in_array($key, ['allOf', 'oneOf', 'anyOf'], true)) {
|
||||
$node[$key] = array_map(fn ($child) => $this->writeSchema($child, $draft), $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $payload
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function draft(array $payload): array
|
||||
{
|
||||
abort_unless(config('portal.opportunity_specialized_drafts_enabled'), 422, 'Contrato especializado indisponível.');
|
||||
$this->validateSchema($payload, true);
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
private function validateSchema(array $payload, bool $draft): void
|
||||
{
|
||||
$schema = $this->schema($draft);
|
||||
$validator = new CompliantValidator(null, 100, false);
|
||||
$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;
|
||||
}
|
||||
$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.'];
|
||||
}
|
||||
}
|
||||
foreach ($node->subErrors() as $child) {
|
||||
$required($child);
|
||||
}
|
||||
};
|
||||
$required($error);
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $node
|
||||
* @param array<string,mixed> $defs
|
||||
*/
|
||||
private function schemaData(mixed $value, array $node, array $defs): mixed
|
||||
{
|
||||
if (isset($node['$ref'])) {
|
||||
$name = basename($node['$ref']);
|
||||
$node = $defs[$name] ?? $node;
|
||||
}
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (in_array('object', (array) ($node['type'] ?? []), true) || isset($node['properties'])) {
|
||||
$result = new \stdClass;
|
||||
foreach ($value as $key => $item) {
|
||||
$result->{$key} = $this->schemaData($item, $node['properties'][$key] ?? [], $defs);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
return array_map(fn ($item) => $this->schemaData($item, $node['items'] ?? [], $defs), $value);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function validateSubmission(Opportunity $record): array
|
||||
{
|
||||
$values = app(OpportunityManagement::class)->values($record);
|
||||
$payload = $values['canonical'] ?? [];
|
||||
$this->validateSchema($payload, false);
|
||||
$errors = [];
|
||||
$check = function (bool $valid, string $path, string $message) use (&$errors): void {
|
||||
if (! $valid) {
|
||||
$errors['canonical.'.$path] = $message;
|
||||
}
|
||||
};
|
||||
$check(($payload['opportunity_category'] ?? null) === $record->opportunity_category, 'opportunity_category', 'A categoria deve coincidir com o registo e a autorização.');
|
||||
$check(($payload['promoter_id'] ?? null) === ($record->organization_id ?? (int) $record->owner_user_id), 'promoter_id', 'Use a organização representada ou o autor individual; não outra identidade.');
|
||||
$sector = DB::table('sectors')->where('id', $payload['sector_id'])->whereNull('deleted_at')->where('is_active', true)->first();
|
||||
$subsector = DB::table('economic_activities')->where('id', $payload['subsector_id'])->where('status', 'published')->first();
|
||||
$activity = DB::table('economic_activities')->where('id', $payload['economic_activity_id'])->where('status', 'published')->first();
|
||||
$root = $subsector?->parent_id ? DB::table('economic_activities')->where('id', $subsector->parent_id)->where('status', 'published')->first() : null;
|
||||
$check($sector !== null && $root !== null && (int) $root->sector_id === (int) $sector->id
|
||||
&& $activity !== null && $activity->parent_id === $subsector->id && $activity->catalog_version_id === $root->catalog_version_id,
|
||||
'economic_activity_id', 'Sector → subsector → atividade requer referências publicadas da mesma versão e hierarquia.');
|
||||
foreach (['internal_contact_id', 'public_contact_id'] as $field) {
|
||||
if (! empty($payload[$field])) {
|
||||
$contacts = DB::table('contacts')->where('contacts.id', $payload[$field])->whereNull('contacts.deleted_at');
|
||||
if ($record->organization_id) {
|
||||
$contacts->whereExists(fn ($q) => $q->selectRaw('1')->from('investor_contacts as ic')->join('investors as i', 'i.id', '=', 'ic.investor_id')
|
||||
->whereColumn('ic.contact_id', 'contacts.id')->where('i.organization_id', $record->organization_id)->whereNull('i.deleted_at'));
|
||||
} else {
|
||||
$contacts->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$record->owner_user_id);
|
||||
}
|
||||
$check($contacts->exists(), $field, 'Contacto inexistente ou sem relação com o Promotor.');
|
||||
}
|
||||
}
|
||||
$resources = [];
|
||||
foreach (['locations', 'documents', 'images'] as $kind) {
|
||||
$table = app(OpportunityResources::class)->table($kind);
|
||||
foreach ($payload[$kind] ?? [] as $index => $id) {
|
||||
$row = DB::table($table)->where('id', $id)->where('opportunity_id', $record->id)->whereNull('deleted_at')->first();
|
||||
$check($row !== null, "$kind.$index", 'Recurso inexistente, eliminado ou de outra oportunidade.');
|
||||
if (! $row) {
|
||||
continue;
|
||||
}
|
||||
$row->payload = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($kind !== 'locations') {
|
||||
$file = DB::table('documents')->where('id', $row->document_id)->first();
|
||||
$check($file !== null && $file->deleted_at === null && $file->status === 'active' && $file->malware_scan_status === 'clean'
|
||||
&& hash_equals(trim($file->sha256), trim((string) $file->malware_scanned_sha256)), "$kind.$index", 'Original ativo com análise antimalware correspondente obrigatória.');
|
||||
if ($file) {
|
||||
// Verify actual bytes/cipher integrity as well as the recorded scan hash.
|
||||
app(VerifiedDocumentBinary::class)->respond($file);
|
||||
$row->sha256 = trim($file->sha256);
|
||||
}
|
||||
} else {
|
||||
$location = $row->payload;
|
||||
$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;
|
||||
$check($country === 'MZ', "locations.$index.country_code", 'A hierarquia administrativa moçambicana deve declarar MZ; outros países exigem localização própria.');
|
||||
}
|
||||
$resources[$kind][$id] = (array) $row;
|
||||
}
|
||||
}
|
||||
$locations = $resources['locations'] ?? [];
|
||||
$primary = array_filter($locations, fn ($l) => $l['payload']['is_primary'] ?? false);
|
||||
$check(count($primary) === 1, 'locations', 'Selecione exatamente uma localização principal.');
|
||||
$check($payload['location_mode'] !== 'single' || count($locations) === 1, 'location_mode', 'Modo single exige uma localização.');
|
||||
foreach ($payload['evidences'] as $i => $evidence) {
|
||||
$check(isset($resources['documents'][$evidence['document_id']]), "evidences.$i.document_id", 'Evidência deve usar um documento ativo desta oportunidade incluído no contrato.');
|
||||
}
|
||||
$this->categoryRules($payload, $record, $resources, $errors);
|
||||
app(OpportunityCategoryFields::class)->validate($payload, $record, $resources, $errors);
|
||||
if ($errors) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
ksort($payload);
|
||||
$snapshot = ['adapter_version' => self::VERSION, 'schema_sha256' => hash_file('sha256', resource_path('data/investmoz-opportunity-modular.schema.json')),
|
||||
'payload' => $payload, 'resources' => $resources];
|
||||
if (isset(OpportunityModularProfiles::PROFILES[$record->opportunity_category]) || ($payload['module_profile_version'] ?? '') === OpportunityModularProfiles::HISTORY_VERSION) {
|
||||
$snapshot['qa_extension'] = ['version' => OpportunityModularProfiles::VERSION, 'profile_version' => $payload['module_profile_version'],
|
||||
'functional_decision' => 'Experimental QA proposal; functional approval of modular contracts and SLA remains pending. Legacy integration authorization does not approve these modules.',
|
||||
'gates' => $this->gates($record)];
|
||||
if ($record->opportunity_category === 'other') {
|
||||
$snapshot['qa_extension']['subtype'] = config('portal.opportunity_other_qa_subtypes.'.($payload['module_details']['subtype'] ?? ''), []);
|
||||
}
|
||||
// A documentary correction must not rewrite the checksum of an already
|
||||
// signed, unchanged version. Its historical annotation is explicitly
|
||||
// reconciled by the read adapter; new/changed content uses the current note.
|
||||
$prior = $record->workflow_context['submission'] ?? [];
|
||||
if (isset($prior['qa_extension']) && ($prior['payload'] ?? null) == $snapshot['payload'] && ($prior['resources'] ?? null) == $snapshot['resources']) {
|
||||
$snapshot['qa_extension']['functional_decision'] = $prior['qa_extension']['functional_decision'];
|
||||
}
|
||||
}
|
||||
$snapshot['hash'] = hash('sha256', json_encode($snapshot, JSON_THROW_ON_ERROR));
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $p
|
||||
* @param array<string,mixed> $resources
|
||||
* @param array<string,string> $errors
|
||||
*/
|
||||
private function categoryRules(array $p, Opportunity $record, array $resources, array &$errors): void
|
||||
{
|
||||
$category = $p['opportunity_category'];
|
||||
app(OpportunityModularProfiles::class)->validate($p, $resources, $errors);
|
||||
foreach (['real_estate', 'land_rights', 'business_transaction'] as $module) {
|
||||
$applicable = match ($module) {
|
||||
'real_estate' => ['real_estate'], 'land_rights' => ['land_rights'], default => ['business_sale', 'business_partnership', 'franchise']
|
||||
};
|
||||
if (isset($p[$module]) && ! in_array($category, $applicable, true)) {
|
||||
$errors['canonical.'.$module] = 'Módulo incompatível com a categoria. Preserve-o noutra versão antes de mudar de categoria.';
|
||||
}
|
||||
}
|
||||
if ($category === 'investment_project') {
|
||||
$total = $p['total_investment'];
|
||||
$sum = array_sum(array_column($p['investment_breakdown'], 'amount'));
|
||||
$secured = array_sum(array_column($p['secured_financing'], 'amount'));
|
||||
if (abs($sum - $total) > 0.010001 || $secured > $total || abs($p['funding_sought'] - ($total - $secured)) > 0.010001) {
|
||||
$errors['canonical.investment_breakdown'] = 'Rubricas e financiamento devem reconciliar com o total (tolerância normativa 0,01).';
|
||||
}
|
||||
if (! in_array($p['maturity_stage'], array_keys(OpportunityMaturity::STAGES), true)) {
|
||||
$errors['canonical.maturity_stage'] = 'Use um código explícito do catálogo de oito etapas; não reinterpretar a escala histórica.';
|
||||
}
|
||||
foreach (['investment_breakdown', 'secured_financing'] as $field) {
|
||||
foreach ($p[$field] as $i => $amount) {
|
||||
if ($amount['currency'] !== $p['currency']) {
|
||||
$errors["canonical.$field.$i.currency"] = 'Moedas distintas requerem cenário/câmbio explícito; não somar valores de moedas diferentes.';
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($p['markets'] as $i => $market) {
|
||||
if (isset($market['country_code']) && Validator::make(['country' => $market['country_code']], ['country' => app(CountryCatalogue::class)->rule()])->fails()) {
|
||||
$errors["canonical.markets.$i.country_code"] = 'Use país do catálogo ISO existente.';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($category === 'real_estate') {
|
||||
$re = $p['real_estate'];
|
||||
if ($re['transaction_type'] === 'sale' && ($re['price'] ?? 0) <= 0) {
|
||||
$errors['canonical.real_estate.price'] = 'Venda exige preço positivo.';
|
||||
}
|
||||
if ($re['transaction_type'] === 'lease') {
|
||||
if (($re['rent'] ?? 0) <= 0) {
|
||||
$errors['canonical.real_estate.rent'] = 'Arrendamento exige renda positiva.';
|
||||
}
|
||||
if (empty($re['rent_periodicity'])) {
|
||||
$errors['canonical.real_estate.rent_periodicity'] = 'Indique a periodicidade da renda.';
|
||||
}
|
||||
}
|
||||
if (in_array($re['construction_status'], ['completed', 'occupied', 'renovation'], true) && empty($re['property_condition'])) {
|
||||
$errors['canonical.real_estate.property_condition'] = 'Imóvel existente exige condição identificada.';
|
||||
}
|
||||
if (in_array($re['construction_status'], ['planned', 'under_construction'], true) && empty($re['planning_permit_document_id'])) {
|
||||
$errors['canonical.real_estate.planning_permit_document_id'] = 'Estado construtivo exige licença de construção (§25.1).';
|
||||
}
|
||||
if (in_array($re['construction_status'], ['completed', 'occupied', 'renovation'], true) && empty($re['use_license_document_id'])) {
|
||||
$errors['canonical.real_estate.use_license_document_id'] = 'Imóvel existente exige licença de utilização aplicável (§25.1).';
|
||||
}
|
||||
foreach (['planning_permit_document_id', 'use_license_document_id'] as $field) {
|
||||
if (! empty($re[$field]) && ! isset($resources['documents'][$re[$field]])) {
|
||||
$errors['canonical.real_estate.'.$field] = 'Licença deve referir documento ativo desta oportunidade.';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($category === 'land_rights') {
|
||||
$land = $p['land_rights'];
|
||||
if (! empty($land['issuing_authority_id']) && ! DB::table('authorities')->where('id', $land['issuing_authority_id'])->where('status', 'published')->exists()) {
|
||||
$errors['canonical.land_rights.issuing_authority_id'] = 'Entidade emissora deve usar autoridade canónica publicada.';
|
||||
}
|
||||
if (! empty($land['issue_date']) && ($land['issue_date'] > today()->toDateString() || (! empty($land['expiry_date']) && $land['expiry_date'] <= $land['issue_date']))) {
|
||||
$errors['canonical.land_rights.issue_date'] = 'Emissão não futura e validade posterior à emissão.';
|
||||
}
|
||||
foreach ($land['parcels'] as $i => $parcel) {
|
||||
if (! isset($resources['locations'][$parcel['location_id']])) {
|
||||
$errors["canonical.land_rights.parcels.$i.location_id"] = 'Parcela deve usar uma localização desta oportunidade.';
|
||||
}
|
||||
try {
|
||||
$g = DB::selectOne('SELECT ST_IsValid(g) AND NOT ST_IsEmpty(g) AND ST_GeometryType(g)=\'ST_MultiPolygon\' AND ST_XMin(Box3D(g))>=-180 AND ST_XMax(Box3D(g))<=180 AND ST_YMin(Box3D(g))>=-90 AND ST_YMax(Box3D(g))<=90 AS valid FROM (SELECT ST_SetSRID(ST_GeomFromGeoJSON(?),4326) g) s', [json_encode($parcel['geometry'])]);
|
||||
if (! $g?->valid) {
|
||||
throw new \RuntimeException;
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
$errors["canonical.land_rights.parcels.$i.geometry"] = 'Parcela requer MultiPolygon válido, não vazio, EPSG:4326; limite administrativo não é parcela.';
|
||||
}
|
||||
}
|
||||
if (in_array($land['duat_status'], ['provisional', 'definitive'], true) && empty($land['duat_number'])) {
|
||||
$errors['canonical.land_rights.duat_number'] = 'DUAT provisório/definitivo exige número e entidade emissora.';
|
||||
}
|
||||
}
|
||||
if (isset($p['business_transaction'])) {
|
||||
$business = $p['business_transaction'];
|
||||
if ($business['legal_entity_id'] !== $record->organization_id || ! DB::table('organizations')->where('id', $business['legal_entity_id'])->whereNull('deleted_at')->exists()) {
|
||||
$errors['canonical.business_transaction.legal_entity_id'] = 'Entidade ativa representada obrigatória.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $snapshot */
|
||||
public function validatePublication(array $snapshot): void
|
||||
{
|
||||
$p = $snapshot['payload'];
|
||||
$errors = [];
|
||||
app(OpportunityCategoryFields::class)->publication($p, $errors);
|
||||
app(OpportunityModularProfiles::class)->publication($p, $errors);
|
||||
foreach ($snapshot['resources']['documents'] ?? [] as $id => $document) {
|
||||
if (! empty($document['payload']['valid_until']) && $document['payload']['valid_until'] < today()->toDateString()) {
|
||||
$errors['documents.'.$id] = 'Documento incluído expirou; preserve o original e reveja a versão.';
|
||||
}
|
||||
}
|
||||
if ($p['opportunity_category'] === 'land_rights') {
|
||||
foreach ($p['land_rights']['required_authorizations'] as $i => $authorization) {
|
||||
if (! in_array($authorization['status'] ?? '', ['approved', 'not_required'], true)
|
||||
|| (($authorization['status'] ?? '') === 'approved' && ! isset($snapshot['resources']['documents'][$authorization['document_id'] ?? '']))) {
|
||||
$errors['land_rights.required_authorizations.'.$i] = 'Autorização externa pendente ou sem documento. Aprovação interna não substitui esse ato.';
|
||||
}
|
||||
}
|
||||
foreach ($p['land_rights']['overlaps_conflicts'] as $i => $conflict) {
|
||||
if (($conflict['type'] ?? '') !== 'none' && ($conflict['status'] ?? '') !== 'resolved') {
|
||||
$errors['land_rights.overlaps_conflicts.'.$i] = 'Conflito impeditivo deve ser resolvido com evidência antes de publicar.';
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($p['visibility'] === 'public') {
|
||||
$images = $snapshot['resources']['images'] ?? [];
|
||||
if (count(array_filter($images, fn ($image) => $image['payload']['is_cover'] ?? false)) !== 1) {
|
||||
$errors['images'] = 'Publicação pública exige uma capa explícita.';
|
||||
}
|
||||
foreach ($images as $id => $image) {
|
||||
$meta = $image['payload'];
|
||||
if (empty($meta['alt_text']) || empty($meta['caption']) || empty($meta['rights_status']) || empty($meta['derivatives'])
|
||||
|| (! empty($meta['rights_valid_until']) && $meta['rights_valid_until'] < today()->toDateString())) {
|
||||
$errors['images.'.$id] = 'Legenda, texto alternativo, direitos válidos e derivadas verificadas obrigatórios.';
|
||||
}
|
||||
foreach ($meta['derivatives'] ?? [] as $derived) {
|
||||
$file = DB::table('documents')->where('id', $derived['document_id'])->whereNull('deleted_at')->where('status', 'active')->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->first();
|
||||
if (! $file) {
|
||||
$errors['images.'.$id] = 'Scan de uma derivada ainda não demonstrado.';
|
||||
} else {
|
||||
app(VerifiedDocumentBinary::class)->respond($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($errors) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function gates(Opportunity $record): array
|
||||
{
|
||||
return match ($record->opportunity_category) {
|
||||
'investment_project' => ['technical_review', 'legal_territorial_review'],
|
||||
'real_estate' => ['property_review', 'registry_urban_review', 'building_compliance_review'],
|
||||
'land_rights' => ['cadastral_screening', 'land_legal_review', 'community_environment_review', 'competent_authority_clearance'],
|
||||
'business_sale' => ['corporate_screening', 'financial_review', 'legal_tax_due_diligence', 'confidentiality_clearance'],
|
||||
'business_partnership' => ['corporate_screening', 'financial_review', 'partnership_governance_review', 'legal_tax_due_diligence'],
|
||||
'franchise' => ['brand_license_review', 'financial_review', 'franchise_legal_review', 'confidentiality_clearance'],
|
||||
default => app(OpportunityModularProfiles::class)->gates($record),
|
||||
};
|
||||
}
|
||||
|
||||
/** Same exact projection for preview and publication; never expose private business analysis.
|
||||
* @param array<string,mixed> $payload
|
||||
* @return array{title:string,summary:string,description:string} */
|
||||
public function publicProjection(array $payload): array
|
||||
{
|
||||
$business = isset($payload['business_transaction']) && ($payload['visibility'] ?? '') === 'public';
|
||||
|
||||
$label = match ($payload['module_details']['mode'] ?? '') {
|
||||
'intention_call' => 'Intenção/chamada em preparação — não é direito atribuído. ',
|
||||
'awarded_right' => 'Concessão com ato competente documentado. ',
|
||||
'seeking_funding' => 'Procura de financiamento. ', 'funding_offer' => 'Oferta de financiamento — sujeita a análise do beneficiário. ',
|
||||
'purchase_request' => 'Pedido de compra. ', 'supply_offer' => 'Oferta de fornecimento. ', default => '',
|
||||
};
|
||||
if (($payload['module_details']['conditions_status'] ?? '') === 'proposed') {
|
||||
$label .= 'Valores e condições propostos, sem compromisso assumido. ';
|
||||
}
|
||||
|
||||
return ['title' => (string) ($payload['official_title'] ?? ''), 'summary' => Str::limit($label.(string) ($business ? ($payload['business_transaction']['teaser'] ?? '') : ($payload['executive_summary'] ?? '')), 499, '…'),
|
||||
'description' => (string) ($business ? ($payload['business_transaction']['teaser'] ?? '') : ($payload['demand_statement'] ?? ''))];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function options(User $actor, ?Opportunity $record): array
|
||||
{
|
||||
$orgs = array_values(array_unique(array_column(app(PortalProfileAccess::class)->navigation($actor)['contexts'] ?? [], 'organization_id')));
|
||||
if ($record?->organization_id) {
|
||||
$orgs = [$record->organization_id];
|
||||
}
|
||||
$contacts = DB::table('contacts')->whereNull('contacts.deleted_at')->where(function ($q) use ($orgs, $actor) {
|
||||
$q->where(fn ($own) => $own->where('source_system', 'portal-user-contact')->where('external_id', 'user:'.$actor->id))
|
||||
->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']);
|
||||
|
||||
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'],
|
||||
'activities' => DB::table('economic_activities')->where('status', 'published')->get(['id', 'parent_id', 'sector_id', 'label_pt_mz', 'catalog_version_id']),
|
||||
'contacts' => $contacts, 'countries' => app(CountryCatalogue::class)->all(),
|
||||
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
||||
'gates' => $record ? $this->gates($record) : [], 'resources' => $record ? array_combine(['locations', 'documents', 'images'], array_map(fn ($k) => array_values(array_filter(app(OpportunityResources::class)->listing($record->id, $k), fn ($row) => empty($row->deleted_at))), ['locations', 'documents', 'images'])) : []];
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Read adapter only: preserve persisted identifiers and make unresolved metadata explicit. */
|
||||
class OpportunityCanonicalResponse
|
||||
{
|
||||
public const VERSION = 'opportunity-response-existing-ids-20261011-4';
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function read(User $actor, Opportunity $record): array
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$access->authorize($actor, 'view', $record);
|
||||
$payload = app(OpportunityManagement::class)->values($record)['canonical'] ?? [];
|
||||
$context = $record->workflow_context ?? [];
|
||||
$data = [...app(OpportunityCanonicalMetadata::class)->project($payload, $context['canonical_items'] ?? []), 'id' => $record->id, 'opportunity_code' => $record->reference,
|
||||
'opportunity_category' => $record->opportunity_category, 'status' => $access->state($record),
|
||||
'version' => (int) $record->management_version, 'is_deleted' => $record->trashed(),
|
||||
'deleted_at' => $record->deleted_at?->toIso8601String(), ...$this->rootMetadata($record)];
|
||||
foreach (['submitted' => 'submission', 'approved' => 'approval', 'published' => 'publication', 'archived' => 'archive'] as $prefix => $key) {
|
||||
$data[$prefix.'_by'] = $context[$key]['actor_id'] ?? null;
|
||||
$data[$prefix.'_at'] = $context[$key]['at'] ?? null;
|
||||
}
|
||||
$completion = app(OpportunityCompleteness::class)->calculate($payload);
|
||||
$data['completion_percentage'] = $completion['percentage'];
|
||||
$errors = [];
|
||||
try {
|
||||
app(OpportunityCanonicalContract::class)->validateSubmission($record);
|
||||
} catch (ValidationException $failure) {
|
||||
$errors = $failure->errors();
|
||||
} catch (HttpExceptionInterface $failure) {
|
||||
$errors = ['canonical.resources' => ['Recurso indisponível para validação; estado HTTP '.$failure->getStatusCode().'. Preserve o original e resolva a operação afetada.']];
|
||||
}
|
||||
$data['validation_result'] = ['errors' => $errors, 'warnings' => [], 'rule' => OpportunityCanonicalContract::VERSION,
|
||||
'evaluated_at' => now()->toIso8601String(), 'persisted_submission_hash' => $context['submission']['hash'] ?? null,
|
||||
'external_decision' => 'not_inferred'];
|
||||
$mutations = [];
|
||||
foreach (DB::table('audit_events')->where('source_system', 'opportunity-resources')->where('after_data->opportunity_id', $record->id)->orderBy('occurred_at')->orderBy('id')->get(['actor_user_id', 'action', 'occurred_at', 'after_data']) as $event) {
|
||||
$detail = json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
$mutations[$detail['resource_id']][] = ['actor' => $event->actor_user_id, 'action' => $event->action, 'at' => $event->occurred_at, 'reason' => $detail['reason'] ?? null];
|
||||
}
|
||||
$references = [];
|
||||
foreach (OpportunityResources::KINDS as $kind) {
|
||||
$references[$kind] = $payload[$kind] ?? [];
|
||||
$rows = [];
|
||||
if (app(OpportunityResources::class)->installed()) {
|
||||
foreach (app(OpportunityResources::class)->listing($record->id, $kind) as $row) {
|
||||
$rows[$row->id] = $row;
|
||||
}
|
||||
}
|
||||
$data[$kind] = array_map(function (string $id) use ($rows, $kind, $mutations): array {
|
||||
$row = $rows[$id] ?? null;
|
||||
if ($row === null) {
|
||||
return ['id' => $id, 'availability' => 'unavailable'];
|
||||
}
|
||||
$value = [...$row->payload, 'id' => $row->id, 'version' => (int) $row->version,
|
||||
'is_deleted' => $row->deleted_at !== null, 'deleted_at' => $row->deleted_at,
|
||||
'created_by' => $row->created_by, 'created_at' => $row->created_at, 'updated_at' => $row->updated_at];
|
||||
$events = $mutations[$id] ?? [];
|
||||
$last = $events ? $events[array_key_last($events)] : null;
|
||||
$deletion = $row->deleted_at && ($last['action'] ?? '') === 'delete' ? $last : null;
|
||||
$value['updated_by'] = $last['actor'] ?? ((int) $row->version === 1 ? $row->created_by : null);
|
||||
$value['deleted_by'] = $deletion['actor'] ?? null;
|
||||
$value['delete_reason'] = $deletion && $deletion['reason'] ? Crypt::decryptString($deletion['reason']) : null;
|
||||
$value['mutation_metadata_source'] = $last ? 'existing_audit_events' : 'creation_record_only';
|
||||
if ($kind !== 'locations') {
|
||||
$value['original_name'] = $row->file?->file_name;
|
||||
$value['mime_type'] = $row->file?->media_type;
|
||||
$value['sha256'] = $row->file?->sha256;
|
||||
$value['scan_recorded_status'] = $row->file?->malware_scan_status;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}, $references[$kind]);
|
||||
}
|
||||
|
||||
return ['adapter_version' => self::VERSION,
|
||||
'source_schema_sha256' => hash_file('sha256', resource_path('data/investmoz-opportunity-modular.schema.json')),
|
||||
'data' => $data, 'resource_references' => $references,
|
||||
'completion' => $completion, 'materiality' => $context['materiality'] ?? null,
|
||||
'review_conditions' => array_values($context['conditions'] ?? []),
|
||||
'deleted_inline_items' => array_values($context['canonical_items']['deleted'] ?? []),
|
||||
'validation_result' => ['scope' => 'current_payload_validation_and_recorded_submission_metadata', 'submission_hash' => $context['submission']['hash'] ?? null,
|
||||
'submitted_content_revision' => $context['submission']['content_revision'] ?? null,
|
||||
'current_content_revision' => $context['content_revision'] ?? 1,
|
||||
'revalidated_on_read' => true, 'external_decision' => 'not_inferred'],
|
||||
'publication' => $record->publicationPresentation(),
|
||||
'compatibility' => ['normative_response_complete' => false, 'opportunity_actor_sector_ids' => 'existing bigint, not converted to UUID',
|
||||
'modular_decision' => 'Functional approval of four modular contracts and SLA remains pending; legacy integration did not approve them. Historical snapshot annotations are preserved, not current approvals.',
|
||||
'opportunity_code' => 'existing reference preserved; no INV-MZ code invented',
|
||||
'states' => 'existing workflow values preserved; no implicit stage equivalence',
|
||||
'inline_modules' => 'management_draft canonical JSON with audited revisions; no parallel specialized tables',
|
||||
'state_correspondence' => ['draft' => 'draft', 'needs_information' => 'returned', 'submitted' => 'submitted', 'approved' => 'approved', 'published' => 'published', 'suspended' => 'suspended', 'archived' => 'archived', 'rejected' => 'rejected'],
|
||||
'unmapped_review_states' => 'in_review/information_pending preserve parallel gates; no single normative stage inferred',
|
||||
'metadata_gaps' => ['Legacy inline creation metadata can be unknown; first observation is not creation. Ambiguous changed collection rows get new identities with previous identities retained as deleted.', 'Existing bigint IDs remain explicit compatibility differences; no renumbering.']]];
|
||||
}
|
||||
|
||||
/**
|
||||
* Recover actors from existing audited versions; an imported creator must never be inferred.
|
||||
*
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function rootMetadata(Opportunity $record): array
|
||||
{
|
||||
$events = [];
|
||||
foreach (DB::table('audit_events')->whereIn('source_system', ['opportunity-management', 'portal-profiles-v1'])
|
||||
->where('after_data->record_id', $record->id)->get(['source_system', 'actor_user_id', 'action', 'after_data']) as $event) {
|
||||
$detail = json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR);
|
||||
$version = $detail['version'] ?? $detail['after']['version'] ?? null;
|
||||
if (! is_int($version)) {
|
||||
continue;
|
||||
}
|
||||
$events[$version] = ['actor' => $event->actor_user_id, 'action' => $event->action,
|
||||
'reason' => $detail['reason'] ?? null, 'encrypted_reason' => $event->source_system === 'opportunity-management'];
|
||||
}
|
||||
ksort($events);
|
||||
$creation = null;
|
||||
$deletion = null;
|
||||
foreach ($events as $event) {
|
||||
if ($event['action'] === 'draft_created') {
|
||||
$creation = $event;
|
||||
}
|
||||
if ($event['action'] === 'delete') {
|
||||
$deletion = $event;
|
||||
}
|
||||
}
|
||||
$latest = $events[(int) $record->management_version] ?? null;
|
||||
$deletion = $record->trashed() ? $deletion : null;
|
||||
|
||||
return ['created_by' => $creation['actor'] ?? null, 'created_at' => $record->created_at?->toIso8601String(),
|
||||
'updated_by' => $latest['actor'] ?? null, 'updated_at' => $record->updated_at?->toIso8601String(),
|
||||
'deleted_by' => $deletion['actor'] ?? null,
|
||||
'delete_reason' => $deletion && $deletion['reason'] ? ($deletion['encrypted_reason'] ? Crypt::decryptString($deletion['reason']) : $deletion['reason']) : null,
|
||||
'mutation_metadata_source' => 'existing_audit_events_and_record_timestamps',
|
||||
'mutation_metadata_gaps' => array_values(array_filter([
|
||||
$creation === null ? 'No recorded creation actor; imported ownership does not establish creation.' : null,
|
||||
$latest === null ? 'No audit actor matching the current management version; no updater inferred.' : null,
|
||||
]))];
|
||||
}
|
||||
}
|
||||
+508
@@ -0,0 +1,508 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class OpportunityProfileWorkflow
|
||||
{
|
||||
public function __construct(private PortalProfileAccess $access, private OpportunityManagement $management,
|
||||
private OpportunityCanonicalContract $contract, private OpportunityWorkflowTasks $tasks) {}
|
||||
|
||||
/** @return list<string> */
|
||||
public function actions(User $actor, Opportunity $record): array
|
||||
{
|
||||
if ($record->owner_user_id === null || ! $this->access->canView($actor, $record)) {
|
||||
return [];
|
||||
}
|
||||
$actions = [];
|
||||
$state = $this->access->state($record);
|
||||
if ($this->access->scoped($actor, 'promoter', $record->organization_id, $record->opportunity_category)
|
||||
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id)
|
||||
&& $this->access->operational($actor, 'edit', $record->id)) {
|
||||
if (in_array($state, ['draft', 'needs_information'], true)) {
|
||||
$actions[] = 'submit';
|
||||
}
|
||||
if (in_array($state, ['approved', 'published', 'suspended'], true)) {
|
||||
$actions[] = 'request_revision';
|
||||
}
|
||||
if (! in_array($state, ['archived', 'rejected'], true)) {
|
||||
$actions[] = 'request_archive';
|
||||
}
|
||||
if ($state === 'rejected' && empty($record->workflow_context['appeal']['pending'])) {
|
||||
$actions[] = 'appeal';
|
||||
}
|
||||
}
|
||||
if ($this->access->mfa($actor) && ! $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';
|
||||
}
|
||||
if ($state === 'submitted') {
|
||||
$actions[] = 'start_review';
|
||||
}
|
||||
if (in_array($state, ['submitted', 'in_review', 'information_pending'], true)) {
|
||||
array_push($actions, 'request_correction', 'pending_opinion', 'reject', 'review_gate', 'approve');
|
||||
if ($this->responsibility($actor, $record, 'validation_coordinator')) {
|
||||
$actions[] = 'assign_review';
|
||||
}
|
||||
}
|
||||
if ($state === 'rejected' && ($record->workflow_context['appeal']['pending'] ?? false)
|
||||
&& $this->responsibility($actor, $record, 'appeal_reviewer')
|
||||
&& (int) ($record->workflow_context['rejection']['actor_id'] ?? 0) !== $actor->id) {
|
||||
array_push($actions, 'appeal_uphold', 'appeal_reopen');
|
||||
}
|
||||
if (count(array_filter($record->workflow_context['opinions'] ?? [], fn ($opinion) => ($opinion['recipient_id'] ?? 0) === $actor->id && ($opinion['status'] ?? '') === 'pending')) > 0) {
|
||||
$actions[] = 'respond_opinion';
|
||||
}
|
||||
}
|
||||
if ($this->access->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category)) {
|
||||
if ($state === 'approved' && $this->access->operational($actor, 'publish', $record->id)
|
||||
&& (int) ($record->workflow_context['approval']['actor_id'] ?? 0) !== $actor->id) {
|
||||
$actions[] = 'publish';
|
||||
if ($this->responsibility($actor, $record, 'publication_coordinator')) {
|
||||
$actions[] = 'assign_publication';
|
||||
}
|
||||
}
|
||||
if ($this->access->operational($actor, 'archive', $record->id)) {
|
||||
if ($record->status === 'published') {
|
||||
$actions[] = 'suspend';
|
||||
}
|
||||
if ($state !== 'archived') {
|
||||
$actions[] = 'archive';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($record->workflow_context['assignment']['assignee_user_id']) && (int) $record->workflow_context['assignment']['assignee_user_id'] !== $actor->id) {
|
||||
$actions = array_values(array_diff($actions, ['start_review', 'request_correction', 'pending_opinion', 'reject', 'review_gate', 'approve']));
|
||||
}
|
||||
if (isset($record->workflow_context['publication_assignment']['assignee_user_id']) && (int) $record->workflow_context['publication_assignment']['assignee_user_id'] !== $actor->id) {
|
||||
$actions = array_values(array_diff($actions, ['publish']));
|
||||
}
|
||||
|
||||
return $actions;
|
||||
}
|
||||
|
||||
/** Scoped names/IDs only; no secrets or implicit assignees.
|
||||
* @return array<string,mixed> */
|
||||
public function participants(User $actor, Opportunity $record): array
|
||||
{
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
if (! $this->access->has($actor, 'validator') && ! $this->access->has($actor, 'publisher')) {
|
||||
return ['validators' => [], 'publishers' => [], 'condition_responsibles' => []];
|
||||
}
|
||||
$result = ['validators' => [], 'publishers' => [], 'condition_responsibles' => []];
|
||||
foreach (User::whereNotNull('email_verified_at')->whereNotNull('two_factor_confirmed_at')->get() as $candidate) {
|
||||
if ($this->access->canView($candidate, $record) && (($this->access->scoped($candidate, 'promoter', $record->organization_id, $record->opportunity_category) && $this->access->operational($candidate, 'edit', $record->id))
|
||||
|| ($this->access->scoped($candidate, 'validator', $record->organization_id, $record->opportunity_category) && $this->access->operational($candidate, 'validate', $record->id)))) {
|
||||
$result['condition_responsibles'][] = ['id' => $candidate->id, 'name' => $candidate->name];
|
||||
}
|
||||
if ($this->access->conflict($candidate, $record)) {
|
||||
continue;
|
||||
}
|
||||
foreach (['validator' => 'validators', 'publisher' => 'publishers'] as $role => $list) {
|
||||
if ($this->access->scoped($candidate, $role, $record->organization_id, $record->opportunity_category) && $this->access->operational($candidate, $role === 'validator' ? 'validate' : 'publish', $record->id)) {
|
||||
if ($role === 'publisher' && (int) ($record->workflow_context['approval']['actor_id'] ?? 0) === $candidate->id) {
|
||||
continue;
|
||||
}
|
||||
$result[$list][] = ['id' => $candidate->id, 'name' => $candidate->name, 'technical' => $this->responsibility($candidate, $record, 'technical_reviewer'), 'legal' => $this->responsibility($candidate, $record, 'legal_reviewer')];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function submissionGaps(Opportunity $record): array
|
||||
{
|
||||
try {
|
||||
$this->contract->validateSubmission($record);
|
||||
|
||||
return [];
|
||||
} catch (ValidationException $error) {
|
||||
return array_keys($error->errors());
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function transition(User $actor, int $id, array $input): Opportunity
|
||||
{
|
||||
$record = Opportunity::withTrashed()->findOrFail($id);
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
abort_unless($record->owner_user_id !== null && ! $record->trashed(), 409, 'Workflow apenas para registos explicitamente sujeitos à política.');
|
||||
$data = Validator::make($input, ['etag' => 'required|string|size:64',
|
||||
'action' => 'required|in:submit,start_review,request_correction,pending_opinion,respond_opinion,reject,approve,publish,suspend,archive,request_archive,appeal,request_revision,review_gate,assign_review,assign_publication,appeal_uphold,appeal_reopen',
|
||||
'reason' => 'required|string|min:20|max:1000', 'correction_items' => 'sometimes|array', 'correction_items.*' => 'required|string|max:250',
|
||||
'gate' => 'sometimes|string|max:80', 'gate_decision' => 'sometimes|in:approved,rejected', 'assignee_user_id' => 'sometimes|integer|min:1',
|
||||
'opinion_id' => 'sometimes|uuid', 'recipient_user_id' => 'sometimes|integer|min:1',
|
||||
'evidence_document_ids' => 'sometimes|array', 'evidence_document_ids.*' => 'uuid', 'due_at' => 'prohibited',
|
||||
'confirm_publication' => 'sometimes|boolean', 'preview_hash' => 'sometimes|string|size:64',
|
||||
'condition' => 'sometimes|array:description,responsible_user_id,due_on,blocking_action',
|
||||
'condition.description' => 'required_with:condition|string|min:10|max:1000',
|
||||
'condition.responsible_user_id' => 'required_with:condition|integer|min:1',
|
||||
'condition.due_on' => 'sometimes|nullable|date_format:Y-m-d',
|
||||
'condition.blocking_action' => 'required_with:condition|in:approve,publish',
|
||||
'resolve_condition_ids' => 'sometimes|array', 'resolve_condition_ids.*' => 'uuid|distinct',
|
||||
])->validate();
|
||||
$action = $data['action'];
|
||||
if ($action !== 'review_gate' && (isset($data['condition']) || ! empty($data['resolve_condition_ids']))) {
|
||||
throw ValidationException::withMessages(['condition' => 'Condições só podem ser verificadas numa revisão especializada autorizada.']);
|
||||
}
|
||||
$this->authorizeAction($actor, $record, $action);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data, $action) {
|
||||
$record = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_unless(hash_equals($this->management->etag($record), $data['etag']), 409, 'Versão alterada.');
|
||||
$this->authorizeAction($actor, $record, $action);
|
||||
$context = $record->workflow_context ?? [];
|
||||
$state = $this->access->state($record);
|
||||
$before = ['status' => $state, 'publication_status' => $record->status, 'version' => $record->management_version];
|
||||
$from = match ($action) {
|
||||
'submit' => ['draft', 'needs_information'], 'start_review' => ['submitted'],
|
||||
'request_correction', 'pending_opinion', 'respond_opinion', 'reject', 'approve', 'assign_review' => ['submitted', 'in_review', 'information_pending'],
|
||||
'review_gate' => ['submitted', 'in_review', 'information_pending', 'approved'],
|
||||
'publish' => ['approved'], 'suspend' => [$state],
|
||||
'assign_publication' => ['approved'],
|
||||
'request_revision' => ['approved', 'published', 'suspended'],
|
||||
'archive' => ['draft', 'submitted', 'in_review', 'information_pending', 'needs_information', 'approved', 'rejected', 'published', 'suspended'],
|
||||
'request_archive' => ['draft', 'submitted', 'in_review', 'information_pending', 'needs_information', 'approved', 'published', 'suspended'],
|
||||
'appeal', 'appeal_uphold', 'appeal_reopen' => ['rejected'],
|
||||
default => [],
|
||||
};
|
||||
abort_unless(in_array($state, $from, true), 409, 'Transição incompatível com o estado atual.');
|
||||
$decision = ['actor_id' => $actor->id, 'action' => $action, 'reason' => $data['reason'], 'at' => now()->toIso8601String(),
|
||||
'content_revision' => $context['content_revision'] ?? 1];
|
||||
if (isset($context['review_cycle'])) {
|
||||
$decision['review_cycle'] = $context['review_cycle'];
|
||||
}
|
||||
$next = $state;
|
||||
$snapshot = [];
|
||||
if ($action === 'submit' && $record->opportunity_category === 'land_rights') {
|
||||
// Serialize the existing JSON-backed §27 uniqueness check across records.
|
||||
DB::select('SELECT pg_advisory_xact_lock(111026,270000)');
|
||||
}
|
||||
if (in_array($action, ['submit', 'review_gate', 'pending_opinion', 'respond_opinion', 'approve', 'publish'], true)) {
|
||||
$blockers = $this->contract->deliveryBlockers($this->management->values($record)['canonical'] ?? []);
|
||||
try {
|
||||
$snapshot = $this->contract->validateSubmission($record);
|
||||
} catch (ValidationException $error) {
|
||||
$errors = $error->errors();
|
||||
foreach ($blockers as $field => $message) {
|
||||
$errors[$field][] = $message;
|
||||
}
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
if ($blockers !== []) {
|
||||
throw ValidationException::withMessages($blockers);
|
||||
}
|
||||
if ($action !== 'submit') {
|
||||
abort_unless(hash_equals($context['submission']['hash'] ?? '', $snapshot['hash']), 409, 'Conteúdo ou recursos mudaram desde a submissão. Exige nova submissão/revisão.');
|
||||
}
|
||||
}
|
||||
if ($action === 'submit') {
|
||||
// New review attempt, even when the canonical content is unchanged.
|
||||
// Historical decisions/tasks and the content revision keep their IDs.
|
||||
$context['review_cycle'] = max((int) ($context['review_cycle'] ?? 0), $this->submissionCount($context)) + 1;
|
||||
$decision['review_cycle'] = $context['review_cycle'];
|
||||
foreach ($context['opinions'] ?? [] as $opinionId => $opinion) {
|
||||
if (($opinion['status'] ?? '') === 'pending') {
|
||||
$context['opinions'][$opinionId]['status'] = 'superseded';
|
||||
$this->tasks->complete($opinion['task_id'] ?? null, 'Nova versão submetida; parecer anterior preservado.');
|
||||
}
|
||||
}
|
||||
$baseline = $context['review_baseline'] ?? $context['submission'] ?? [];
|
||||
$materiality = app(OpportunityReviewMateriality::class)->reconcile($baseline, $snapshot, $context['reviews'] ?? [], $this->contract->gates($record), ! empty($context['force_review']));
|
||||
$context['materiality'] = array_diff_key($materiality, ['reviews' => true]);
|
||||
$context['reviews'] = $materiality['reviews'];
|
||||
app(OpportunityReviewConditions::class)->reconcile($context, $snapshot, $materiality['reopened']);
|
||||
$context['submission'] = [...$snapshot, ...$decision];
|
||||
$context['sla'] = ['policy_version' => null, 'due_at' => null, 'status' => 'unconfigured'];
|
||||
unset($context['approval'], $context['assignment'], $context['publication_assignment'], $context['review_baseline'], $context['force_review']);
|
||||
$record->first_submitted_at ??= now()->toIso8601String();
|
||||
$record->management_closed_once = true;
|
||||
$record->workflow_context = $context;
|
||||
$context['review_task_id'] = $this->tasks->ensure($record, 'opportunity_review', 'Validação da oportunidade '.$record->reference);
|
||||
$this->tasks->complete($context['correction_task_id'] ?? null, $data['reason']);
|
||||
$next = 'submitted';
|
||||
} elseif ($action === 'start_review' || $action === 'assign_review') {
|
||||
$subject = $action === 'start_review' ? $actor : User::whereKey($data['assignee_user_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($subject, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->operational($subject, 'validate', $record->id) && ! $this->access->conflict($subject, $record)
|
||||
&& $subject->two_factor_confirmed_at !== null, 403, 'Responsável requer papel válido, MFA configurado e independência.');
|
||||
if ($this->tasks->closedReviewBinding($record, $context['review_task_id'] ?? null)) {
|
||||
// Recover only a completed task of this opportunity in an
|
||||
// already submitted legacy attempt. Never reopen/delete it.
|
||||
$oldTask = $context['review_task_id'];
|
||||
$context['review_cycle'] = max(1, (int) ($context['review_cycle'] ?? 0), $this->submissionCount($context));
|
||||
$record->workflow_context = $context;
|
||||
$context['review_task_id'] = $this->tasks->ensure($record, 'opportunity_review', 'Validação da oportunidade '.$record->reference);
|
||||
$context['review_task_binding_history'][] = ['previous_task_id' => $oldTask, 'task_id' => $context['review_task_id'],
|
||||
'review_cycle' => $context['review_cycle'], 'at' => now()->toIso8601String(), 'reason' => 'Completed legacy review binding replaced for the current submission; original preserved.'];
|
||||
$decision['review_cycle'] = $context['review_cycle'];
|
||||
}
|
||||
$context['review_task_id'] ??= $this->tasks->ensure($record, 'opportunity_review', 'Validação da oportunidade '.$record->reference);
|
||||
$this->tasks->assign($record, $context['review_task_id'], $subject);
|
||||
$context['assignment'] = [...$decision, 'assignee_user_id' => $subject->id];
|
||||
$next = 'in_review';
|
||||
} elseif ($action === 'review_gate') {
|
||||
if ($state === 'approved') {
|
||||
throw_unless(! empty($data['resolve_condition_ids']) && empty($data['condition']) && ($data['gate_decision'] ?? '') === 'approved', ValidationException::withMessages(['resolve_condition_ids' => 'Após aprovação, só verificar condições de publicação existentes; alterações exigem nova revisão.']));
|
||||
}
|
||||
$gate = $data['gate'] ?? '';
|
||||
abort_unless(in_array($gate, $this->contract->gates($record), true), 422, 'Gate não aplicável.');
|
||||
$legal = preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1;
|
||||
abort_unless($this->responsibility($actor, $record, $legal ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Responsabilidade de revisão necessária.');
|
||||
$documents = $data['evidence_document_ids'] ?? [];
|
||||
abort_unless($documents !== [] && array_diff($documents, array_keys($snapshot['resources']['documents'] ?? [])) === [], 422, 'Selecione evidência documental desta versão.');
|
||||
abort_unless(isset($data['gate_decision']), 422, 'Indique decisão fundamentada do gate.');
|
||||
app(OpportunityReviewConditions::class)->review($record, $actor, $data, $snapshot, $context);
|
||||
$context['reviews'][$gate] = [...$decision, 'decision' => $data['gate_decision'], 'hash' => $snapshot['hash'], 'evidence_document_ids' => $documents];
|
||||
$context['reviews'][$gate]['scope_hash'] = app(OpportunityReviewMateriality::class)->hash($snapshot, $gate, $context['reviews'][$gate]);
|
||||
$context['reviews'][$gate]['scope_rule'] = OpportunityReviewMateriality::VERSION;
|
||||
$next = 'in_review';
|
||||
} elseif ($action === 'approve') {
|
||||
app(OpportunityReviewConditions::class)->authorize($context, $snapshot, 'approve');
|
||||
abort_if(count(array_filter($context['opinions'] ?? [], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['status'] ?? '') === 'pending')) > 0, 422, 'Parecer da versão atual ainda pendente.');
|
||||
abort_if(count(array_filter($context['opinions'] ?? [], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['response']['decision'] ?? '') === 'rejected')) > 0, 422, 'Parecer desfavorável exige correção e nova versão.');
|
||||
foreach ($this->contract->gates($record) as $gate) {
|
||||
$review = $context['reviews'][$gate] ?? [];
|
||||
abort_unless(($review['decision'] ?? null) === 'approved' && (($review['hash'] ?? '') === $snapshot['hash'] || ($review['accepted_submission_hash'] ?? '') === $snapshot['hash']), 422, 'Gate '.$gate.' pendente, rejeitado ou de outra versão.');
|
||||
abort_unless(app(OpportunityReviewMateriality::class)->matches($snapshot, $gate, $review), 409, 'Âmbito da revisão alterado.');
|
||||
$reviewer = User::whereKey($review['actor_id'])->firstOrFail();
|
||||
abort_unless($this->access->scoped($reviewer, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& ! $this->access->conflict($reviewer, $record) && $this->access->operational($reviewer, 'validate', $record->id)
|
||||
&& $this->responsibility($reviewer, $record, preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Revisor revogado, sem responsabilidade ou com conflito.');
|
||||
}
|
||||
$context['approval'] = [...$decision, 'hash' => $snapshot['hash'], 'gates' => $context['reviews'] ?? []];
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$record->workflow_context = $context;
|
||||
$context['publication_task_id'] = $this->tasks->ensure($record, 'opportunity_publication', 'Preparação editorial '.$record->reference);
|
||||
$next = 'approved';
|
||||
} elseif ($action === 'assign_publication') {
|
||||
$subject = User::whereKey($data['assignee_user_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($subject, 'publisher', $record->organization_id, $record->opportunity_category) && $this->access->operational($subject, 'publish', $record->id) && ! $this->access->conflict($subject, $record) && $subject->two_factor_confirmed_at !== null && (int) ($context['approval']['actor_id'] ?? 0) !== $subject->id, 403, 'Publicador exige MFA, âmbito e independência da aprovação.');
|
||||
$context['publication_task_id'] ??= $this->tasks->ensure($record, 'opportunity_publication', 'Preparação editorial '.$record->reference);
|
||||
$this->tasks->assign($record, $context['publication_task_id'], $subject);
|
||||
$context['publication_assignment'] = [...$decision, 'assignee_user_id' => $subject->id];
|
||||
} elseif ($action === 'publish') {
|
||||
app(OpportunityReviewConditions::class)->authorize($context, $snapshot, 'publish');
|
||||
Validator::make($data, ['confirm_publication' => 'required|accepted', 'preview_hash' => 'required|string|size:64'])->validate();
|
||||
$this->contract->validatePublication($snapshot);
|
||||
abort_unless(hash_equals($snapshot['hash'], $data['preview_hash']), 409, 'Pré-visualização diferente da versão aprovada.');
|
||||
abort_unless(($context['approval']['hash'] ?? '') === $snapshot['hash'], 409, 'Aprovação não corresponde ao conteúdo atual.');
|
||||
foreach ($this->contract->gates($record) as $gate) {
|
||||
$review = $context['approval']['gates'][$gate] ?? [];
|
||||
abort_unless(($review['decision'] ?? null) === 'approved' && (($review['hash'] ?? '') === $snapshot['hash'] || ($review['accepted_submission_hash'] ?? '') === $snapshot['hash']), 422, 'Revisão aprovada desta versão necessária.');
|
||||
$reviewer = User::whereKey($review['actor_id'])->firstOrFail();
|
||||
abort_unless($this->access->scoped($reviewer, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& ! $this->access->conflict($reviewer, $record) && $this->access->operational($reviewer, 'validate', $record->id)
|
||||
&& $this->responsibility($reviewer, $record, preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Revisor revogado, sem responsabilidade ou com conflito na publicação.');
|
||||
}
|
||||
$approver = User::whereKey($context['approval']['actor_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($approver, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& ! $this->access->conflict($approver, $record) && $this->access->operational($approver, 'validate', $record->id), 403, 'Aprovador revogado ou com conflito.');
|
||||
$p = $snapshot['payload'];
|
||||
if (! empty($p['review_due_date'])) {
|
||||
abort_unless($p['review_due_date'] > today()->toDateString(), 422, 'Data de revisão deve ser futura.');
|
||||
}
|
||||
if (isset($p['business_transaction'])) {
|
||||
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'] = [...$decision, 'hash' => $snapshot['hash'], 'visibility' => $p['visibility'],
|
||||
'public_fields' => ['title', 'summary', 'description', 'sector_id', 'province', 'district']];
|
||||
// Minimal public projection; contacts, valuations, evidence and originals remain private.
|
||||
$projection = $this->contract->publicProjection($p);
|
||||
$record->title = $projection['title'];
|
||||
$record->summary = $projection['summary'];
|
||||
$record->description = $projection['description'];
|
||||
$record->sector_id = $p['sector_id'];
|
||||
$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);
|
||||
$last = array_key_last($path);
|
||||
abort_unless($last !== null, 422, 'Localização principal sem hierarquia.');
|
||||
$record->primary_territory_id = $path[$last]->id;
|
||||
$record->province = $path[0]->name;
|
||||
$record->district = $path[1]->name;
|
||||
$record->geography_scope = $p['geographic_scope'] === 'national' ? 'national' : 'specific';
|
||||
$record->published_at = now();
|
||||
$record->status = 'published';
|
||||
$next = 'published';
|
||||
$this->tasks->complete($context['publication_task_id'] ?? null, $data['reason']);
|
||||
} elseif ($action === 'pending_opinion') {
|
||||
$gate = $data['gate'] ?? '';
|
||||
abort_unless(in_array($gate, $this->contract->gates($record), true), 422, 'Indique a revisão aplicável ao parecer.');
|
||||
$subject = User::whereKey($data['recipient_user_id'] ?? 0)->firstOrFail();
|
||||
abort_unless($this->access->scoped($subject, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
&& $this->access->operational($subject, 'validate', $record->id) && ! $this->access->conflict($subject, $record) && $subject->two_factor_confirmed_at !== null
|
||||
&& $this->responsibility($subject, $record, preg_match('/legal|registry|authority|confidentiality|license/', $gate) === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Destinatário exige responsabilidade, MFA e independência.');
|
||||
abort_if($subject->id === $actor->id, 422, 'O parecer deve ser solicitado a outro revisor.');
|
||||
$opinionId = (string) Str::uuid();
|
||||
$taskId = $this->tasks->ensure($record, 'opportunity_opinion:'.$opinionId, 'Parecer da oportunidade '.$record->reference);
|
||||
$this->tasks->assign($record, $taskId, $subject);
|
||||
$context['opinions'][$opinionId] = [...$decision, 'id' => $opinionId, 'recipient_id' => $subject->id, 'gate' => $gate, 'status' => 'pending', 'hash' => $snapshot['hash'], 'task_id' => $taskId];
|
||||
$next = 'information_pending';
|
||||
} elseif ($action === 'respond_opinion') {
|
||||
$opinionId = $data['opinion_id'] ?? '';
|
||||
$opinion = $context['opinions'][$opinionId] ?? [];
|
||||
abort_unless(($opinion['recipient_id'] ?? 0) === $actor->id, 403, 'Parecer atribuído a outro revisor.');
|
||||
abort_unless($this->responsibility($actor, $record, preg_match('/legal|registry|authority|confidentiality|license/', $opinion['gate'] ?? '') === 1 ? 'legal_reviewer' : 'technical_reviewer'), 403, 'Responsabilidade do parecer revogada.');
|
||||
abort_unless(($opinion['status'] ?? '') === 'pending' && ($opinion['hash'] ?? '') === $snapshot['hash'], 409, 'Parecer encerrado ou de outra versão.');
|
||||
$documents = $data['evidence_document_ids'] ?? [];
|
||||
abort_unless(isset($data['gate_decision']) && $documents !== [] && array_diff($documents, array_keys($snapshot['resources']['documents'] ?? [])) === [], 422, 'Resposta exige decisão e documentos desta versão.');
|
||||
$context['opinions'][$opinionId]['status'] = 'answered';
|
||||
$context['opinions'][$opinionId]['response'] = [...$decision, 'decision' => $data['gate_decision'], 'evidence_document_ids' => $documents];
|
||||
$this->tasks->complete($opinion['task_id'], $data['reason']);
|
||||
$next = count(array_filter($context['opinions'], fn ($o) => ($o['hash'] ?? '') === $snapshot['hash'] && ($o['status'] ?? '') === 'pending')) > 0 ? 'information_pending' : 'in_review';
|
||||
} elseif ($action === 'request_correction') {
|
||||
abort_unless($data['correction_items'] ?? [], 422, 'Indique campos e documentos a corrigir.');
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$context['correction_items'] = $data['correction_items'];
|
||||
$context['correction_cycles'] = ($context['correction_cycles'] ?? 0) + 1;
|
||||
$record->workflow_context = $context;
|
||||
$context['correction_task_id'] = $this->tasks->ensure($record, 'opportunity_correction', 'Correções da oportunidade '.$record->reference);
|
||||
$next = 'needs_information';
|
||||
} elseif ($action === 'request_revision' || $action === 'appeal_reopen') {
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
$this->tasks->complete($context['publication_task_id'] ?? null, $data['reason']);
|
||||
$context['decision_history'][] = ['approval' => $context['approval'] ?? null, 'reviews' => $context['reviews'] ?? null, 'submission' => $context['submission'] ?? null];
|
||||
$context['review_baseline'] = $context['submission'] ?? [];
|
||||
$context['force_review'] = $action === 'appeal_reopen' || $state === 'suspended';
|
||||
unset($context['approval']);
|
||||
$next = 'needs_information';
|
||||
} elseif ($action === 'request_archive') {
|
||||
$context['request_archive'] = $decision;
|
||||
} elseif ($action === 'appeal') {
|
||||
abort_if($context['appeal']['pending'] ?? false, 409, 'Recurso já pendente.');
|
||||
$context['appeal'] = [...$decision, 'pending' => true];
|
||||
$context['appeal_task_id'] = $this->tasks->ensure($record, 'opportunity_appeal', 'Recurso da oportunidade '.$record->reference);
|
||||
} elseif ($action === 'appeal_uphold') {
|
||||
$next = 'rejected';
|
||||
} else {
|
||||
$next = match ($action) {
|
||||
'reject' => 'rejected', 'suspend' => 'suspended', 'archive' => 'archived'
|
||||
};
|
||||
if ($action === 'reject') {
|
||||
$context['rejection'] = $decision;
|
||||
$this->tasks->complete($context['review_task_id'] ?? null, $data['reason']);
|
||||
}
|
||||
if ($action === 'archive') {
|
||||
$context['archive'] = $decision;
|
||||
}
|
||||
if (in_array($action, ['suspend', 'archive'], true)) {
|
||||
$record->status = $next;
|
||||
foreach (['review_task_id', 'correction_task_id', 'publication_task_id', 'appeal_task_id'] as $task) {
|
||||
$this->tasks->complete($context[$task] ?? null, $data['reason']);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (in_array($action, ['appeal_uphold', 'appeal_reopen'], true)) {
|
||||
$context['appeal']['pending'] = false;
|
||||
$context['appeal']['decision'] = $decision;
|
||||
$this->tasks->complete($context['appeal_task_id'] ?? null, $data['reason']);
|
||||
}
|
||||
if (in_array($action, ['request_correction', 'reject'], true)) {
|
||||
if ($action === 'reject') {
|
||||
$context['force_review'] = true;
|
||||
}
|
||||
unset($context['approval']);
|
||||
}
|
||||
if (in_array($action, ['request_correction', 'reject', 'suspend', 'archive', 'request_revision', 'appeal_reopen'], true)) {
|
||||
foreach ($context['opinions'] ?? [] as $opinionId => $opinion) {
|
||||
if (($opinion['status'] ?? '') === 'pending') {
|
||||
$context['opinions'][$opinionId]['status'] = 'superseded';
|
||||
$this->tasks->complete($opinion['task_id'] ?? null, $data['reason']);
|
||||
}
|
||||
}
|
||||
}
|
||||
$context['working_state'] = $next;
|
||||
$context['last_decision'] = $decision;
|
||||
$context['events'][] = [...$decision, 'from' => $state, 'to' => $next];
|
||||
if ($record->status !== 'published' || in_array($action, ['suspend', 'archive'], true)) {
|
||||
$record->status = $next;
|
||||
}
|
||||
$record->management_version++;
|
||||
$record->workflow_context = $context;
|
||||
$record->save();
|
||||
$this->access->audit($actor, 'workflow_'.$action, ['record_id' => $record->id, 'before' => $before,
|
||||
'after' => ['status' => $next, 'publication_status' => $record->status, 'version' => $record->management_version], 'reason' => $data['reason']]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<array-key, mixed> $context */
|
||||
private function submissionCount(array $context): int
|
||||
{
|
||||
$events = $context['events'] ?? [];
|
||||
abort_unless(is_array($events), 409, 'Histórico de submissões inconsistente; preservar e recuperar antes de continuar.');
|
||||
$count = 0;
|
||||
foreach ($events as $event) {
|
||||
if (is_array($event) && ($event['action'] ?? null) === 'submit') {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
private function responsibility(User $actor, Opportunity $record, string $name): bool
|
||||
{
|
||||
foreach ($this->access->grants($actor, $name === 'publication_coordinator' ? 'publisher' : 'validator') as $grant) {
|
||||
if (($grant->organization_id === null || $grant->organization_id === $record->organization_id)
|
||||
&& in_array($record->opportunity_category, json_decode($grant->opportunity_types, true), true)
|
||||
&& in_array($name, json_decode($grant->responsibilities, true), true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function authorizeAction(User $actor, Opportunity $record, string $action): void
|
||||
{
|
||||
$this->access->authorize($actor, 'view', $record);
|
||||
$promoter = $this->access->scoped($actor, 'promoter', $record->organization_id, $record->opportunity_category)
|
||||
&& ($record->organization_id !== null || (int) $record->owner_user_id === $actor->id);
|
||||
if (in_array($action, ['submit', 'request_archive', 'appeal', 'request_revision'], 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.');
|
||||
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.');
|
||||
}
|
||||
if ($action === 'assign_publication') {
|
||||
abort_unless($this->responsibility($actor, $record, 'publication_coordinator'), 403);
|
||||
}
|
||||
if ($action === 'assign_review') {
|
||||
abort_unless($this->responsibility($actor, $record, 'validation_coordinator'), 403);
|
||||
}
|
||||
if (in_array($action, ['start_review', 'review_gate', 'request_correction', 'pending_opinion', 'reject', 'approve'], true)
|
||||
&& isset($record->workflow_context['assignment']['assignee_user_id'])) {
|
||||
abort_unless((int) $record->workflow_context['assignment']['assignee_user_id'] === $actor->id, 403, 'Tarefa atribuída a outro Validador; o coordenador deve registar a reatribuição.');
|
||||
}
|
||||
if (in_array($action, ['appeal_uphold', 'appeal_reopen'], true)) {
|
||||
abort_unless($this->responsibility($actor, $record, 'appeal_reviewer') && ($record->workflow_context['appeal']['pending'] ?? false)
|
||||
&& (int) ($record->workflow_context['rejection']['actor_id'] ?? 0) !== $actor->id, 403, 'Recurso exige instância independente da rejeição.');
|
||||
}
|
||||
if ($action === 'suspend') {
|
||||
abort_unless($record->status === 'published', 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Explicit internal review conditions in the existing workflow JSON and audit. */
|
||||
class OpportunityReviewConditions
|
||||
{
|
||||
/** @param array<string,mixed> $data
|
||||
* @param array<string,mixed> $snapshot
|
||||
* @param array<string,mixed> $context */
|
||||
public function review(Opportunity $record, User $actor, array $data, array $snapshot, array &$context): void
|
||||
{
|
||||
$gate = $data['gate'];
|
||||
foreach ($data['resolve_condition_ids'] ?? [] as $id) {
|
||||
$condition = $context['conditions'][$id] ?? null;
|
||||
$this->require($condition !== null && $condition['gate'] === $gate && $condition['status'] === 'open', 'resolve_condition_ids', 'Selecione uma condição aberta desta revisão.');
|
||||
$this->require(($data['gate_decision'] ?? '') === 'approved', 'gate_decision', 'A resolução exige verificação interna aprovada com evidência.');
|
||||
$documents = [];
|
||||
foreach ($data['evidence_document_ids'] ?? [] as $documentId) {
|
||||
$documents[$documentId] = $snapshot['resources']['documents'][$documentId]['sha256'];
|
||||
}
|
||||
$this->require($documents !== [], 'evidence_document_ids', 'A resolução exige documento ativo e analisado desta oportunidade.');
|
||||
$context['conditions'][$id]['status'] = 'resolved';
|
||||
$context['conditions'][$id]['resolution'] = ['actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => $data['reason'], 'document_hashes' => $documents, 'content_revision' => $context['content_revision'] ?? 1, 'scope' => 'internal_verification_not_external_decision'];
|
||||
}
|
||||
if (! empty($data['condition'])) {
|
||||
$input = $data['condition'];
|
||||
$subject = User::query()->whereKey($input['responsible_user_id'])->first();
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$this->require($subject !== null && $access->canView($subject, $record)
|
||||
&& (($access->scoped($subject, 'promoter', $record->organization_id, $record->opportunity_category) && $access->operational($subject, 'edit', $record->id))
|
||||
|| ($access->scoped($subject, 'validator', $record->organization_id, $record->opportunity_category) && $access->operational($subject, 'validate', $record->id))),
|
||||
'condition.responsible_user_id', 'Selecione um responsável autorizado neste âmbito; não atribua responsabilidade externa.');
|
||||
$id = (string) Str::uuid();
|
||||
$context['conditions'][$id] = ['id' => $id, 'gate' => $gate, 'description' => $input['description'], 'responsible_user_id' => $subject->id,
|
||||
'responsible_name' => $subject->name, 'due_on' => $input['due_on'] ?? null, 'blocking_action' => $input['blocking_action'],
|
||||
'status' => 'open', 'created_by' => $actor->id, 'created_at' => now()->toIso8601String(), 'scope' => 'internal_review_condition', 'resolution_history' => []];
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $context
|
||||
* @param array<string,mixed> $snapshot
|
||||
* @param list<string> $reopened */
|
||||
public function reconcile(array &$context, array $snapshot, array $reopened): void
|
||||
{
|
||||
foreach ($context['conditions'] ?? [] as $id => $condition) {
|
||||
if ($condition['status'] !== 'resolved') {
|
||||
continue;
|
||||
}
|
||||
$matches = ! in_array($condition['gate'], $reopened, true);
|
||||
foreach ($condition['resolution']['document_hashes'] ?? [] as $documentId => $sha) {
|
||||
$matches = $matches && ($snapshot['resources']['documents'][$documentId]['sha256'] ?? null) === $sha;
|
||||
}
|
||||
if (! $matches) {
|
||||
$context['conditions'][$id]['resolution_history'][] = $condition['resolution'];
|
||||
unset($context['conditions'][$id]['resolution']);
|
||||
$context['conditions'][$id]['status'] = 'open';
|
||||
$context['conditions'][$id]['reopened_at'] = now()->toIso8601String();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $context
|
||||
* @param array<string,mixed> $snapshot */
|
||||
public function authorize(array $context, array $snapshot, string $action): void
|
||||
{
|
||||
foreach ($context['conditions'] ?? [] as $condition) {
|
||||
if ($action === 'approve' && $condition['blocking_action'] !== 'approve') {
|
||||
continue;
|
||||
}
|
||||
$resolved = $condition['status'] === 'resolved';
|
||||
foreach ($condition['resolution']['document_hashes'] ?? [] as $id => $sha) {
|
||||
$resolved = $resolved && ($snapshot['resources']['documents'][$id]['sha256'] ?? null) === $sha;
|
||||
}
|
||||
$this->require($resolved, 'conditions.'.$condition['id'], 'Condição pendente: '.$condition['description'].'. Responsável: '.$condition['responsible_name'].'. Prazo: '.($condition['due_on'] ?? 'não definido').'.');
|
||||
}
|
||||
}
|
||||
|
||||
private function require(bool $ok, string $field, string $message): void
|
||||
{
|
||||
if (! $ok) {
|
||||
throw ValidationException::withMessages([$field => $message]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
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 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
|
||||
{
|
||||
$p = $snapshot['payload'] ?? [];
|
||||
$common = ['opportunity_category', 'promoter_id', 'promoter_type', 'sector_id', 'subsector_id', 'economic_activity_id', 'demand_statement', 'executive_summary'];
|
||||
$fields = match ($gate) {
|
||||
'property_review' => ['real_estate.property_type', 'real_estate.land_area', 'real_estate.built_area', 'real_estate.area_unit', 'real_estate.units', 'real_estate.occupancy_status', 'real_estate.price', 'real_estate.rent', 'real_estate.rent_periodicity', 'real_estate.valuation', 'real_estate.utilities'],
|
||||
'registry_urban_review' => ['real_estate.transaction_type', 'real_estate.title_type', 'real_estate.registration_number', 'real_estate.encumbrances', 'real_estate.land_area', 'real_estate.area_unit'],
|
||||
'building_compliance_review' => ['real_estate.construction_status', 'real_estate.property_condition', 'real_estate.built_area', 'real_estate.floors', 'real_estate.planning_permit_document_id', 'real_estate.use_license_document_id'],
|
||||
'cadastral_screening' => ['land_rights.parcels', 'land_rights.overlaps_conflicts'],
|
||||
'land_legal_review' => ['land_rights.operation_type', 'land_rights.duat_status', 'land_rights.duat_number', 'land_rights.holder_id', 'land_rights.holder_name', 'land_rights.issuing_authority_id', 'land_rights.issue_date', 'land_rights.expiry_date', 'land_rights.authorized_purpose', 'land_rights.improvements', 'land_rights.consideration'],
|
||||
'community_environment_review' => ['land_rights.communities', 'land_rights.community_consultation', 'environmental_social'],
|
||||
'competent_authority_clearance' => ['land_rights.required_authorizations', 'land_rights.exploitation_plan_document_id', 'land_rights.authorized_purpose'],
|
||||
'corporate_screening' => ['business_transaction.legal_entity_id', 'business_transaction.legal_form', 'business_transaction.beneficial_owners', 'business_transaction.percentage_offered'],
|
||||
'financial_review' => ['business_transaction.asking_price', 'business_transaction.valuation', 'business_transaction.financial_periods', 'business_transaction.assets_liabilities', 'business_transaction.employees', 'business_transaction.partner_contribution'],
|
||||
'legal_tax_due_diligence' => ['business_transaction.transaction_type', 'business_transaction.percentage_offered', 'business_transaction.contracts_licenses', 'business_transaction.litigation_contingencies', 'business_transaction.governance_rights', 'business_transaction.franchise_terms', 'business_transaction.tax_labor_compliance'],
|
||||
'partnership_governance_review' => ['business_transaction.percentage_offered', 'business_transaction.partner_contribution', 'business_transaction.governance_rights'],
|
||||
'brand_license_review' => ['business_transaction.franchise_terms', 'business_transaction.contracts_licenses'],
|
||||
'franchise_legal_review' => ['business_transaction.franchise_terms', 'business_transaction.contracts_licenses', 'business_transaction.litigation_contingencies'],
|
||||
'confidentiality_clearance' => ['visibility', 'publish_contact', 'public_contact_id', 'business_transaction.confidentiality_level', 'business_transaction.teaser', 'business_transaction.nda_document_id', 'business_transaction.data_room_index_document_id'],
|
||||
'technical_review' => ['demand_statement', 'opportunity_type', 'maturity_stage', 'investment_modalities', 'investor_profiles', 'products', 'assets', 'inputs', 'markets', 'competitive_advantage', 'employment', 'impact_indicators', 'total_investment', 'currency', 'investment_breakdown', 'secured_financing', 'funding_sought', 'financial_indicators', 'milestones', 'risks'],
|
||||
'legal_territorial_review' => ['licenses', 'environmental_social', 'relations', 'truth_declaration'],
|
||||
// Experimental modules have no approved scope contract: never carry their decisions.
|
||||
default => array_keys($p),
|
||||
};
|
||||
if ($extended) {
|
||||
$fields = [...$fields, ...match ($gate) {
|
||||
'land_legal_review' => ['land_rights.holder_document_id', 'land_rights.area_unit'],
|
||||
'community_environment_review' => ['land_rights.communities_affected'],
|
||||
'competent_authority_clearance' => ['land_rights.exploitation_plan_required'],
|
||||
'corporate_screening' => ['business_transaction.entity_registration'],
|
||||
'financial_review' => ['business_transaction.available_financial_years', 'business_transaction.history_status', 'business_transaction.history_declaration', 'business_transaction.history_declaration_document_id', 'business_transaction.projections'],
|
||||
'franchise_legal_review' => ['business_transaction.legal_entity_id', 'business_transaction.legal_form', 'business_transaction.beneficial_owners', 'business_transaction.entity_registration', 'business_transaction.governance_rights', 'business_transaction.tax_labor_compliance'],
|
||||
'confidentiality_clearance' => ['internal_contact_id'],
|
||||
default => [],
|
||||
}];
|
||||
}
|
||||
$data = [];
|
||||
foreach ([...$common, ...$fields] as $field) {
|
||||
if (! is_string($field)) {
|
||||
throw new \UnexpectedValueException('Canonical review fields must be named fields.');
|
||||
}
|
||||
$data[$field] = Arr::get($p, $field);
|
||||
}
|
||||
// Explicitly unclassified specialised fields conservatively reopen reviews.
|
||||
// They cannot silently become immaterial when a schema gains a new field.
|
||||
$classified = match ($p['opportunity_category'] ?? '') {
|
||||
'real_estate' => ['transaction_type', 'property_type', 'construction_status', 'property_condition', 'land_area', 'built_area', 'area_unit', 'units', 'rooms', 'floors', 'amenities', 'utilities', 'occupancy_status', 'title_type', 'registration_number', 'encumbrances', 'price', 'rent', 'rent_periodicity', 'deposit', 'valuation', 'viewing', 'planning_permit_document_id', 'use_license_document_id', 'title_document_id', 'title_holder_name', 'issuing_authority_id', 'expected_completion_date', 'occupancy_details', 'occupancy_document_id', 'amenities_other', 'urban_limit_document_id', 'max_built_area'],
|
||||
default => [],
|
||||
};
|
||||
if ($classified !== []) {
|
||||
$data['unclassified_module_fields'] = array_diff_key($p['real_estate'] ?? [], array_flip($classified));
|
||||
}
|
||||
if ($gate === 'property_review') {
|
||||
foreach (['rooms', 'amenities', 'deposit', 'occupancy_details', 'occupancy_document_id', 'amenities_other'] as $key) {
|
||||
$data['real_estate.'.$key] = Arr::get($p, 'real_estate.'.$key);
|
||||
}
|
||||
}
|
||||
if ($gate === 'registry_urban_review') {
|
||||
foreach (['title_document_id', 'title_holder_name', 'issuing_authority_id', 'urban_limit_document_id', 'max_built_area'] as $key) {
|
||||
$data['real_estate.'.$key] = Arr::get($p, 'real_estate.'.$key);
|
||||
}
|
||||
}
|
||||
if ($gate === 'building_compliance_review') {
|
||||
$data['real_estate.expected_completion_date'] = Arr::get($p, 'real_estate.expected_completion_date');
|
||||
}
|
||||
|
||||
// A changed evidence file always invalidates a decision relying on it.
|
||||
// Unrelated documents/images and editorial timestamps are not review evidence.
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $snapshot
|
||||
* @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);
|
||||
$locationGates = ['registry_urban_review', 'cadastral_screening', 'legal_territorial_review', 'property_review'];
|
||||
if (! $legacy) {
|
||||
$locationGates = [...$locationGates, 'land_legal_review', 'community_environment_review', 'competent_authority_clearance'];
|
||||
}
|
||||
if (in_array($gate, $locationGates, true)) {
|
||||
$data['locations'] = array_map(fn ($r) => $r['payload'], $snapshot['resources']['locations'] ?? []);
|
||||
}
|
||||
foreach ($review['evidence_document_ids'] ?? [] as $id) {
|
||||
$r = $snapshot['resources']['documents'][$id] ?? null;
|
||||
$data['evidence'][$id] = $r ? ['sha256' => $r['sha256'] ?? null, 'payload' => $r['payload'] ?? [], 'deleted_at' => $r['deleted_at'] ?? null] : null;
|
||||
}
|
||||
|
||||
if ($extended) {
|
||||
// Nested references are part of the decision even when the reviewer
|
||||
// selected a different supporting file. Preserve the original bytes.
|
||||
$referenced = function (array $node) use (&$referenced, &$data, $snapshot): void {
|
||||
foreach ($node as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$referenced($value);
|
||||
} elseif (is_string($key) && is_string($value) && $value !== '' && (str_ends_with($key, 'document_id') || $key === 'image_id')) {
|
||||
$kind = $key === 'image_id' ? 'images' : 'documents';
|
||||
$resource = $snapshot['resources'][$kind][$value] ?? null;
|
||||
$data['referenced_resources'][$kind][$value] = $resource ? ['sha256' => $resource['sha256'] ?? null, 'payload' => $resource['payload'] ?? [], 'deleted_at' => $resource['deleted_at'] ?? null] : null;
|
||||
}
|
||||
}
|
||||
};
|
||||
$referenced($data);
|
||||
}
|
||||
|
||||
return $legacy ? hash('sha256', json_encode(Arr::sortRecursive($data), JSON_THROW_ON_ERROR)) : OpportunityCanonicalValue::hash($data);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $snapshot
|
||||
* @param array<string,mixed> $review */
|
||||
public function matches(array $snapshot, string $gate, array $review): bool
|
||||
{
|
||||
if (! isset($review['scope_hash'])) {
|
||||
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);
|
||||
$expected = $this->hash($snapshot, $gate, $review, $legacy, $rule);
|
||||
|
||||
return hash_equals($review['scope_hash'], $expected);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $before
|
||||
* @param array<string,mixed> $after
|
||||
* @param array<string,mixed> $reviews
|
||||
* @param list<string> $gates
|
||||
* @return array<string,mixed> */
|
||||
public function reconcile(array $before, array $after, array $reviews, array $gates, bool $force = false): array
|
||||
{
|
||||
$kept = [];
|
||||
$reopened = [];
|
||||
foreach ($gates as $gate) {
|
||||
$review = $reviews[$gate] ?? [];
|
||||
// Compare the signed baseline and new content with the new scope;
|
||||
// separately validate old scope signatures under their original rule.
|
||||
$priorHash = $this->hash($before, $gate, $review);
|
||||
$currentHash = $this->hash($after, $gate, $review);
|
||||
if (! $force && $before !== [] && ($review['decision'] ?? '') === 'approved' && $this->matches($before, $gate, $review) && hash_equals($priorHash, $currentHash)) {
|
||||
$kept[$gate] = [...$review, 'scope_hash' => $priorHash, 'scope_rule' => self::VERSION, 'accepted_submission_hash' => $after['hash'],
|
||||
'carried_forward' => ['rule' => self::VERSION, 'from_scope_hash' => $review['scope_hash'] ?? null, 'from_scope_rule' => $review['scope_rule'] ?? 'legacy_unspecified', 'from_submission_hash' => $before['hash'] ?? null, 'at' => now()->toIso8601String()]];
|
||||
} else {
|
||||
$reopened[] = $gate;
|
||||
}
|
||||
}
|
||||
|
||||
return ['rule' => self::VERSION, 'reviews' => $kept, 'reopened' => $reopened, 'retained' => array_keys($kept),
|
||||
'reason' => $force ? 'Suspensão, rejeição ou recurso exige nova decisão; motivo anterior preservado.' : 'Comparação dos campos e evidências aplicáveis a cada revisão (§28.1).',
|
||||
'final_approval' => 'Nova assinatura independente da versão; nenhum parecer ou decisão externa inventado.'];
|
||||
}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class PortalProfileAccess
|
||||
{
|
||||
public const VERSION = 'profiles-v1-20261010';
|
||||
|
||||
/** @return list<string> */
|
||||
public static function fingerprintFiles(): array
|
||||
{
|
||||
return [__FILE__, app_path('Models/User.php'), app_path('Models/Opportunity.php'), config_path('portal.php'), base_path('routes/web.php'),
|
||||
app_path('Http/Middleware/HandleInertiaRequests.php'), app_path('Services/OpportunityManagement.php'),
|
||||
app_path('Services/OpportunityResources.php'), app_path('Services/OpportunityImageProcessor.php'), app_path('Services/VerifiedDocumentBinary.php'),
|
||||
app_path('Services/PortalProfileAdministration.php'), app_path('Services/PortalSuperusers.php'),
|
||||
app_path('Services/OpportunityProfileWorkflow.php'), app_path('Http/Controllers/PortalProfileController.php'), app_path('Http/Controllers/DashboardController.php'),
|
||||
app_path('Http/Controllers/OpportunityManagementController.php'),
|
||||
app_path('Services/OpportunityCanonicalContract.php'), app_path('Services/OpportunityCanonicalResponse.php'), app_path('Services/OpportunityCategoryFields.php'), app_path('Services/OpportunityModularProfiles.php'), app_path('Services/OpportunityWorkflowTasks.php'), base_path('composer.json'), base_path('composer.lock'),
|
||||
app_path('Services/OpportunityReviewMateriality.php'), app_path('Services/OpportunityReviewConditions.php'), app_path('Services/OpportunityCanonicalMetadata.php'), app_path('Services/OpportunityCompleteness.php'), app_path('Services/OpportunityCanonicalValue.php'),
|
||||
resource_path('data/investmoz-opportunity-modular.schema.json'), resource_path('js/components/opportunity-canonical-fields.tsx'), resource_path('js/components/opportunity-parcel-geometry.tsx'),
|
||||
app_path('Http/Controllers/OpportunityResourceController.php'),
|
||||
app_path('Http/Controllers/InvestmentTerritoryController.php'),
|
||||
app_path('Http/Middleware/PortalProfileSession.php'), app_path('Http/Middleware/ProtectProfileOpportunity.php'),
|
||||
app_path('Http/Middleware/ProtectPrivilegedIdentity.php'), app_path('Http/Middleware/EnsurePortalProfiles.php'),
|
||||
app_path('Http/Middleware/AuditProfileDecision.php'), app_path('Providers/AppServiceProvider.php'),
|
||||
database_path('migrations/2026_10_10_040000_create_portal_profile_authorization.php'), base_path('bootstrap/app.php'),
|
||||
resource_path('js/pages/profiles/request.tsx'), resource_path('js/pages/profiles/administration.tsx'), resource_path('js/pages/profiles/audit.tsx'),
|
||||
resource_path('js/components/profile-navigation.tsx'), resource_path('js/components/opportunity-profile-actions.tsx'),
|
||||
resource_path('js/components/portal-grouped-menu.tsx'), resource_path('js/components/user-menu-content.tsx'),
|
||||
resource_path('js/pages/management/opportunities.tsx'), resource_path('js/pages/management/opportunity-draft.tsx'),
|
||||
resource_path('js/types/profile-access.ts'), resource_path('js/lib/profile-json.ts'), resource_path('js/pages/management/shared.tsx'),
|
||||
resource_path('js/pages/dashboard.tsx'), resource_path('js/pages/PortalInvestidor.tsx'),
|
||||
resource_path('js/layouts/portal-navigation.tsx'), resource_path('js/components/interactive-investment-map.tsx'),
|
||||
resource_path('js/components/simulation-form.tsx'), resource_path('js/lib/simulation-form.ts'), app_path('Services/LegacyContent.php'),
|
||||
resource_path('js/components/ui/sidebar.tsx'), resource_path('js/components/simulation-financial-tools.tsx'), resource_path('js/components/simulation-cashflow-planner.tsx'), resource_path('js/pages/investor-path/show.tsx'), resource_path('views/app.blade.php'),
|
||||
resource_path('js/pages/management/opportunity-resources.tsx'),
|
||||
app_path('Services/PortalProfileInstallation.php'), app_path('Http/Controllers/PortalProfileInstallationController.php'), config_path('portal_profiles.php'), resource_path('js/pages/profiles/installation.tsx')];
|
||||
}
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return config('portal.profile_access_enabled') && Schema::hasTable('portal_role_assignments')
|
||||
&& Schema::hasTable('portal_superuser_pair') && Schema::hasTable('portal_profile_requests')
|
||||
&& Schema::hasTable('portal_security_approvals') && Schema::hasColumn('users', 'portal_access_revision')
|
||||
&& Schema::hasColumn('opportunities', 'workflow_context') && Schema::hasColumn('opportunities', 'owner_user_id')
|
||||
&& Schema::hasColumn('opportunities', 'organization_id');
|
||||
}
|
||||
|
||||
/** @return list<\stdClass> */
|
||||
public function grants(User $actor, ?string $role = null): array
|
||||
{
|
||||
if (! $this->available() || ! $actor->hasVerifiedEmail()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(DB::table('portal_role_assignments')->where('user_id', $actor->id)->whereNull('revoked_at')->where('starts_at', '<=', now())
|
||||
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->when($role, fn ($q) => $q->where('role', $role))->get()->all());
|
||||
}
|
||||
|
||||
public function has(User $actor, string $role): bool
|
||||
{
|
||||
return $role === 'superuser' ? $this->superuser($actor) : $this->grants($actor, $role) !== [];
|
||||
}
|
||||
|
||||
public function superuser(User $actor): bool
|
||||
{
|
||||
return $this->available() && $actor->hasVerifiedEmail() && DB::table('portal_superuser_pair')->where('id', 1)
|
||||
->where(fn ($q) => $q->where('first_user_id', $actor->id)->orWhere('second_user_id', $actor->id))->exists();
|
||||
}
|
||||
|
||||
public function represents(User $actor, ?string $organization): bool
|
||||
{
|
||||
return $organization === null || DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')
|
||||
->where('m.user_id', $actor->id)->where('m.organization_id', $organization)
|
||||
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->exists();
|
||||
}
|
||||
|
||||
public function mfa(User $actor): bool
|
||||
{
|
||||
// Enrollment alone is insufficient: Fortify must have completed MFA in this session.
|
||||
return $actor->two_factor_confirmed_at !== null && $actor->two_factor_secret !== null
|
||||
&& session('login.id') === null && session('portal.mfa_actor') === $actor->id
|
||||
&& (int) session('portal.mfa_at', 0) >= time() - 900;
|
||||
}
|
||||
|
||||
public function scoped(User $actor, string $role, ?string $organization, string $type): bool
|
||||
{
|
||||
foreach ($this->grants($actor, $role) as $grant) {
|
||||
if (($grant->organization_id === $organization || ($role !== 'promoter' && $grant->organization_id === null))
|
||||
&& in_array($type, json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR), true)) {
|
||||
return $role !== 'promoter' || $this->represents($actor, $organization);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function operational(User $actor, string $action, ?int $recordId = null): bool
|
||||
{
|
||||
if ($this->has($actor, 'auditor')) {
|
||||
return false;
|
||||
}
|
||||
if (! $this->superuser($actor)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return DB::table('portal_security_approvals')->where('kind', 'elevation')->where('subject_user_id', $actor->id)
|
||||
->whereNotNull('approved_by')->whereNull('consumed_at')->where('expires_at', '>', now())
|
||||
->whereExists(fn ($q) => $q->selectRaw('1')->from('portal_superuser_pair')
|
||||
->where(fn ($holders) => $holders->whereColumn('first_user_id', 'portal_security_approvals.approved_by')->orWhereColumn('second_user_id', 'portal_security_approvals.approved_by')))
|
||||
->where('scope->action', $action)->where('scope->record_id', $recordId)->exists();
|
||||
}
|
||||
|
||||
public function canCreate(User $actor, ?string $organization, string $type): bool
|
||||
{
|
||||
$included = in_array($type, OpportunityCanonicalContract::BASE_CATEGORIES, true) || app(OpportunityModularProfiles::class)->enabled();
|
||||
|
||||
return $included && $this->available() && $this->scoped($actor, 'promoter', $organization, $type) && $this->operational($actor, 'create');
|
||||
}
|
||||
|
||||
public function legacyWriteAllowed(User $actor): bool
|
||||
{
|
||||
// A deliberate v1 assignment cannot use the old allowlist to bypass its scope.
|
||||
if (! $actor->can('manage-portal')) {
|
||||
return false;
|
||||
}
|
||||
if (! Schema::hasTable('portal_role_assignments')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Revocation/expiry must not silently restore an older, wider privilege.
|
||||
return ! DB::table('portal_role_assignments')->where('user_id', $actor->id)->exists()
|
||||
&& ! DB::table('portal_superuser_pair')->where(fn ($q) => $q->where('first_user_id', $actor->id)->orWhere('second_user_id', $actor->id))->exists()
|
||||
&& ! DB::table('portal_security_approvals')->where('kind', 'replacement')->whereNotNull('consumed_at')->where('scope->old_user_id', $actor->id)->exists();
|
||||
}
|
||||
|
||||
public function canView(User $actor, Opportunity $record): bool
|
||||
{
|
||||
if ($record->owner_user_id === null) {
|
||||
return $actor->can('manage-portal');
|
||||
}
|
||||
if (! $this->available() || ! $actor->hasVerifiedEmail()) {
|
||||
return false;
|
||||
}
|
||||
if ($this->has($actor, 'auditor') || $this->superuser($actor)) {
|
||||
return true;
|
||||
}
|
||||
$personal = $record->organization_id !== null || (int) $record->owner_user_id === $actor->id;
|
||||
|
||||
return ($personal && $this->scoped($actor, 'promoter', $record->organization_id, $record->opportunity_category))
|
||||
|| $this->scoped($actor, 'validator', $record->organization_id, $record->opportunity_category)
|
||||
|| $this->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category);
|
||||
}
|
||||
|
||||
public function canEdit(User $actor, Opportunity $record, ?string $newType = null): bool
|
||||
{
|
||||
if ($record->owner_user_id === null) {
|
||||
return $this->legacyWriteAllowed($actor);
|
||||
}
|
||||
|
||||
return $this->canView($actor, $record) && ! $record->trashed()
|
||||
&& in_array($this->state($record), ['draft', 'needs_information'], true)
|
||||
&& $this->scoped($actor, 'promoter', $record->organization_id, $newType ?? $record->opportunity_category)
|
||||
&& $this->operational($actor, 'edit', $record->id);
|
||||
}
|
||||
|
||||
public function conflict(User $actor, Opportunity $record): bool
|
||||
{
|
||||
$context = $record->workflow_context ?? [];
|
||||
|
||||
return (int) $record->owner_user_id === $actor->id || in_array($actor->id, $context['contributors'] ?? [], true)
|
||||
|| ($record->organization_id !== null && DB::table('memberships')->where('user_id', $actor->id)
|
||||
->where('organization_id', $record->organization_id)->whereNull('deleted_at')->exists());
|
||||
}
|
||||
|
||||
public function state(Opportunity $record): string
|
||||
{
|
||||
return $record->workflow_context['working_state'] ?? $record->status;
|
||||
}
|
||||
|
||||
public function authorize(User $actor, string $action, Opportunity $record): void
|
||||
{
|
||||
$allowed = $action === 'view' ? $this->canView($actor, $record) : $this->canEdit($actor, $record);
|
||||
if (! $allowed) {
|
||||
$this->audit($actor, 'access_denied', ['record_id' => $record->id, 'action' => $action]);
|
||||
}
|
||||
abort_unless($allowed, 403, 'O perfil, representação, tipo ou estado não autoriza esta operação.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Opportunity> $query
|
||||
* @return Builder<Opportunity>
|
||||
*/
|
||||
public function scope(Builder $query, User $actor): Builder
|
||||
{
|
||||
if ($this->has($actor, 'auditor') || $this->superuser($actor)) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
return $query->where(function ($scope) use ($actor) {
|
||||
$scope->whereRaw('1=0');
|
||||
if ($actor->can('manage-portal')) {
|
||||
$scope->orWhereNull('owner_user_id');
|
||||
}
|
||||
foreach ($this->grants($actor) as $grant) {
|
||||
if ($grant->role === 'promoter' && ! $this->represents($actor, $grant->organization_id)) {
|
||||
continue;
|
||||
}
|
||||
$scope->orWhere(function ($allowed) use ($actor, $grant) {
|
||||
$allowed->whereNotNull('owner_user_id')->whereIn('opportunity_category', json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR));
|
||||
if ($grant->organization_id !== null) {
|
||||
$allowed->where('organization_id', $grant->organization_id);
|
||||
} elseif ($grant->role === 'promoter') {
|
||||
$allowed->whereNull('organization_id')->where('owner_user_id', $actor->id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function navigation(?User $actor): ?array
|
||||
{
|
||||
if (! $actor || ! $this->available() || ! $actor->hasVerifiedEmail()) {
|
||||
return null;
|
||||
}
|
||||
$contexts = [];
|
||||
$seen = [];
|
||||
foreach ($this->grants($actor, 'promoter') as $grant) {
|
||||
if (! $this->represents($actor, $grant->organization_id)) {
|
||||
continue;
|
||||
}
|
||||
foreach (json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR) as $type) {
|
||||
$key = ($grant->organization_id ?? 'individual').'|'.$type;
|
||||
if (! isset($seen[$key]) && $this->canCreate($actor, $grant->organization_id, $type)) {
|
||||
$contexts[] = ['organization_id' => $grant->organization_id, 'type' => $type];
|
||||
$seen[$key] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['contexts' => $contexts, 'mine' => $contexts ? '/minhas-oportunidades' : null, 'create' => $contexts ? '/minhas-oportunidades/create' : null,
|
||||
'request' => '/perfil/promotor', 'review' => $this->has($actor, 'validator') || $this->has($actor, 'publisher') || $this->has($actor, 'auditor') || $this->superuser($actor) ? '/minhas-oportunidades' : null,
|
||||
'audit' => $this->has($actor, 'auditor') || $this->superuser($actor) ? '/perfis/auditoria' : null, 'administration' => $this->superuser($actor) ? '/perfis/gestao' : null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
public function audit(User $actor, string $action, array $data): void
|
||||
{
|
||||
DB::table('audit_events')->insert(['source_system' => 'portal-profiles-v1', 'entity_type' => 'authorization', 'actor_user_id' => $actor->id,
|
||||
'action' => $action, 'data_classification' => 'restricted', 'correlation_id' => (string) Str::uuid(),
|
||||
'after_data' => json_encode([...$data, 'policy_version' => self::VERSION, 'origin_ip' => request()->ip()], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
|
||||
public function revokeSessions(User $subject): void
|
||||
{
|
||||
DB::table('users')->where('id', $subject->id)->increment('portal_access_revision');
|
||||
// Invalidate remember-me as well; no password or MFA changes.
|
||||
DB::table('users')->where('id', $subject->id)->update(['remember_token' => null]);
|
||||
if (Schema::hasTable('sessions')) {
|
||||
DB::table('sessions')->where('user_id', $subject->id)->delete();
|
||||
}
|
||||
if (Schema::hasTable('personal_access_tokens')) {
|
||||
DB::table('personal_access_tokens')->where('tokenable_type', User::class)->where('tokenable_id', $subject->id)->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\HeaderUtils;
|
||||
|
||||
/** Authorization/publication stays with the consumer; originals share integrity and cipher handling. */
|
||||
class VerifiedDocumentBinary
|
||||
{
|
||||
public function respond(\stdClass $document, bool $inline = false): Response|BinaryFileResponse
|
||||
{
|
||||
$this->authorizeOpportunityAttachment($document);
|
||||
abort_unless($document->status === 'active' && $document->malware_scan_status === 'clean'
|
||||
&& ($document->deleted_at ?? null) === null && hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
|
||||
$disk = Storage::disk('local');
|
||||
$root = realpath($disk->path(''));
|
||||
$path = realpath($disk->path($document->storage_key));
|
||||
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
|
||||
$headers = ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, no-store'];
|
||||
if ($inline) {
|
||||
$headers['Content-Type'] = $document->media_type;
|
||||
$headers['Content-Security-Policy'] = "sandbox; default-src 'none'; style-src 'unsafe-inline'";
|
||||
}
|
||||
if (($document->storage_encryption ?? null) === 'laravel') {
|
||||
try {
|
||||
$bytes = Crypt::decryptString($disk->get($document->storage_key));
|
||||
} catch (DecryptException) {
|
||||
abort(404);
|
||||
}
|
||||
abort_unless(hash_equals(trim($document->sha256), hash('sha256', $bytes)), 404);
|
||||
$headers['Content-Type'] = $document->media_type;
|
||||
$headers['Content-Disposition'] = HeaderUtils::makeDisposition($inline ? 'inline' : 'attachment', basename($document->file_name), 'document');
|
||||
|
||||
return response($bytes, 200, $headers);
|
||||
}
|
||||
abort_unless(($document->storage_encryption ?? null) === null, 404);
|
||||
$checksum = hash_file('sha256', $path);
|
||||
abort_unless(is_string($checksum) && hash_equals(trim($document->sha256), $checksum), 404);
|
||||
|
||||
return $inline ? response()->file($path, $headers)->setContentDisposition('inline', basename($document->file_name)) : response()->download($path, basename($document->file_name), $headers);
|
||||
}
|
||||
|
||||
/** The general document route must not bypass the opportunity's current authorization. */
|
||||
private function authorizeOpportunityAttachment(\stdClass $document): void
|
||||
{
|
||||
$links = collect();
|
||||
foreach (['opportunity_documents', 'opportunity_images'] as $table) {
|
||||
if (! Schema::hasTable($table)) {
|
||||
continue;
|
||||
}
|
||||
$query = DB::table($table)->where('document_id', $document->id);
|
||||
if ($table === 'opportunity_images') {
|
||||
$query->orWhereRaw("payload->'derivatives' @> ?::jsonb", [json_encode([['document_id' => $document->id]], JSON_THROW_ON_ERROR)]);
|
||||
}
|
||||
$links = $links->concat($query->get(['opportunity_id', 'deleted_at']));
|
||||
}
|
||||
$privateOrigin = in_array($document->source_system ?? null, ['opportunity-resources', 'opportunity-image-derivatives'], true);
|
||||
if ($links->isEmpty() && ! $privateOrigin) {
|
||||
return; // Other consumers retain their own publication/authorization rules.
|
||||
}
|
||||
$actor = request()->user();
|
||||
abort_unless($actor instanceof \App\Models\User, 403, 'Anexo privado: é necessário acesso autorizado à oportunidade.');
|
||||
foreach ($links as $link) {
|
||||
$opportunity = \App\Models\Opportunity::find($link->opportunity_id);
|
||||
if ($link->deleted_at === null && $opportunity && $opportunity->status !== 'archived'
|
||||
&& app(PortalProfileAccess::class)->canView($actor, $opportunity)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
abort(403, 'O perfil atual não autoriza consultar este anexo da oportunidade.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user