@@ -13,6 +13,7 @@ final class EvidenceRepository
|
||||
->where('s.status', 'approved')->where('s.purpose', 'investment_information')
|
||||
->where('s.valid_until', '>=', now()->toDateString())->where('s.source_date', '<=', now()->toDateString())
|
||||
->where('d.status', 'active')->whereNull('d.deleted_at')->whereIn('d.data_classification', ['public', 'internal'])
|
||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256')
|
||||
->whereColumn('s.document_version', 'd.version_no')->whereColumn('s.document_checksum', 'd.sha256');
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ final class SourceIngestion
|
||||
{
|
||||
return DB::transaction(function () use ($data, $actor): string {
|
||||
$document = DB::table('documents')->where('id', $data['document_id'])->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
if (! $document || $document->status !== 'active' || $document->media_type !== 'text/plain'
|
||||
if (! $document || $document->status !== 'active' || $document->malware_scan_status !== 'clean'
|
||||
|| ! hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)) || $document->media_type !== 'text/plain'
|
||||
|| ! in_array($document->data_classification, ['public', 'internal'], true)) {
|
||||
throw ValidationException::withMessages(['document_id' => 'Documento activo de texto autorizado necessário; fontes confidenciais/restritas não são admitidas.']);
|
||||
}
|
||||
|
||||
@@ -3,37 +3,77 @@
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class BusinessFormSchema
|
||||
{
|
||||
/** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,string>}> */
|
||||
/** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,string>,when?:array<string,list<string>>}> */
|
||||
public static function fields(): array
|
||||
{
|
||||
return [
|
||||
'proponent_type' => ['step' => 1, 'pt' => 'Tipo de proponente', 'en' => 'Applicant type', 'type' => 'select', 'max' => 30, 'options' => ['person' => 'Pessoa / Person', 'organization' => 'Organização / Organization']],
|
||||
'proponent_type' => ['step' => 1, 'pt' => 'Quem apresenta a oportunidade?', 'en' => 'Who is presenting the opportunity?', 'type' => 'select', 'max' => 30, 'options' => ['organization' => 'Empresa ou organização / Company or organization', 'sole_trader' => 'Empresário em nome individual / Sole trader', 'person' => 'Pessoa singular / Individual', 'public_entity' => 'Entidade pública / Public entity']],
|
||||
'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200],
|
||||
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador', 'en' => 'Tax identifier', 'type' => 'text', 'max' => 50],
|
||||
'contact_email' => ['step' => 1, 'pt' => 'Email de contacto', 'en' => 'Contact email', 'type' => 'email', 'max' => 254],
|
||||
'contact_phone' => ['step' => 1, 'pt' => 'Telefone', 'en' => 'Phone', 'type' => 'tel', 'max' => 40],
|
||||
'country' => ['step' => 1, 'pt' => 'País (código de duas letras)', 'en' => 'Country (two-letter code)', 'type' => 'text', 'max' => 2],
|
||||
'country' => ['step' => 1, 'pt' => 'País de origem ou constituição (código ISO de duas letras)', 'en' => 'Country of origin or incorporation (two-letter ISO code)', 'type' => 'text', 'max' => 2],
|
||||
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador (interno, quando aplicável)', 'en' => 'NUIT or identifier (internal, when applicable)', 'type' => 'text', 'max' => 50],
|
||||
'contact_name' => ['step' => 1, 'pt' => 'Nome da pessoa de contacto', 'en' => 'Contact person name', 'type' => 'text', 'max' => 200],
|
||||
'contact_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254],
|
||||
'contact_phone' => ['step' => 1, 'pt' => 'Telefone (indique telefone ou email)', 'en' => 'Phone (provide phone or email)', 'type' => 'tel', 'max' => 40],
|
||||
'contact_preference' => ['step' => 1, 'pt' => 'Preferência de contacto', 'en' => 'Contact preference', 'type' => 'select', 'max' => 30, 'options' => ['through_portal' => 'Receber pedidos através da InvestMoz', 'approved_business_contact' => 'Mostrar contacto empresarial aprovado']],
|
||||
'acting_capacity' => ['step' => 2, 'pt' => 'Qualidade em que actua', 'en' => 'Acting capacity', 'type' => 'select', 'max' => 30, 'options' => ['holder' => 'Titular / Holder', 'representative' => 'Representante / Representative']],
|
||||
'declared_holder' => ['step' => 2, 'pt' => 'Titular declarado', 'en' => 'Declared holder', 'type' => 'text', 'max' => 200],
|
||||
'mandate_reference' => ['step' => 2, 'pt' => 'Referência do mandato', 'en' => 'Mandate reference', 'type' => 'text', 'max' => 500],
|
||||
'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10],
|
||||
'declared_holder' => ['step' => 2, 'pt' => 'Entidade ou pessoa representada', 'en' => 'Entity or person represented', 'type' => 'text', 'max' => 200],
|
||||
'mandate_reference' => ['step' => 2, 'pt' => 'Referência do documento de autorização', 'en' => 'Authorization document reference', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'mandate_document_reference' => ['step' => 2, 'pt' => 'Referência interna do documento de autorização (não carregue aqui)', 'en' => 'Internal authorization document reference (do not upload here)', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'disclosure_scope' => ['step' => 2, 'pt' => 'Limites da autorização de divulgação', 'en' => 'Limits of disclosure authorization', 'type' => 'textarea', 'max' => 2000, 'when' => ['acting_capacity' => ['representative']]],
|
||||
'legitimacy_declaration' => ['step' => 2, 'pt' => 'Declaro legitimidade para esta submissão', 'en' => 'I declare authority to submit', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim / Yes', 'no' => 'Não / No']],
|
||||
'title' => ['step' => 3, 'pt' => 'Título proposto', 'en' => 'Proposed title', 'type' => 'text', 'max' => 200],
|
||||
'description' => ['step' => 3, 'pt' => 'Descrição reservada', 'en' => 'Private description', 'type' => 'textarea', 'max' => 10000],
|
||||
'opportunity_type' => ['step' => 3, 'pt' => 'Tipo de oportunidade', 'en' => 'Opportunity type', 'type' => 'select', 'max' => 40, 'options' => ['investment_project' => 'Projecto de investimento', 'company_sale' => 'Venda de negócio existente', 'asset_sale' => 'Activo disponível', 'business_partnership' => 'Parceria empresarial', 'financing_request' => 'Procura de financiamento', 'concession_opportunity' => 'Concessão', 'supply_opportunity' => 'Oportunidade de fornecimento']],
|
||||
'description' => ['step' => 3, 'pt' => 'Descrição resumida: o que está disponível, procura e condições principais', 'en' => 'Summary: what is available, sought and key conditions', 'type' => 'textarea', 'max' => 10000],
|
||||
'subsector_activity' => ['step' => 3, 'pt' => 'Subsector e actividade (por designação)', 'en' => 'Subsector and activity (by name)', 'type' => 'text', 'max' => 500],
|
||||
'declared_reason' => ['step' => 3, 'pt' => 'Motivo e objectivo', 'en' => 'Reason and objective', 'type' => 'textarea', 'max' => 2000],
|
||||
'valid_until' => ['step' => 3, 'pt' => 'Validade declarada', 'en' => 'Declared expiry', 'type' => 'date', 'max' => 10],
|
||||
'asking_value' => ['step' => 4, 'pt' => 'Valor pedido', 'en' => 'Asking value', 'type' => 'decimal', 'max' => 24],
|
||||
'currency' => ['step' => 4, 'pt' => 'Moeda (código de três letras)', 'en' => 'Currency (three-letter code)', 'type' => 'text', 'max' => 3],
|
||||
'value_nature' => ['step' => 4, 'pt' => 'Natureza do valor', 'en' => 'Value basis', 'type' => 'select', 'max' => 30, 'options' => ['asking' => 'Pedido / Asking', 'indicative' => 'Indicativo / Indicative', 'appraised' => 'Avaliado, sujeito a prova / Appraised, evidence required']],
|
||||
'project_stage' => ['step' => 3, 'pt' => 'Situação do projecto ou negócio', 'en' => 'Project or business status', 'type' => 'select', 'max' => 40, 'options' => ['idea' => 'Ideia ou conceito', 'study' => 'Em estudo', 'preparation' => 'Em preparação', 'implementation' => 'Em implementação', 'operating' => 'Em funcionamento', 'suspended' => 'Actividade suspensa', 'other' => 'Outra situação']],
|
||||
'project_stage_other' => ['step' => 3, 'pt' => 'Especifique a situação', 'en' => 'Specify the status', 'type' => 'text', 'max' => 200, 'when' => ['project_stage' => ['other']]],
|
||||
'availability' => ['step' => 3, 'pt' => 'Disponibilidade', 'en' => 'Availability', 'type' => 'select', 'max' => 40, 'options' => ['available' => 'Disponível', 'from_date' => 'Disponível a partir de uma data', 'negotiating' => 'Em negociação; aceita manifestações de interesse']],
|
||||
'available_from' => ['step' => 3, 'pt' => 'Disponível a partir de', 'en' => 'Available from', 'type' => 'date', 'max' => 10, 'when' => ['availability' => ['from_date']]],
|
||||
'valid_until' => ['step' => 3, 'pt' => 'Prazo para manifestações de interesse (opcional)', 'en' => 'Interest deadline (optional)', 'type' => 'date', 'max' => 10],
|
||||
'asking_value' => ['step' => 4, 'pt' => 'Valor', 'en' => 'Value', 'type' => 'decimal', 'max' => 24, 'when' => ['value_status' => ['defined', 'indicative']]],
|
||||
'value_status' => ['step' => 4, 'pt' => 'O valor está definido?', 'en' => 'Is the value defined?', 'type' => 'select', 'max' => 30, 'options' => ['defined' => 'Sim', 'indicative' => 'Valor indicativo', 'consultation' => 'Sob consulta', 'unknown' => 'Ainda não definido']],
|
||||
'value_meaning' => ['step' => 4, 'pt' => 'Significado do valor', 'en' => 'Meaning of the value', 'type' => 'select', 'max' => 30, 'options' => ['asking_price' => 'Preço pedido', 'investment_estimate' => 'Investimento estimado', 'financing_sought' => 'Financiamento procurado'], 'when' => ['value_status' => ['defined', 'indicative']]],
|
||||
'value_nature' => ['step' => 4, 'pt' => 'Natureza do valor', 'en' => 'Value basis', 'type' => 'select', 'max' => 30, 'options' => ['asking' => 'Pedido', 'indicative' => 'Indicativo', 'appraised' => 'Avaliado, sujeito a prova'], 'when' => ['value_status' => ['defined', 'indicative']]],
|
||||
'currency' => ['step' => 4, 'pt' => 'Moeda (código de três letras)', 'en' => 'Currency (three-letter code)', 'type' => 'text', 'max' => 3, 'when' => ['value_status' => ['defined', 'indicative']]],
|
||||
'amount_secured' => ['step' => 4, 'pt' => 'Montante assegurado (projectos)', 'en' => 'Secured amount (projects)', 'type' => 'decimal', 'max' => 24, 'when' => ['opportunity_type' => ['investment_project']]],
|
||||
'investment_total' => ['step' => 4, 'pt' => 'Investimento total estimado (projectos)', 'en' => 'Estimated total investment (projects)', 'type' => 'decimal', 'max' => 24, 'when' => ['opportunity_type' => ['investment_project']]],
|
||||
'amount_sought' => ['step' => 4, 'pt' => 'Montante de financiamento procurado', 'en' => 'Financing sought', 'type' => 'decimal', 'max' => 24, 'when' => ['opportunity_type' => ['investment_project', 'financing_request']]],
|
||||
'equity_percentage' => ['step' => 4, 'pt' => 'Participação disponível (%)', 'en' => 'Available equity (%)', 'type' => 'decimal', 'max' => 8],
|
||||
'funds_use' => ['step' => 4, 'pt' => 'Utilização dos fundos', 'en' => 'Use of funds', 'type' => 'textarea', 'max' => 2000],
|
||||
'location_notes' => ['step' => 5, 'pt' => 'Localização declarada (reservada)', 'en' => 'Declared location (private)', 'type' => 'textarea', 'max' => 2000],
|
||||
'asset_deal_kind' => ['step' => 4, 'pt' => 'Tipo de venda', 'en' => 'Type of sale', 'type' => 'select', 'max' => 30, 'options' => ['whole_business' => 'Venda total', 'participation' => 'Participação', 'assets' => 'Activos'], 'when' => ['opportunity_type' => ['company_sale', 'asset_sale']]],
|
||||
'partnership_contribution' => ['step' => 4, 'pt' => 'Contribuição pretendida', 'en' => 'Contribution sought', 'type' => 'select', 'max' => 30, 'options' => ['capital' => 'Capital', 'technology' => 'Tecnologia', 'management' => 'Gestão', 'equipment' => 'Equipamento', 'distribution' => 'Distribuição', 'other' => 'Outra'], 'when' => ['opportunity_type' => ['business_partnership']]],
|
||||
'asset_modality' => ['step' => 4, 'pt' => 'Modalidade do activo', 'en' => 'Asset arrangement', 'type' => 'select', 'max' => 30, 'options' => ['sale' => 'Venda', 'lease' => 'Arrendamento', 'other' => 'Outra'], 'when' => ['opportunity_type' => ['asset_sale']]],
|
||||
'concession_entity' => ['step' => 4, 'pt' => 'Entidade responsável pela concessão', 'en' => 'Concession authority', 'type' => 'text', 'max' => 300, 'when' => ['opportunity_type' => ['concession_opportunity']]],
|
||||
'concession_reference' => ['step' => 4, 'pt' => 'Referência oficial, procedimento e prazo', 'en' => 'Official reference, procedure and deadline', 'type' => 'textarea', 'max' => 2000, 'when' => ['opportunity_type' => ['concession_opportunity']]],
|
||||
'supply_description' => ['step' => 4, 'pt' => 'Bem ou serviço, quantidade/capacidade, destino e prazo', 'en' => 'Good or service, quantity/capacity, destination and timing', 'type' => 'textarea', 'max' => 2000, 'when' => ['opportunity_type' => ['supply_opportunity']]],
|
||||
'conditions' => ['step' => 4, 'pt' => 'Condições adicionais', 'en' => 'Additional conditions', 'type' => 'textarea', 'max' => 4000],
|
||||
'geography_scope' => ['step' => 5, 'pt' => 'Âmbito geográfico', 'en' => 'Geographic scope', 'type' => 'select', 'max' => 30, 'options' => ['specific' => 'Localização específica', 'multiple' => 'Várias localizações', 'national' => 'Âmbito nacional', 'digital' => 'Digital/sem instalação definida']],
|
||||
'province_id' => ['step' => 5, 'pt' => 'Província ou Cidade de Maputo', 'en' => 'Province or Maputo City', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
'district_id' => ['step' => 5, 'pt' => 'Distrito', 'en' => 'District', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
'admin_post_id' => ['step' => 5, 'pt' => 'Posto administrativo', 'en' => 'Administrative post', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
'locality_id' => ['step' => 5, 'pt' => 'Localidade', 'en' => 'Locality', 'type' => 'territory', 'max' => 36, 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
'locations_json' => ['step' => 5, 'pt' => 'Localizações administrativas (várias)', 'en' => 'Administrative locations (multiple)', 'type' => 'location_list', 'max' => 16000, 'when' => ['geography_scope' => ['multiple']]],
|
||||
'location_notes' => ['step' => 5, 'pt' => 'Endereço ou referência (interno)', 'en' => 'Address or reference (internal)', 'type' => 'textarea', 'max' => 2000],
|
||||
'location_unknown' => ['step' => 5, 'pt' => 'Não conheço a localização exacta', 'en' => 'I do not know the exact location', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim', 'no' => 'Não'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
'disclosure_precision' => ['step' => 5, 'pt' => 'Precisão de divulgação', 'en' => 'Disclosure precision', 'type' => 'select', 'max' => 30, 'options' => ['exact' => 'Localização exacta (sujeita a aprovação)', 'approximate' => 'Localização aproximada', 'administrative' => 'Apenas território administrativo'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
|
||||
'asset_notes' => ['step' => 6, 'pt' => 'Resumo dos activos e direitos declarados', 'en' => 'Declared assets and rights summary', 'type' => 'textarea', 'max' => 2000],
|
||||
'source_reference' => ['step' => 7, 'pt' => 'Referência da fonte', 'en' => 'Source reference', 'type' => 'textarea', 'max' => 2000],
|
||||
'source_provider' => ['step' => 7, 'pt' => 'Quem forneceu os dados?', 'en' => 'Who supplied the information?', 'type' => 'text', 'max' => 500],
|
||||
'source_date' => ['step' => 7, 'pt' => 'Data da fonte/informação', 'en' => 'Source/information date', 'type' => 'date', 'max' => 10],
|
||||
'official_source_entity' => ['step' => 7, 'pt' => 'Entidade da fonte oficial (se existir)', 'en' => 'Official source authority (if any)', 'type' => 'text', 'max' => 500],
|
||||
'official_source_document' => ['step' => 7, 'pt' => 'Documento oficial associado', 'en' => 'Related official document', 'type' => 'text', 'max' => 500],
|
||||
'official_source_url' => ['step' => 7, 'pt' => 'Ligação da fonte oficial', 'en' => 'Official source link', 'type' => 'url', 'max' => 2000],
|
||||
'official_source_period' => ['step' => 7, 'pt' => 'Período da fonte oficial', 'en' => 'Official source period', 'type' => 'text', 'max' => 200],
|
||||
'document_reference' => ['step' => 7, 'pt' => 'Referências documentais (não são ficheiros validados)', 'en' => 'Document references (not validated files)', 'type' => 'textarea', 'max' => 2000],
|
||||
'confirm_information' => ['step' => 8, 'pt' => 'Confirmo que a informação corresponde ao que conheço e identifiquei estimativas ou pendências.', 'en' => 'I confirm the information reflects what I know and identify estimates or pending items.', 'type' => 'checkbox', 'max' => 3, 'options' => ['yes' => 'yes']],
|
||||
'confirm_disclosure_authority' => ['step' => 8, 'pt' => 'Confirmo que tenho autorização para apresentar a oportunidade e divulgar os conteúdos seleccionados.', 'en' => 'I confirm I am authorized to submit the opportunity and disclose selected content.', 'type' => 'checkbox', 'max' => 3, 'options' => ['yes' => 'yes']],
|
||||
'confirm_no_publication_guarantee' => ['step' => 8, 'pt' => 'Compreendo que a submissão não constitui publicação, aprovação oficial ou garantia de investimento.', 'en' => 'I understand submission is not publication, official approval or an investment guarantee.', 'type' => 'checkbox', 'max' => 3, 'options' => ['yes' => 'yes']],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -47,34 +87,108 @@ final class BusinessFormSchema
|
||||
$rules['payload.'.$key][] = 'in:'.implode(',', array_keys($field['options']));
|
||||
}
|
||||
}
|
||||
$rules['payload.contact_email'][] = 'nullable';
|
||||
$rules['payload.contact_email'][] = 'email';
|
||||
$rules['payload.country'][] = 'regex:/^[A-Z]{2}$/';
|
||||
$rules['payload.currency'][] = 'regex:/^[A-Z]{3}$/';
|
||||
$rules['payload.asking_value'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.amount_secured'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.investment_total'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.amount_sought'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
|
||||
$rules['payload.source_date'][] = 'date_format:Y-m-d';
|
||||
$rules['payload.official_source_url'][] = 'url';
|
||||
$rules['payload.equity_percentage'][] = 'numeric';
|
||||
$rules['payload.equity_percentage'][] = 'between:0,100';
|
||||
foreach (['valid_until', 'mandate_valid_until'] as $date) {
|
||||
$rules['payload.'.$date][] = 'date_format:Y-m-d';
|
||||
}
|
||||
$rules['payload.wizard_version'] = ['nullable', 'in:1'];
|
||||
$rules['payload.wizard_version'] = ['nullable', 'in:1,2'];
|
||||
$rules['payload.wizard_step'] = ['nullable', 'integer', 'between:1,8'];
|
||||
$rules['payload.locations_json'][] = 'json';
|
||||
$rules['payload.title'] = ['required', 'string', 'max:200'];
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
public static function validateSubmission(array $payload): void
|
||||
public static function validateSubmission(array $payload, ?int $sectorId, string $modality): void
|
||||
{
|
||||
if (($payload['opportunity_type'] ?? null) !== $modality) {
|
||||
throw ValidationException::withMessages(['opportunity_type' => 'O tipo da oportunidade não corresponde à classificação guardada.']);
|
||||
}
|
||||
|
||||
$rules = [];
|
||||
foreach (['proponent_type', 'proponent_name', 'tax_identifier', 'contact_email', 'country', 'acting_capacity', 'declared_holder', 'location_notes'] as $field) {
|
||||
foreach (['proponent_type', 'proponent_name', 'contact_name', 'country', 'acting_capacity', 'title', 'opportunity_type', 'description', 'project_stage', 'availability', 'geography_scope', 'source_reference', 'source_provider', 'source_date'] as $field) {
|
||||
$rules[$field] = ['required'];
|
||||
}
|
||||
$rules['sector_id'] = ['required'];
|
||||
$rules['contact_email'] = ['required_without:contact_phone', 'nullable', 'email'];
|
||||
$rules['contact_phone'] = ['required_without:contact_email', 'nullable', 'string', 'regex:/^[+0-9() .-]{7,40}$/'];
|
||||
$rules['legitimacy_declaration'] = ['required', 'in:yes'];
|
||||
foreach (['confirm_information', 'confirm_disclosure_authority', 'confirm_no_publication_guarantee'] as $confirmation) {
|
||||
$rules[$confirmation] = ['required', 'in:yes'];
|
||||
}
|
||||
$rules['mandate_reference'] = ['required_if:acting_capacity,representative'];
|
||||
$rules['mandate_valid_until'] = ['required_if:acting_capacity,representative', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'];
|
||||
$rules['currency'] = ['required_with:asking_value'];
|
||||
$rules['value_nature'] = ['required_with:asking_value'];
|
||||
Validator::make($payload, $rules)->validate();
|
||||
$rules['declared_holder'] = ['required_if:acting_capacity,representative'];
|
||||
$rules['disclosure_scope'] = ['required_if:acting_capacity,representative'];
|
||||
$rules['mandate_valid_until'] = ['nullable', 'date_format:Y-m-d', 'after_or_equal:today'];
|
||||
$rules['mandate_document_reference'] = ['required_if:acting_capacity,representative'];
|
||||
$rules['project_stage_other'] = ['required_if:project_stage,other'];
|
||||
$rules['available_from'] = ['required_if:availability,from_date', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'];
|
||||
$rules['value_status'] = ['required', 'in:defined,indicative,consultation,unknown'];
|
||||
$rules['province_id'] = ['required_if:geography_scope,specific', 'nullable', 'uuid'];
|
||||
foreach (['district_id', 'admin_post_id', 'locality_id'] as $locationField) {
|
||||
$rules[$locationField] = ['nullable', 'uuid'];
|
||||
}
|
||||
$rules['locations_json'] = ['required_if:geography_scope,multiple', 'nullable', 'json', 'max:16000'];
|
||||
$rules['asking_value'] = ['required_if:value_status,defined,indicative', 'nullable', 'numeric', 'min:0'];
|
||||
$rules['currency'] = ['required_if:value_status,defined,indicative', 'nullable', 'regex:/^[A-Z]{3}$/'];
|
||||
$rules['value_meaning'] = ['required_if:value_status,defined,indicative'];
|
||||
$rules['amount_secured'] = ['nullable', 'numeric', 'min:0'];
|
||||
$rules['investment_total'] = ['required_if:opportunity_type,investment_project', 'nullable', 'numeric', 'gt:0'];
|
||||
$rules['amount_sought'] = ['nullable', 'numeric', 'min:0'];
|
||||
$rules['equity_percentage'] = ['nullable', 'numeric', 'between:0,100'];
|
||||
$rules['asset_deal_kind'] = ['required_if:opportunity_type,company_sale,asset_sale'];
|
||||
$rules['equity_percentage'] = ['required_if:asset_deal_kind,participation', 'nullable', 'numeric', 'between:0,100'];
|
||||
$rules['partnership_contribution'] = ['required_if:opportunity_type,business_partnership'];
|
||||
$rules['amount_sought'] = ['required_if:opportunity_type,financing_request', 'nullable', 'numeric', 'min:0'];
|
||||
$rules['asset_modality'] = ['required_if:opportunity_type,asset_sale'];
|
||||
$rules['concession_entity'] = ['required_if:opportunity_type,concession_opportunity'];
|
||||
$rules['concession_reference'] = ['required_if:opportunity_type,concession_opportunity'];
|
||||
$rules['supply_description'] = ['required_if:opportunity_type,supply_opportunity'];
|
||||
Validator::make([...$payload, 'sector_id' => $sectorId, 'modality' => $modality], $rules)->validate();
|
||||
|
||||
$geography = app(InvestmentGeography::class);
|
||||
if (($payload['geography_scope'] ?? null) === 'specific') {
|
||||
$geography->selection(array_intersect_key($payload, array_flip(InvestmentGeography::FIELDS)));
|
||||
} elseif (($payload['geography_scope'] ?? null) === 'multiple') {
|
||||
$locations = json_decode($payload['locations_json'], true, 512, JSON_THROW_ON_ERROR);
|
||||
Validator::make(['locations' => $locations], [
|
||||
'locations' => ['required', 'array', 'min:2', 'max:20'],
|
||||
'locations.*' => ['required', 'array:province_id,district_id,admin_post_id,locality_id'],
|
||||
'locations.*.province_id' => ['required', 'uuid'],
|
||||
'locations.*.district_id' => ['nullable', 'uuid'],
|
||||
'locations.*.admin_post_id' => ['nullable', 'uuid'],
|
||||
'locations.*.locality_id' => ['nullable', 'uuid'],
|
||||
])->validate();
|
||||
|
||||
$paths = [];
|
||||
foreach ($locations as $index => $location) {
|
||||
$path = array_map(fn ($node) => (string) $node->id, $geography->selection($location));
|
||||
foreach ($paths as $existingPath) {
|
||||
$sharedPrefixLength = 0;
|
||||
while (isset($path[$sharedPrefixLength], $existingPath[$sharedPrefixLength])
|
||||
&& $path[$sharedPrefixLength] === $existingPath[$sharedPrefixLength]) {
|
||||
$sharedPrefixLength++;
|
||||
}
|
||||
if ($sharedPrefixLength === min(count($path), count($existingPath))) {
|
||||
throw ValidationException::withMessages([
|
||||
'locations_json' => 'As localizações devem ser distintas e não podem repetir ou conter o mesmo percurso administrativo.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
$paths[] = $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,13 @@ class ConvertInterestToLead
|
||||
{
|
||||
return DB::transaction(function () use ($interest, $data, $actor) {
|
||||
$interest = InterestRequest::lockForUpdate()->findOrFail($interest->id);
|
||||
$contactConsentIsCurrent = DB::table('consents')->where('interest_request_id', $interest->id)
|
||||
->where('subject_ref', $interest->reference)->where('purpose', 'respond_to_interest')
|
||||
->where('status', 'granted')->whereNotNull('granted_at')->where('granted_at', '<=', now())
|
||||
->whereNull('withdrawn_at')->whereNull('deleted_at')->lockForUpdate()->exists();
|
||||
if (! $interest->privacy_consent || ! $contactConsentIsCurrent) {
|
||||
throw ValidationException::withMessages(['investor_id' => 'O pedido não tem consentimento de contacto activo.']);
|
||||
}
|
||||
$existing = Lead::withTrashed()->where('interest_request_id', $interest->id)->first();
|
||||
if ($existing) {
|
||||
if ($existing->trashed()) {
|
||||
@@ -25,8 +32,8 @@ class ConvertInterestToLead
|
||||
|
||||
return $existing;
|
||||
}
|
||||
if (! $interest->privacy_consent) {
|
||||
throw ValidationException::withMessages(['investor_id' => 'O pedido não tem consentimento de contacto registado.']);
|
||||
if (! is_string($interest->email) || trim($interest->email) === '') {
|
||||
throw ValidationException::withMessages(['investor_id' => 'Confirme um email antes de converter este pedido telefonico num contacto/lead CRM.']);
|
||||
}
|
||||
$email = strtolower(trim($interest->email));
|
||||
$journeyInvestor = DB::table('investor_journeys')->where('interest_request_id', $interest->id)->whereNull('deleted_at')->value('investor_id');
|
||||
|
||||
@@ -15,7 +15,7 @@ use Illuminate\Validation\Rule;
|
||||
|
||||
final class ExistingBusinessDrafts
|
||||
{
|
||||
public const MODALITIES = ['company_sale', 'participation_sale', 'capital_increase', 'financial_investor', 'strategic_partner', 'buyer_search', 'position_assignment', 'franchise', 'asset_sale', 'asset_lease', 'business_unit_transfer', 'joint_venture', 'succession', 'recovery', 'expansion', 'internationalization', 'real_estate', 'agricultural_investment', 'land_right', 'mining_license', 'forestry_license'];
|
||||
public const MODALITIES = ['company_sale', 'participation_sale', 'capital_increase', 'financial_investor', 'strategic_partner', 'buyer_search', 'position_assignment', 'franchise', 'asset_sale', 'asset_lease', 'business_unit_transfer', 'joint_venture', 'succession', 'recovery', 'expansion', 'internationalization', 'real_estate', 'agricultural_investment', 'land_right', 'mining_license', 'forestry_license', 'investment_project', 'business_partnership', 'financing_request', 'concession_opportunity', 'supply_opportunity'];
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input, ?string $id = null): ExistingBusiness
|
||||
@@ -47,9 +47,6 @@ final class ExistingBusinessDrafts
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
if ($id) {
|
||||
$business = app(BusinessRepository::class)->find($id, true);
|
||||
if (($business->payload['wizard_version'] ?? null) === '1') {
|
||||
$data['payload']['wizard_version'] = '1';
|
||||
}
|
||||
Gate::forUser($actor)->authorize('update', $business);
|
||||
abort_unless($business->version_no === $data['version_no'], 409, 'O rascunho foi alterado. Recarregue antes de gravar.');
|
||||
$business->version_no++;
|
||||
|
||||
@@ -65,8 +65,8 @@ final class ExistingBusinessIntake
|
||||
];
|
||||
abort_unless(in_array($business->status, $allowed[$action], true), 409, 'Transição indisponível neste estado.');
|
||||
if ($action === 'submitted') {
|
||||
if (($business->payload['wizard_version'] ?? null) === '1') {
|
||||
BusinessFormSchema::validateSubmission($business->payload);
|
||||
if (($business->payload['wizard_version'] ?? null) === '2') {
|
||||
BusinessFormSchema::validateSubmission($business->payload, $business->sector_id, $business->modality);
|
||||
$requiredKind = ['asset_sale' => 'asset', 'asset_lease' => 'asset', 'real_estate' => 'property',
|
||||
'agricultural_investment' => 'agricultural_investment', 'land_right' => 'land_right',
|
||||
'mining_license' => 'license', 'forestry_license' => 'license', 'capital_increase' => 'capital_request',
|
||||
@@ -78,11 +78,40 @@ final class ExistingBusinessIntake
|
||||
'confirmation_code' => ['required', Rule::in([$business->code])],
|
||||
'sector_id' => ['required', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
|
||||
])->validate();
|
||||
} elseif (($business->payload['wizard_version'] ?? null) === '1') {
|
||||
Validator::make($business->payload, [
|
||||
'proponent_type' => ['required'], 'proponent_name' => ['required'], 'tax_identifier' => ['required'],
|
||||
'contact_email' => ['required', 'email'], 'country' => ['required', 'regex:/^[A-Z]{2}$/'],
|
||||
'acting_capacity' => ['required'], 'declared_holder' => ['required'], 'location_notes' => ['required'],
|
||||
'legitimacy_declaration' => ['required', 'in:yes'],
|
||||
'mandate_reference' => ['required_if:acting_capacity,representative'],
|
||||
'mandate_valid_until' => ['required_if:acting_capacity,representative', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'],
|
||||
])->validate();
|
||||
Validator::make(['confirmation_code' => $confirmationCode], [
|
||||
'confirmation_code' => ['required', Rule::in([$business->code])],
|
||||
])->validate();
|
||||
}
|
||||
Validator::make([...$business->payload, 'consent' => $consent], [
|
||||
'description' => ['required', 'string', 'min:30'], 'source_reference' => ['required', 'string', 'min:10'],
|
||||
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'], 'consent' => ['accepted'],
|
||||
])->validate();
|
||||
if (($business->payload['wizard_version'] ?? null) === '1') {
|
||||
$requiredKind = ['asset_sale' => 'asset', 'asset_lease' => 'asset', 'real_estate' => 'property',
|
||||
'agricultural_investment' => 'agricultural_investment', 'land_right' => 'land_right',
|
||||
'mining_license' => 'license', 'forestry_license' => 'license', 'capital_increase' => 'capital_request',
|
||||
'participation_sale' => 'participation'][$business->modality] ?? null;
|
||||
if ($requiredKind !== null && ! ExistingBusinessObject::where('business_id', $business->id)->where('kind', $requiredKind)->exists()) {
|
||||
throw ValidationException::withMessages(['objects' => 'Declare the applicable object in step 6: '.$requiredKind]);
|
||||
}
|
||||
}
|
||||
$submissionRules = [
|
||||
'description' => ['required', 'string', 'min:30'],
|
||||
'source_reference' => ['required', 'string', 'min:10'],
|
||||
'consent' => ['accepted'],
|
||||
// Deadlines are optional for newer and legacy payloads, but
|
||||
// an explicitly supplied deadline must never be expired.
|
||||
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:today'],
|
||||
];
|
||||
if (($business->payload['wizard_version'] ?? null) === '1') {
|
||||
$submissionRules['valid_until'][0] = 'required';
|
||||
}
|
||||
Validator::make([...$business->payload, 'consent' => $consent], $submissionRules)->validate();
|
||||
}
|
||||
if ($action === OpportunityStatus::Approved->value) {
|
||||
$levelOneActor = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
||||
|
||||
@@ -21,6 +21,8 @@ final class ExistingBusinessObjects
|
||||
'declared_holder' => ['nullable', 'string', 'max:500'],
|
||||
'document_reference' => ['nullable', 'string', 'max:1000'],
|
||||
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'source_date' => ['nullable', 'date_format:Y-m-d'],
|
||||
'resource_status' => ['nullable', 'in:available,contracted,planned,unconfirmed'],
|
||||
'competent_entity' => ['nullable', 'string', 'max:500'],
|
||||
'purpose' => ['nullable', 'string', 'max:2000'],
|
||||
'location_description' => ['nullable', 'string', 'max:2000'],
|
||||
|
||||
@@ -18,7 +18,9 @@ final class InterestSubmission
|
||||
{
|
||||
$canonical = array_replace(['phone' => null, 'opportunityReference' => null, 'existingBusinessId' => null,
|
||||
'modality' => null, 'investmentRange' => null, 'shareWithProponent' => false], $payload);
|
||||
$canonical['email'] = strtolower(trim($canonical['email']));
|
||||
$canonical['email'] = isset($canonical['email']) && trim((string) $canonical['email']) !== ''
|
||||
? strtolower(trim((string) $canonical['email']))
|
||||
: null;
|
||||
$canonical['fullName'] = trim($canonical['fullName']);
|
||||
$canonical['message'] = trim($canonical['message']);
|
||||
$canonical['privacyConsent'] = true; // FormRequest requires acceptance.
|
||||
|
||||
@@ -19,6 +19,7 @@ class InvestmentCatalogue
|
||||
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
||||
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
'include_national' => ['nullable', 'boolean'],
|
||||
'province' => ['nullable', 'string', 'max:100'], 'district' => ['nullable', 'string', 'max:100'],
|
||||
'cluster_id' => ['nullable', 'uuid'], 'corridor_id' => ['nullable', 'uuid'], 'project_id' => ['nullable', 'uuid'],
|
||||
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
|
||||
@@ -46,9 +47,19 @@ class InvestmentCatalogue
|
||||
$query->whereKey($filters['opportunity_id']);
|
||||
}
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
$includeNational = filter_var($filters['include_national'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
if ($path !== []) {
|
||||
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->whereIn('primary_territory_id', $ids);
|
||||
$query->where(function ($territory) use ($ids, $includeNational): void {
|
||||
$territory->whereIn('opportunities.primary_territory_id', $ids)
|
||||
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('opportunity_locations as territory_link')
|
||||
->whereColumn('territory_link.opportunity_id', 'opportunities.id')->whereIn('territory_link.geo_location_id', $ids));
|
||||
if ($includeNational) {
|
||||
$territory->orWhere('opportunities.geography_scope', 'national');
|
||||
}
|
||||
});
|
||||
} elseif (! $includeNational) {
|
||||
$query->where('opportunities.geography_scope', '!=', 'national');
|
||||
}
|
||||
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
|
||||
$query->whereIn('opportunities.id', app(InvestmentZones::class)->links()->join('investment_item_opportunities as mapping', 'mapping.item_id', '=', 'zl.item_id')
|
||||
@@ -83,8 +94,20 @@ class InvestmentCatalogue
|
||||
}
|
||||
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
||||
if (! empty($filters[$foreign])) {
|
||||
$locationIds = $relation === 'locations'
|
||||
? app(InvestmentGeography::class)->descendants((string) $filters[$foreign])
|
||||
: null;
|
||||
if ($relation === 'locations') {
|
||||
$query->where(fn ($matches) => $matches->whereIn('opportunities.primary_territory_id', $locationIds ?? [])
|
||||
->orWhereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_locations as link')
|
||||
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
|
||||
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
|
||||
->whereNull('target.deleted_at')->where('target.data_classification', 'public')));
|
||||
|
||||
continue;
|
||||
}
|
||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_'.$relation.' as link')->join($table.' as target', 'target.id', '=', 'link.'.$foreign)
|
||||
->whereColumn('link.opportunity_id', 'opportunities.id')->where('link.'.$foreign, $filters[$foreign])->whereNull('target.deleted_at')
|
||||
->whereColumn('link.opportunity_id', 'opportunities.id')->when($relation === 'locations', fn ($q) => $q->whereIn('link.'.$foreign, $locationIds ?? []), fn ($q) => $q->where('link.'.$foreign, $filters[$foreign]))->whereNull('target.deleted_at')
|
||||
->when($relation === 'locations', fn ($q) => $q->where('target.data_classification', 'public'),
|
||||
fn ($q) => $q->whereIn('target.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign))));
|
||||
}
|
||||
@@ -93,8 +116,10 @@ class InvestmentCatalogue
|
||||
$query->where(fn ($q) => $q->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('is_education', true))
|
||||
->orWhereExists(fn ($sub) => $sub->selectRaw('1')->from('education_investment_proposals')->whereColumn('opportunity_id', 'opportunities.id')->whereNull('deleted_at')));
|
||||
}
|
||||
foreach ($filters['facets'] ?? [] as $option) {
|
||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_facets')->whereColumn('opportunity_id', 'opportunities.id')->where('option_id', $option));
|
||||
$facetGroups = DB::table('investment_reference_options')->whereIn('id', $filters['facets'] ?? [])->get(['id', 'group'])->groupBy('group');
|
||||
foreach ($facetGroups as $options) {
|
||||
$optionIds = $options->pluck('id')->all();
|
||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_facets')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('option_id', $optionIds));
|
||||
}
|
||||
foreach (['min_amount' => '>=', 'max_amount' => '<='] as $field => $operator) {
|
||||
if (isset($filters[$field])) {
|
||||
@@ -118,7 +143,7 @@ class InvestmentCatalogue
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function references(bool $management = false): array
|
||||
public function references(bool $management = false, array $territoryFilters = []): array
|
||||
{
|
||||
$result = ['options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
||||
'sectors' => DB::table('sectors')->where('is_active', true)->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'slug'])];
|
||||
@@ -134,7 +159,11 @@ class InvestmentCatalogue
|
||||
$result[$relation] = $query->orderBy('name')->get(['id', 'name']);
|
||||
}
|
||||
|
||||
$result['zones'] = app(InvestmentZones::class)->visible()->orderBy('name')->get(['id', 'name', 'category']);
|
||||
$zones = app(InvestmentZones::class)->visible();
|
||||
if (! $management && $territoryFilters !== []) {
|
||||
$zones = app(InvestmentZones::class)->search($territoryFilters);
|
||||
}
|
||||
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
@@ -10,6 +11,44 @@ final class InvestmentGeography
|
||||
{
|
||||
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
||||
|
||||
/**
|
||||
* Restrict published dossier searches using direct territories and public, validated structure links.
|
||||
* @param EloquentBuilder<\App\Models\InvestmentDossier> $query
|
||||
* @param list<string> $territoryIds
|
||||
* @return EloquentBuilder<\App\Models\InvestmentDossier>
|
||||
*/
|
||||
public function constrainDossiersToTerritories(EloquentBuilder $query, array $territoryIds): EloquentBuilder
|
||||
{
|
||||
return $query->where(function ($matches) use ($territoryIds): void {
|
||||
$matches->whereIn('project_id', DB::table('projects')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
|
||||
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as pl')
|
||||
->whereColumn('pl.project_id', 'investment_dossiers.project_id')->whereNull('pl.deleted_at')
|
||||
->where('pl.data_classification', 'public')->whereIn('pl.geo_location_id', $territoryIds))
|
||||
->orWhereIn('cluster_id', DB::table('economic_clusters')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
|
||||
->orWhereIn('corridor_id', DB::table('development_corridors')->whereNull('deleted_at')->whereIn('primary_territory_id', $territoryIds)->select('id'))
|
||||
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('corridor_locations as cl')
|
||||
->whereColumn('cl.corridor_id', 'investment_dossiers.corridor_id')->whereNull('cl.deleted_at')
|
||||
->where('cl.data_classification', 'public')->whereIn('cl.geo_location_id', $territoryIds));
|
||||
|
||||
foreach ([['cluster_projects', 'cluster_id'], ['corridor_projects', 'corridor_id']] as [$linkTable, $ownerColumn]) {
|
||||
$matches->orWhereExists(fn ($links) => $links->selectRaw('1')->from($linkTable.' as territorial_link')
|
||||
->join('projects as linked_project', 'linked_project.id', '=', 'territorial_link.project_id')
|
||||
->whereColumn('territorial_link.'.$ownerColumn, 'investment_dossiers.'.$ownerColumn)
|
||||
->whereNull('territorial_link.deleted_at')->where('territorial_link.data_classification', 'public')
|
||||
->where('territorial_link.validation_status', 'validated')
|
||||
->whereDate('territorial_link.valid_from', '<=', today()->toDateString())
|
||||
->where(fn ($validity) => $validity->whereNull('territorial_link.valid_until')->orWhereDate('territorial_link.valid_until', '>=', today()->toDateString()))
|
||||
->whereNull('linked_project.deleted_at')->where('linked_project.status', '!=', 'draft')
|
||||
->where(function ($projectArea) use ($territoryIds): void {
|
||||
$projectArea->whereIn('linked_project.primary_territory_id', $territoryIds)
|
||||
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('project_locations as linked_location')
|
||||
->whereColumn('linked_location.project_id', 'linked_project.id')->whereNull('linked_location.deleted_at')
|
||||
->where('linked_location.data_classification', 'public')->whereIn('linked_location.geo_location_id', $territoryIds));
|
||||
}));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function publicReferences(): Builder
|
||||
{
|
||||
return DB::table('geo_locations')->whereNull('deleted_at')->where('data_classification', 'public')
|
||||
@@ -33,6 +72,73 @@ final class InvestmentGeography
|
||||
: $this->publicReferences();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @return list<list<string>>
|
||||
*/
|
||||
public function displayPaths(array $payload): array
|
||||
{
|
||||
$locations = [];
|
||||
if (($payload['geography_scope'] ?? null) === 'multiple') {
|
||||
$decoded = json_decode((string) ($payload['locations_json'] ?? ''), true);
|
||||
$locations = is_array($decoded) ? $decoded : [];
|
||||
} elseif (($payload['geography_scope'] ?? null) === 'specific') {
|
||||
$locations = [array_intersect_key($payload, array_flip(array_keys(self::FIELDS)))];
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
|
||||
$leafIds = [];
|
||||
foreach ($locations as $location) {
|
||||
$leafIds[] = is_array($location)
|
||||
? ($location['locality_id'] ?? $location['admin_post_id'] ?? $location['district_id'] ?? $location['province_id'] ?? null)
|
||||
: null;
|
||||
}
|
||||
$selected = array_filter($leafIds, fn ($id) => is_string($id) && $id !== '');
|
||||
if (! $selected) {
|
||||
return array_fill(0, count($locations), []);
|
||||
}
|
||||
|
||||
$values = [];
|
||||
$bindings = [];
|
||||
foreach ($selected as $index => $id) {
|
||||
$values[] = '(?, ?::uuid)';
|
||||
$bindings[] = $index;
|
||||
$bindings[] = $id;
|
||||
}
|
||||
$rows = DB::select('WITH RECURSIVE selected(location_index, id) AS (VALUES '.implode(',', $values).'),
|
||||
tree AS (
|
||||
SELECT s.location_index, g.id, g.name, g.location_type, g.parent_id, ARRAY[g.id] AS visited, 0 AS depth
|
||||
FROM selected s JOIN geo_locations g ON g.id=s.id
|
||||
UNION ALL
|
||||
SELECT tree.location_index, parent.id, parent.name, parent.location_type, parent.parent_id,
|
||||
tree.visited||parent.id, tree.depth+1
|
||||
FROM tree JOIN geo_locations parent ON parent.id=tree.parent_id
|
||||
WHERE tree.depth<4 AND NOT parent.id=ANY(tree.visited)
|
||||
)
|
||||
SELECT location_index, id, name, location_type FROM tree ORDER BY location_index, depth DESC', $bindings);
|
||||
$nodeIds = array_values(array_unique(array_map(fn ($row) => (string) $row->id, $rows)));
|
||||
$trustedIds = $this->publicReferences()->whereIn('id', $nodeIds)->pluck('id')->map(fn ($id) => (string) $id)->all();
|
||||
$trusted = array_fill_keys($trustedIds, true);
|
||||
$grouped = [];
|
||||
foreach ($rows as $row) {
|
||||
$grouped[(int) $row->location_index][] = $row;
|
||||
}
|
||||
|
||||
$display = [];
|
||||
foreach ($locations as $index => $_location) {
|
||||
$path = $grouped[$index] ?? [];
|
||||
if (! $path || array_filter($path, fn ($node) => ! isset($trusted[(string) $node->id]))) {
|
||||
$display[] = [];
|
||||
|
||||
continue;
|
||||
}
|
||||
$display[] = array_values(array_map(fn ($node) => (string) $node->name,
|
||||
array_filter($path, fn ($node) => $node->location_type !== 'country')));
|
||||
}
|
||||
|
||||
return $display;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return list<\stdClass>
|
||||
*/
|
||||
@@ -59,7 +165,7 @@ final class InvestmentGeography
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function descendants(string $id): array
|
||||
public function descendants(string $id, bool $includeNonPublic = false): array
|
||||
{
|
||||
$rows = DB::select('WITH RECURSIVE tree AS (
|
||||
SELECT id, ARRAY[id] AS visited FROM geo_locations WHERE id=? AND deleted_at IS NULL
|
||||
@@ -67,7 +173,11 @@ final class InvestmentGeography
|
||||
WHERE g.deleted_at IS NULL AND NOT g.id=ANY(tree.visited) AND cardinality(tree.visited)<5
|
||||
) SELECT id FROM tree', [$id]);
|
||||
|
||||
return array_values($this->publicReferences()->whereIn('id', array_map(fn ($row) => $row->id, $rows))->pluck('id')->map(fn ($id) => (string) $id)->all());
|
||||
$query = $includeNonPublic
|
||||
? DB::table('geo_locations')->whereNull('deleted_at')
|
||||
: $this->publicReferences();
|
||||
|
||||
return array_values($query->whereIn('id', array_map(fn ($row) => $row->id, $rows))->pluck('id')->map(fn ($id) => (string) $id)->all());
|
||||
}
|
||||
|
||||
/** @return list<\stdClass> */
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Models\InvestmentZone;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class InvestmentZones
|
||||
@@ -25,12 +26,61 @@ class InvestmentZones
|
||||
/** @return Builder<InvestmentZone> */
|
||||
public function visible(): Builder
|
||||
{
|
||||
if (! Schema::hasColumn('investment_zones', 'source_evidence')) {
|
||||
return InvestmentZone::query()->where('publication_status', 'published')->where('validation_status', 'validated')
|
||||
->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_legal_sources as source')
|
||||
->whereColumn('source.id', 'investment_zones.legal_source_id')->where('source.validation_status', 'validated')
|
||||
->whereDate('source.valid_from', '<=', today())
|
||||
->where(fn ($q) => $q->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', today())));
|
||||
}
|
||||
|
||||
return InvestmentZone::query()->where('publication_status', 'published')->where('validation_status', 'validated')
|
||||
->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_legal_sources as source')
|
||||
->whereColumn('source.id', 'investment_zones.legal_source_id')->where('source.validation_status', 'validated')
|
||||
->whereDate('source.valid_from', '<=', today())
|
||||
->where(fn ($q) => $q->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', today())))
|
||||
->whereExists(fn ($q) => $q->selectRaw('1')->from('organizations')->whereColumn('organizations.id', 'investment_zones.operator_id')->whereNull('organizations.deleted_at'));
|
||||
->where(function ($query): void {
|
||||
$query->where(function ($legal): void {
|
||||
$legal->whereIn('category', ['zee', 'zfi'])->whereExists(fn ($q) => $q->selectRaw('1')->from('investment_legal_sources as source')
|
||||
->whereColumn('source.id', 'investment_zones.legal_source_id')->where('source.validation_status', 'validated')
|
||||
->whereDate('source.valid_from', '<=', today())
|
||||
->where(fn ($q) => $q->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', today())));
|
||||
})->orWhere(function ($informational): void {
|
||||
$informational->whereNotIn('category', ['zee', 'zfi'])->whereRaw('jsonb_array_length(source_evidence) > 0')
|
||||
->whereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(source_evidence) AS evidence WHERE evidence->>'url' LIKE 'https://%')");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $filters */
|
||||
public function search(array $filters, bool $management = false): Builder
|
||||
{
|
||||
$query = $management ? InvestmentZone::query() : $this->visible();
|
||||
if (! Schema::hasColumn('investment_zones', 'source_evidence')) {
|
||||
unset($filters['physical_category'], $filters['legal_regime'], $filters['development_status'], $filters['availability_status']);
|
||||
}
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->where(function ($matches) use ($territoryIds, $management): void {
|
||||
$matches->whereIn('primary_territory_id', $territoryIds)
|
||||
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('investment_zone_locations as zl')
|
||||
->whereColumn('zl.zone_id', 'investment_zones.id')->whereIn('zl.geo_location_id', $territoryIds)
|
||||
->where('zl.validation_status', 'validated')->where(fn ($valid) => $valid->whereNull('zl.valid_from')->orWhereDate('zl.valid_from', '<=', today()))
|
||||
->where(fn ($valid) => $valid->whereNull('zl.valid_until')->orWhereDate('zl.valid_until', '>=', today())));
|
||||
if (! $management) {
|
||||
$matches->orWhereExists(fn ($geometry) => $geometry->selectRaw('1')->from('investment_zone_geometries as zg')
|
||||
->join('geo_geometries as shape', 'shape.id', '=', 'zg.geometry_id')
|
||||
->whereColumn('zg.zone_id', 'investment_zones.id')->where('zg.publication_authorized', true)
|
||||
->where('zg.validation_status', 'validated')->whereNull('shape.deleted_at')
|
||||
->where('shape.data_classification', 'public')->whereIn('shape.geo_location_id', $territoryIds));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return $query->when($filters['category'] ?? null, fn ($q, $value) => $q->where('category', $value))
|
||||
->when($filters['physical_category'] ?? null, fn ($q, $value) => $q->where('physical_category', $value))
|
||||
->when($filters['legal_regime'] ?? null, fn ($q, $value) => $q->where('legal_regime', $value))
|
||||
->when($filters['development_status'] ?? null, fn ($q, $value) => $q->where('development_status', $value))
|
||||
->when($filters['availability_status'] ?? null, fn ($q, $value) => $q->where('availability_status', $value))
|
||||
->when($filters['activity'] ?? null, fn ($q, $value) => $q->whereRaw('activities @> ?::jsonb', [json_encode([['name' => $value]], JSON_THROW_ON_ERROR)]))
|
||||
->when($filters['q'] ?? null, fn ($q, $value) => $q->where(fn ($q) => $q->where('name', 'ilike', '%'.$value.'%')->orWhere('code', 'ilike', '%'.$value.'%')));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
@@ -40,9 +90,18 @@ class InvestmentZones
|
||||
$zone = $id ? InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail() : new InvestmentZone;
|
||||
abort_if($id && (int) $zone->version_no !== (int) $data['version_no'], 409, 'Versão alterada. Recarregue antes de guardar.');
|
||||
$version = $id ? (int) $zone->version_no + 1 : 1;
|
||||
unset($data['version_no']);
|
||||
$locations = $data['locations'] ?? [];
|
||||
unset($data['locations'], $data['version_no']);
|
||||
$zone->fill([...$data, 'editor_id' => $actor, 'reviewer_id' => null, 'published_at' => null,
|
||||
'version_no' => $version, 'publication_status' => 'draft', 'validation_status' => 'pending'])->save();
|
||||
foreach ($locations as $location) {
|
||||
DB::table('investment_zone_locations')->insertOrIgnore([
|
||||
'id' => (string) Str::uuid(), 'zone_id' => $zone->id, 'geo_location_id' => $location['geo_location_id'],
|
||||
'scope_type' => $location['scope_type'] ?? 'administrative', 'source_reference' => $location['source_reference'],
|
||||
'legal_source_id' => $location['legal_source_id'] ?? null, 'validation_status' => 'pending',
|
||||
'editor_id' => $actor, 'version_no' => 1, 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
$this->snapshot($zone, $actor, 'saved');
|
||||
|
||||
return $zone;
|
||||
@@ -56,11 +115,26 @@ class InvestmentZones
|
||||
abort_if((int) $zone->version_no !== $version, 409, 'Versão alterada. Recarregue antes de aprovar.');
|
||||
abort_if((int) $zone->editor_id === $actor, 403, 'A revisão exige outro gestor autorizado.');
|
||||
$source = DB::table('investment_legal_sources')->where('id', $zone->legal_source_id)->lockForUpdate()->first();
|
||||
abort_unless($source && $source->validation_status === 'validated' && $source->valid_from <= today()->toDateString()
|
||||
&& (! $source->valid_until || $source->valid_until >= today()->toDateString()), 422, 'Fonte jurídica válida e revista em falta.');
|
||||
abort_unless($zone->category !== 'pending' && $zone->operator_id && trim((string) $zone->name_en) !== ''
|
||||
&& trim((string) $zone->description) !== '' && trim((string) $zone->description_en) !== '', 422, 'Categoria, operador e conteúdo PT/EN são obrigatórios.');
|
||||
abort_unless(DB::table('organizations')->where('id', $zone->operator_id)->whereNull('deleted_at')->exists(), 422, 'Operador indisponível.');
|
||||
if (in_array($zone->category, ['zee', 'zfi'], true)) {
|
||||
abort_unless($source && $source->validation_status === 'validated' && $source->valid_from <= today()->toDateString()
|
||||
&& (! $source->valid_until || $source->valid_until >= today()->toDateString()), 422, 'Fonte jurídica válida e revista em falta para este regime.');
|
||||
} else {
|
||||
$evidence = is_array($zone->source_evidence) ? $zone->source_evidence : [];
|
||||
abort_unless(collect($evidence)->contains(fn ($item) => in_array($item['source_type'] ?? null, ['government', 'institutional', 'promoter'], true)
|
||||
&& str_starts_with((string) ($item['url'] ?? ''), 'https://')), 422, 'Fonte institucional ou do promotor com URL HTTPS em falta.');
|
||||
}
|
||||
abort_unless($zone->category !== 'pending' && trim((string) $zone->name) !== ''
|
||||
&& trim((string) $zone->description) !== '', 422, 'Identidade, categoria e descrição são obrigatórias.');
|
||||
abort_unless($zone->physical_category && $zone->physical_category !== 'unknown', 422, 'Categoria física por confirmar.');
|
||||
if (in_array($zone->category, ['zee', 'zfi'], true)) {
|
||||
abort_unless($zone->legal_regime === $zone->category, 422, 'O regime jurídico da ZEE/ZFI deve estar confirmado.');
|
||||
}
|
||||
$publicLocation = $zone->primary_territory_id
|
||||
&& app(InvestmentGeography::class)->publicReferences()->where('id', $zone->primary_territory_id)->exists();
|
||||
$publicLocation = $publicLocation || DB::table('investment_zone_locations as zl')->join('geo_locations as g', 'g.id', '=', 'zl.geo_location_id')
|
||||
->where('zl.zone_id', $id)->where('zl.validation_status', 'validated')->where('g.data_classification', 'public')->whereNull('g.deleted_at')
|
||||
->whereIn('g.id', app(InvestmentGeography::class)->publicReferences()->select('id'))->exists();
|
||||
abort_unless($publicLocation, 422, 'Public, independently reviewed territory required.');
|
||||
$zone->fill(['version_no' => $version + 1, 'reviewer_id' => $actor, 'publication_status' => 'published',
|
||||
'validation_status' => 'validated', 'published_at' => now()])->save();
|
||||
$this->snapshot($zone, $actor, 'published');
|
||||
@@ -81,6 +155,30 @@ class InvestmentZones
|
||||
});
|
||||
}
|
||||
|
||||
public function validateLocation(string $id, int $version, int $actor): object
|
||||
{
|
||||
return DB::transaction(function () use ($id, $version, $actor) {
|
||||
$location = DB::table('investment_zone_locations')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($location, 404);
|
||||
abort_if((int) $location->version_no !== $version, 409, 'Version changed.');
|
||||
abort_if((int) $location->editor_id === $actor, 403, 'Independent review required.');
|
||||
abort_unless($location->validation_status === 'pending', 422, 'Territorial association already reviewed.');
|
||||
abort_unless(app(InvestmentGeography::class)->publicReferences()->where('id', $location->geo_location_id)->exists(), 422, 'Territory is not a public reference location.');
|
||||
if ($location->legal_source_id) {
|
||||
$source = DB::table('investment_legal_sources')->where('id', $location->legal_source_id)->first();
|
||||
abort_unless($source && $source->validation_status === 'validated' && $source->valid_from <= today()->toDateString()
|
||||
&& (! $source->valid_until || $source->valid_until >= today()->toDateString()), 422, 'Location source is not valid.');
|
||||
}
|
||||
DB::table('investment_zone_locations')->where('id', $id)->update(['validation_status' => 'validated', 'reviewer_id' => $actor,
|
||||
'version_no' => $version + 1, 'updated_at' => now()]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'investment-zones', 'entity_type' => 'investment_zone_locations',
|
||||
'entity_id' => $id, 'actor_user_id' => $actor, 'action' => 'validated',
|
||||
'after_data' => json_encode(['version_no' => $version + 1], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return DB::table('investment_zone_locations')->where('id', $id)->first();
|
||||
});
|
||||
}
|
||||
|
||||
private function snapshot(InvestmentZone $zone, int $actor, string $action): void
|
||||
{
|
||||
$json = $zone->toJson(JSON_THROW_ON_ERROR);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Malware;
|
||||
|
||||
final class ArchiveLimitInspector
|
||||
{
|
||||
public function inspect(string $path): ?string
|
||||
{
|
||||
$stream = @fopen($path, 'rb');
|
||||
if (! is_resource($stream)) {
|
||||
return 'archive_inspection_failed';
|
||||
}
|
||||
$signature = fread($stream, 4);
|
||||
fclose($stream);
|
||||
|
||||
if (! is_string($signature) || ! in_array($signature, ["PK\x03\x04", "PK\x05\x06", "PK\x07\x08"], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! class_exists(\ZipArchive::class)) {
|
||||
return 'archive_inspector_unavailable';
|
||||
}
|
||||
|
||||
$archive = new \ZipArchive;
|
||||
if ($archive->open($path, \ZipArchive::RDONLY) !== true) {
|
||||
return 'archive_inspection_failed';
|
||||
}
|
||||
|
||||
try {
|
||||
$maxEntries = max(1, (int) config('services.malware.max_archive_entries', 1000));
|
||||
$maxExpandedBytes = max(1, (int) config('services.malware.max_decompressed_bytes', 104857600));
|
||||
if ($archive->numFiles > $maxEntries) {
|
||||
return 'archive_entry_limit_exceeded';
|
||||
}
|
||||
|
||||
$expandedBytes = 0;
|
||||
for ($index = 0; $index < $archive->numFiles; $index++) {
|
||||
$entry = $archive->statIndex($index);
|
||||
if (! is_array($entry) || ! isset($entry['size']) || ! is_int($entry['size']) || $entry['size'] < 0) {
|
||||
return 'archive_inspection_failed';
|
||||
}
|
||||
|
||||
if ($entry['size'] > $maxExpandedBytes - $expandedBytes) {
|
||||
return 'archive_decompression_limit';
|
||||
}
|
||||
$expandedBytes += $entry['size'];
|
||||
}
|
||||
|
||||
return null;
|
||||
} finally {
|
||||
$archive->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Malware;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
final class ClamDScanner implements MalwareScanner
|
||||
{
|
||||
private string $engineVersion = '';
|
||||
|
||||
private ?DateTimeImmutable $signaturesAt = null;
|
||||
|
||||
public function health(): array
|
||||
{
|
||||
try {
|
||||
$pong = $this->command('PING');
|
||||
if ($pong !== 'PONG') {
|
||||
return $this->unavailable('clamd_protocol_error');
|
||||
}
|
||||
|
||||
$version = $this->command('VERSION');
|
||||
if (! preg_match('/^ClamAV\s+([^\/\s]+)\/(\d+)\/(.+)$/', $version, $matches)) {
|
||||
return $this->unavailable('signature_version_unavailable');
|
||||
}
|
||||
|
||||
$dateText = preg_replace('/\s+/', ' ', trim($matches[3]));
|
||||
$date = DateTimeImmutable::createFromFormat('D M j H:i:s Y', (string) $dateText, new DateTimeZone('UTC'));
|
||||
if (! $date || $date->getTimestamp() > time() + 3600) {
|
||||
return $this->unavailable('signature_date_invalid');
|
||||
}
|
||||
|
||||
$ageHours = max(0, (time() - $date->getTimestamp()) / 3600);
|
||||
$this->engineVersion = $matches[1];
|
||||
$this->signaturesAt = $date;
|
||||
if ($ageHours > (float) config('services.malware.max_signature_age_hours', 48)) {
|
||||
return [
|
||||
'available' => false, 'engine' => 'ClamAV', 'engine_version' => $this->engineVersion,
|
||||
'signatures_at' => $date, 'signature_age_hours' => $ageHours, 'reason_code' => 'signatures_stale',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'available' => true, 'engine' => 'ClamAV', 'engine_version' => $this->engineVersion,
|
||||
'signatures_at' => $date, 'signature_age_hours' => $ageHours, 'reason_code' => null,
|
||||
];
|
||||
} catch (Throwable $exception) {
|
||||
$reason = str_contains(strtolower($exception->getMessage()), 'timed out')
|
||||
? 'scanner_timeout'
|
||||
: 'scanner_unavailable';
|
||||
|
||||
return $this->unavailable($reason);
|
||||
}
|
||||
}
|
||||
|
||||
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array
|
||||
{
|
||||
$startedAt = hrtime(true);
|
||||
$health = $this->health();
|
||||
if (! $health['available']) {
|
||||
return $this->result('inconclusive', $health['reason_code'], $startedAt, null);
|
||||
}
|
||||
|
||||
$root = realpath($storageRoot);
|
||||
$resolved = realpath($path);
|
||||
if (! $root || ! $resolved || ! is_file($resolved)
|
||||
|| ! str_starts_with(strtolower($resolved), strtolower($root.DIRECTORY_SEPARATOR))) {
|
||||
return $this->result('inconclusive', 'private_file_unavailable', $startedAt, null);
|
||||
}
|
||||
|
||||
$actualSize = filesize($resolved);
|
||||
if (! is_int($actualSize) || $actualSize !== $fileSizeBytes) {
|
||||
return $this->result('inconclusive', 'file_size_changed', $startedAt, null);
|
||||
}
|
||||
if ($actualSize > (int) config('services.malware.max_file_bytes', 20 * 1024 * 1024)
|
||||
|| $actualSize > (int) config('services.malware.max_stream_bytes', 25 * 1024 * 1024)) {
|
||||
return $this->result('inconclusive', 'file_scan_limit_exceeded', $startedAt, null);
|
||||
}
|
||||
|
||||
$archiveFailure = app(ArchiveLimitInspector::class)->inspect($resolved);
|
||||
if ($archiveFailure !== null) {
|
||||
return $this->result('inconclusive', $archiveFailure, $startedAt, null);
|
||||
}
|
||||
|
||||
$socket = null;
|
||||
$file = fopen($resolved, 'rb');
|
||||
if (! is_resource($file)) {
|
||||
return $this->result('inconclusive', 'private_file_unavailable', $startedAt, null);
|
||||
}
|
||||
|
||||
try {
|
||||
$socket = $this->connect();
|
||||
$this->writeAll($socket, "zINSTREAM\0");
|
||||
$sent = 0;
|
||||
while (! feof($file)) {
|
||||
$chunk = fread($file, 65536);
|
||||
if ($chunk === false) {
|
||||
throw new RuntimeException('The private file could not be streamed to clamd.');
|
||||
}
|
||||
if ($chunk === '') {
|
||||
break;
|
||||
}
|
||||
$sent += strlen($chunk);
|
||||
if ($sent > $actualSize || $sent > (int) config('services.malware.max_stream_bytes', 25 * 1024 * 1024)) {
|
||||
return $this->result('inconclusive', 'stream_limit_exceeded', $startedAt, null);
|
||||
}
|
||||
$this->writeAll($socket, pack('N', strlen($chunk)).$chunk);
|
||||
}
|
||||
if ($sent !== $actualSize) {
|
||||
return $this->result('inconclusive', 'file_size_changed', $startedAt, null);
|
||||
}
|
||||
|
||||
$this->writeAll($socket, pack('N', 0));
|
||||
$reply = $this->readReply($socket);
|
||||
if (str_ends_with($reply, ': OK')) {
|
||||
return $this->result('clean', null, $startedAt, null);
|
||||
}
|
||||
|
||||
if (preg_match('/:\s(.+) FOUND$/', $reply, $matches)) {
|
||||
$signature = $matches[1];
|
||||
if (preg_match('/encrypted|password|limits?\.exceeded|oversized/i', $signature)) {
|
||||
$reason = preg_match('/encrypted|password/i', $signature)
|
||||
? 'encrypted_or_password_protected'
|
||||
: 'scanner_decompression_limit';
|
||||
|
||||
return $this->result('inconclusive', $reason, $startedAt, $signature);
|
||||
}
|
||||
|
||||
return $this->result('infected', 'threat_detected', $startedAt, $signature);
|
||||
}
|
||||
|
||||
if (stripos($reply, 'size limit exceeded') !== false || stripos($reply, 'limit exceeded') !== false) {
|
||||
return $this->result('inconclusive', 'scanner_decompression_limit', $startedAt, $reply);
|
||||
}
|
||||
|
||||
throw new RuntimeException('ClamD returned an unrecognized scan response.');
|
||||
} catch (Throwable $exception) {
|
||||
$reason = str_contains(strtolower($exception->getMessage()), 'timed out')
|
||||
? 'scanner_timeout'
|
||||
: 'scanner_unavailable';
|
||||
|
||||
return $this->result('inconclusive', $reason, $startedAt, null);
|
||||
} finally {
|
||||
fclose($file);
|
||||
if (is_resource($socket)) {
|
||||
fclose($socket);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function command(string $command): string
|
||||
{
|
||||
$socket = $this->connect();
|
||||
try {
|
||||
$this->writeAll($socket, 'z'.$command."\0");
|
||||
|
||||
return $this->readReply($socket);
|
||||
} finally {
|
||||
fclose($socket);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return resource */
|
||||
private function connect()
|
||||
{
|
||||
if (config('services.malware.scanner') !== 'clamd') {
|
||||
throw new RuntimeException('No production scanner is configured.');
|
||||
}
|
||||
|
||||
$host = (string) config('services.malware.host', '127.0.0.1');
|
||||
$port = (int) config('services.malware.port', 3310);
|
||||
if ($host === '' || in_array($host, ['0.0.0.0', '::'], true) || $port < 1 || $port > 65535) {
|
||||
throw new RuntimeException('The ClamD endpoint is invalid.');
|
||||
}
|
||||
|
||||
$timeout = max(1, (int) config('services.malware.timeout_seconds', 120));
|
||||
$socket = @stream_socket_client("tcp://{$host}:{$port}", $errorCode, $errorMessage, min(10, $timeout));
|
||||
if (! is_resource($socket)) {
|
||||
throw new RuntimeException('ClamD is unavailable.');
|
||||
}
|
||||
stream_set_timeout($socket, $timeout);
|
||||
|
||||
return $socket;
|
||||
}
|
||||
|
||||
/** @param resource $socket */
|
||||
private function writeAll($socket, string $data): void
|
||||
{
|
||||
$offset = 0;
|
||||
$length = strlen($data);
|
||||
while ($offset < $length) {
|
||||
$written = fwrite($socket, substr($data, $offset, 1024 * 1024));
|
||||
if ($written === false || $written === 0) {
|
||||
throw new RuntimeException('ClamD connection stopped accepting scan data.');
|
||||
}
|
||||
$offset += $written;
|
||||
$meta = stream_get_meta_data($socket);
|
||||
if ($meta['timed_out'] ?? false) {
|
||||
throw new RuntimeException('ClamD scan timed out while sending data.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param resource $socket */
|
||||
private function readReply($socket): string
|
||||
{
|
||||
$reply = stream_get_line($socket, 65536, "\0");
|
||||
$meta = stream_get_meta_data($socket);
|
||||
if ($reply === false || ($meta['timed_out'] ?? false)) {
|
||||
throw new RuntimeException(($meta['timed_out'] ?? false) ? 'ClamD scan timed out.' : 'ClamD returned no scan result.');
|
||||
}
|
||||
|
||||
return trim($reply);
|
||||
}
|
||||
|
||||
private function unavailable(string $reason): array
|
||||
{
|
||||
return ['available' => false, 'engine' => 'ClamAV', 'engine_version' => null, 'signatures_at' => null,
|
||||
'signature_age_hours' => null, 'reason_code' => $reason];
|
||||
}
|
||||
|
||||
private function result(string $result, ?string $reason, int $startedAt, ?string $detail): array
|
||||
{
|
||||
return [
|
||||
'result' => $result, 'reason_code' => $reason, 'engine' => 'ClamAV',
|
||||
'engine_version' => $this->engineVersion, 'signatures_at' => $this->signaturesAt,
|
||||
'duration_ms' => (int) ((hrtime(true) - $startedAt) / 1_000_000), 'detail' => $detail,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Malware;
|
||||
|
||||
interface MalwareScanner
|
||||
{
|
||||
/** @return array{result:string,reason_code:?string,engine:string,engine_version:string,signatures_at:\DateTimeImmutable,duration_ms:int,detail:?string} */
|
||||
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array;
|
||||
|
||||
/** @return array{available:bool,engine:string,engine_version:?string,signatures_at:?\DateTimeImmutable,signature_age_hours:?float,reason_code:?string} */
|
||||
public function health(): array;
|
||||
}
|
||||
@@ -21,7 +21,7 @@ final class SimulationExecution
|
||||
$scope = $actorId !== null ? (string) $actorId : ($tokenHash ?? 'anonymous');
|
||||
$scopeHash = hash('sha256', $scope);
|
||||
$keyHash = hash('sha256', strtolower($key));
|
||||
$payload = ['base' => (string) $data['base'], 'rate' => (string) $data['rate'], 'reduction' => (string) $data['reduction'], 'organization_id' => $organizationId];
|
||||
$payload = ['base' => (string) $data['base'], 'rate' => (string) $data['rate'], 'reduction' => (string) $data['reduction'], 'scenario_kind' => 'custom_planning', 'organization_id' => $organizationId];
|
||||
ksort($payload);
|
||||
$payloadHash = hash('sha256', json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
|
||||
@@ -44,7 +44,7 @@ final class SimulationExecution
|
||||
$simulation = Simulation::create([
|
||||
'id' => $id, 'questionnaire_version_id' => '61000100-0000-4000-8000-000000000001', 'owner_user_id' => $actorId, 'organization_id' => $organizationId,
|
||||
'anonymous_token_hash' => $tokenHash, 'status' => 'queued', 'version_no' => 1,
|
||||
'input_snapshot' => $payload, 'calculation_snapshot' => ['engine' => 'portal-tax-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
|
||||
'input_snapshot' => $payload, 'calculation_snapshot' => ['engine' => 'portal-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
|
||||
]);
|
||||
$scenarioId = (string) Str::uuid();
|
||||
DB::table('simulation_scenarios')->insert([
|
||||
@@ -88,7 +88,7 @@ final class SimulationExecution
|
||||
$this->requireMatch($request, $simulation);
|
||||
$scenario = DB::table('simulation_scenarios')->where('simulation_id', $id)->where('id', $scenarioId)->lockForUpdate()->first();
|
||||
abort_if($scenario === null, 404);
|
||||
$parameters = ['base' => (string) $data['base'], 'rate' => (string) $data['rate'], 'reduction' => (string) $data['reduction']];
|
||||
$parameters = ['base' => (string) $data['base'], 'rate' => (string) $data['rate'], 'reduction' => (string) $data['reduction'], 'scenario_kind' => 'custom_planning'];
|
||||
DB::table('simulation_scenarios')->where('id', $scenarioId)->update([
|
||||
'label' => $data['label'], 'parameters' => json_encode($parameters, JSON_THROW_ON_ERROR), 'version_no' => $scenario->version_no + 1, 'updated_at' => now(),
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
final class SimulationFormDraftPrivacyPolicy
|
||||
{
|
||||
/** @param array{personal_snapshot: array<string,mixed>, economic_snapshot: array<string,mixed>} $data
|
||||
* @return array{personal_snapshot: array<string,mixed>, economic_snapshot: array<string,mixed>}
|
||||
*/
|
||||
public static function apply(array $data, bool $authenticated): array
|
||||
{
|
||||
if (! $authenticated) {
|
||||
$data['personal_snapshot'] = [];
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -3,29 +3,43 @@
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\User;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
final class SimulationFormDrafts
|
||||
{
|
||||
/** @param array{personal_snapshot: array<string,mixed>, economic_snapshot: array<string,mixed>} $data */
|
||||
/**
|
||||
* @param array{personal_snapshot: array<string,mixed>, economic_snapshot: array<string,mixed>} $data
|
||||
* @return array{draft: SimulationFormDraft, replayed: bool}
|
||||
*/
|
||||
public function create(array $data, Request $request, string $key): array
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
$data = SimulationFormDraftPrivacyPolicy::apply($data, $actorId !== null);
|
||||
$scope = $actorId === null ? 'anonymous:'.$tokenHash : 'user:'.$actorId;
|
||||
$keyHash = hash_hmac('sha256', strtolower($key), (string) config('app.key'));
|
||||
$canonicalPayload = json_encode($this->canonical($data), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
$payloadHash = hash('sha256', $canonicalPayload);
|
||||
|
||||
return DB::transaction(function () use ($actorId, $tokenHash, $scope, $keyHash, $payloadHash, $canonicalPayload, $data): array {
|
||||
return DB::transaction(function () use ($actorId, $tokenHash, $scope, $keyHash, $payloadHash, $data): array {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
DB::select('select pg_advisory_xact_lock(261010, hashtext(?))', [$scope]);
|
||||
|
||||
$query = SimulationFormDraft::query()->whereNull('deleted_at')->lockForUpdate();
|
||||
$query = $actorId === null ? $query->where('anonymous_token_hash', $tokenHash) : $query->where('owner_user_id', $actorId);
|
||||
$draft = $query->first();
|
||||
if ($actorId === null) {
|
||||
SimulationFormDraft::query()->whereNull('owner_user_id')->where('anonymous_token_hash', $tokenHash)
|
||||
->whereNull('deleted_at')->where('expires_at', '<=', now())->lockForUpdate()
|
||||
->update(['deleted_at' => now()]);
|
||||
}
|
||||
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->first();
|
||||
if ($draft) {
|
||||
if (hash_equals($draft->create_key_hash, $keyHash)) {
|
||||
abort_unless(hash_equals($draft->create_payload_hash, $payloadHash), 409, 'Idempotency-Key já foi utilizada com outros dados.');
|
||||
@@ -40,6 +54,7 @@ final class SimulationFormDrafts
|
||||
'version_no' => 1, 'create_key_hash' => $keyHash, 'create_payload_hash' => $payloadHash, 'snapshot_sha256' => $payloadHash,
|
||||
'personal_snapshot' => SimulationFormDraft::encryptSnapshot($data['personal_snapshot']),
|
||||
'economic_snapshot' => SimulationFormDraft::encryptSnapshot($data['economic_snapshot']),
|
||||
'expires_at' => $actorId === null ? now()->addDays(30) : null,
|
||||
]);
|
||||
|
||||
return ['draft' => $draft, 'replayed' => false];
|
||||
@@ -50,31 +65,260 @@ final class SimulationFormDrafts
|
||||
public function update(string $id, array $data, Request $request): SimulationFormDraft
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
$data = SimulationFormDraftPrivacyPolicy::apply($data, $actorId !== null);
|
||||
|
||||
return DB::transaction(function () use ($id, $data, $request, $actorId, $tokenHash): SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$draft = SimulationFormDraft::query()->whereNull('deleted_at')->lockForUpdate()->findOrFail($id);
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->findOrFail($id);
|
||||
$this->requireMatch($request, $draft);
|
||||
$previousEconomic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
if (($data['economic_snapshot']['reuse_simulation'] ?? null) === 'no') {
|
||||
unset($data['economic_snapshot']['simulation_sources']);
|
||||
} elseif (is_array($previousEconomic['simulation_sources'] ?? null)) {
|
||||
$data['economic_snapshot']['simulation_sources'] = $previousEconomic['simulation_sources'];
|
||||
}
|
||||
$canonicalPayload = json_encode($this->canonical($data), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
$draft->update([
|
||||
'personal_snapshot' => SimulationFormDraft::encryptSnapshot($data['personal_snapshot']),
|
||||
'economic_snapshot' => SimulationFormDraft::encryptSnapshot($data['economic_snapshot']),
|
||||
'snapshot_sha256' => hash('sha256', $canonicalPayload), 'version_no' => $draft->version_no + 1,
|
||||
'expires_at' => $actorId === null ? now()->addDays(30) : null,
|
||||
]);
|
||||
|
||||
return $draft->refresh();
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function renew(string $id, Request $request): SimulationFormDraft
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
|
||||
return DB::transaction(function () use ($id, $request, $actorId, $tokenHash): SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->findOrFail($id);
|
||||
$this->requireMatch($request, $draft);
|
||||
$draft->update(['expires_at' => $actorId === null ? now()->addDays(30) : null]);
|
||||
|
||||
return $draft->refresh();
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $sourceSnapshot
|
||||
* @return array{draft: SimulationFormDraft, replayed: bool}
|
||||
*/
|
||||
public function attachSimulation(string $id, array $sourceSnapshot, Request $request): array
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
$sourceId = (string) ($sourceSnapshot['simulation_id'] ?? '');
|
||||
|
||||
return DB::transaction(function () use ($id, $sourceSnapshot, $sourceId, $request, $actorId, $tokenHash): array {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->findOrFail($id);
|
||||
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
abort_unless(isset($economic['purpose']) && $economic['purpose'] !== 'simulate_only', 422, 'Escolha uma finalidade de investimento antes de converter a simulação.');
|
||||
$sources = is_array($economic['simulation_sources'] ?? null) ? $economic['simulation_sources'] : [];
|
||||
foreach ($sources as $source) {
|
||||
if (is_array($source) && ($source['simulation_id'] ?? null) === $sourceId) {
|
||||
return ['draft' => $draft, 'replayed' => true];
|
||||
}
|
||||
}
|
||||
|
||||
$this->requireMatch($request, $draft);
|
||||
$sources[] = $sourceSnapshot;
|
||||
$economic['simulation_sources'] = $sources;
|
||||
$economic['reuse_simulation'] = 'yes';
|
||||
$personal = SimulationFormDraft::decryptSnapshot($draft->personal_snapshot);
|
||||
$canonicalPayload = json_encode($this->canonical([
|
||||
'personal_snapshot' => $personal,
|
||||
'economic_snapshot' => $economic,
|
||||
]), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
$draft->update([
|
||||
'economic_snapshot' => SimulationFormDraft::encryptSnapshot($economic),
|
||||
'snapshot_sha256' => hash('sha256', $canonicalPayload),
|
||||
'version_no' => $draft->version_no + 1,
|
||||
'expires_at' => $actorId === null ? now()->addDays(30) : null,
|
||||
]);
|
||||
|
||||
$plainToken = $request->header('X-Simulation-Token');
|
||||
$auditTokenHash = is_string($plainToken) && $plainToken !== ''
|
||||
? hash_hmac('sha256', $plainToken, (string) config('app.key'))
|
||||
: null;
|
||||
$this->setContext($actorId, $auditTokenHash ?? $tokenHash);
|
||||
DB::table('simulation_audit_events')->insert([
|
||||
'simulation_id' => $sourceId,
|
||||
'actor_user_id' => $actorId,
|
||||
'action' => 'simulation.attached_to_draft',
|
||||
'correlation_id' => $draft->id,
|
||||
'data' => json_encode(['draft_id' => $draft->id, 'report_sha256' => $sourceSnapshot['report_sha256']], JSON_THROW_ON_ERROR),
|
||||
'occurred_at' => now(),
|
||||
]);
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
|
||||
return ['draft' => $draft->refresh(), 'replayed' => false];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function current(Request $request): ?SimulationFormDraft
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
|
||||
return DB::transaction(function () use ($actorId, $tokenHash): ?SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$query = SimulationFormDraft::query()->whereNull('deleted_at');
|
||||
return $this->ownedQuery($actorId, $tokenHash)->orderByDesc('updated_at')->first();
|
||||
});
|
||||
}
|
||||
|
||||
return ($actorId === null ? $query->where('anonymous_token_hash', $tokenHash) : $query->where('owner_user_id', $actorId))->first();
|
||||
public function forgetCurrent(Request $request): void
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
abort_unless($actorId === null && is_string($tokenHash), 422);
|
||||
|
||||
DB::transaction(function () use ($tokenHash): void {
|
||||
$this->setContext(null, $tokenHash);
|
||||
SimulationFormDraft::query()->whereNull('owner_user_id')->where('anonymous_token_hash', $tokenHash)
|
||||
->whereNull('deleted_at')->lockForUpdate()->update(['deleted_at' => now()]);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @return list<array{id:string,title:string,updated_at:string|null,expires_at:string|null,version_no:int}> */
|
||||
public function ownedDrafts(User $actor): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor): array {
|
||||
$this->setContext($actor->id, null);
|
||||
|
||||
return array_values($this->ownedQuery($actor->id, null)->orderByDesc('updated_at')->get()
|
||||
->map(fn (SimulationFormDraft $draft): array => $this->summary($draft))->all());
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array{id:string,title:string,updated_at:string|null,expires_at:string|null,version_no:int}|null */
|
||||
public function claimPreview(Request $request): ?array
|
||||
{
|
||||
abort_unless($request->user() instanceof User, 401);
|
||||
$tokenHash = $this->anonymousTokenHash($request);
|
||||
|
||||
return DB::transaction(function () use ($request, $tokenHash): ?array {
|
||||
$this->setContext($request->user()->id, $tokenHash);
|
||||
$draft = SimulationFormDraft::query()->whereNull('owner_user_id')->where('anonymous_token_hash', $tokenHash)
|
||||
->whereNull('deleted_at')->where('expires_at', '>', now())->first();
|
||||
|
||||
return $draft ? $this->summary($draft) : null;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array{draft:SimulationFormDraft,choice:string,replayed?:bool} */
|
||||
public function claim(Request $request, string $choice, ?string $existingDraftId = null): array
|
||||
{
|
||||
$actor = $request->user();
|
||||
abort_unless($actor instanceof User && $actor->hasVerifiedEmail(), 403);
|
||||
$tokenHash = $this->anonymousTokenHash($request);
|
||||
|
||||
return DB::transaction(function () use ($actor, $tokenHash, $choice, $existingDraftId): array {
|
||||
$this->setContext($actor->id, $tokenHash);
|
||||
$anonymous = SimulationFormDraft::query()->whereNull('owner_user_id')->where('anonymous_token_hash', $tokenHash)
|
||||
->whereNull('deleted_at')->where('expires_at', '>', now())->lockForUpdate()->first();
|
||||
if (! $anonymous && $choice === 'save_as_new') {
|
||||
$claimed = $this->ownedQuery($actor->id, null)->where('claimed_token_hash', $tokenHash)->lockForUpdate()->first();
|
||||
if ($claimed) {
|
||||
return ['draft' => $claimed, 'choice' => $choice, 'replayed' => true];
|
||||
}
|
||||
}
|
||||
abort_unless($anonymous !== null, 404, 'O rascunho anónimo expirou ou já não está disponível.');
|
||||
|
||||
if ($choice === 'continue_existing') {
|
||||
abort_unless(is_string($existingDraftId) && Str::isUuid($existingDraftId), 422);
|
||||
$existing = $this->ownedQuery($actor->id, null)->whereKey($existingDraftId)->firstOrFail();
|
||||
|
||||
return ['draft' => $existing, 'choice' => $choice];
|
||||
}
|
||||
|
||||
abort_unless($choice === 'save_as_new', 422);
|
||||
$anonymous->update(['owner_user_id' => $actor->id, 'anonymous_token_hash' => null, 'claimed_token_hash' => $tokenHash, 'expires_at' => null,
|
||||
'version_no' => $anonymous->version_no + 1]);
|
||||
|
||||
return ['draft' => $anonymous->refresh(), 'choice' => $choice, 'replayed' => false];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @return list<array{id:string,title:string,modality:string,status:string}> */
|
||||
public function linkableBusinesses(User $actor): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor): array {
|
||||
$this->setContext($actor->id, null);
|
||||
|
||||
$businesses = app(BusinessRepository::class)->query()->where('owner_user_id', $actor->id)->whereNull('deleted_at')
|
||||
->orderByDesc('updated_at')->get()->filter(fn (ExistingBusiness $business): bool => Gate::forUser($actor)->allows('owns', $business))
|
||||
->map(fn (ExistingBusiness $business): array => ['id' => $business->id,
|
||||
'title' => (string) ($business->public_title ?: ($business->payload['title'] ?? 'Negócio sem título')),
|
||||
'modality' => $business->modality, 'status' => $business->status])->values()->all();
|
||||
|
||||
return array_values($businesses);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array{id:string,business_id:string,title:string,linked_at:string}|array{replayed:true} */
|
||||
public function linkBusiness(User $actor, string $draftId, string $businessId): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $draftId, $businessId): array {
|
||||
$this->setContext($actor->id, null);
|
||||
$draft = $this->ownedQuery($actor->id, null)->whereKey($draftId)->lockForUpdate()->firstOrFail();
|
||||
$business = app(BusinessRepository::class)->find($businessId, true);
|
||||
Gate::forUser($actor)->authorize('owns', $business);
|
||||
$active = DB::table('simulation_draft_business_links')->where('draft_id', $draft->id)->whereNull('unlinked_at')->lockForUpdate()->first();
|
||||
if ($active) {
|
||||
abort_unless($active->business_id === $business->id, 409, 'Desassocie o negócio actual antes de escolher outro.');
|
||||
|
||||
return ['replayed' => true];
|
||||
}
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('simulation_draft_business_links')->insert(['id' => $id, 'draft_id' => $draft->id,
|
||||
'business_id' => $business->id, 'owner_user_id' => $actor->id, 'linked_by' => $actor->id,
|
||||
'linked_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
|
||||
|
||||
return ['id' => $id, 'business_id' => $business->id,
|
||||
'title' => (string) ($business->public_title ?: ($business->payload['title'] ?? 'Negócio sem título')),
|
||||
'linked_at' => now()->toISOString()];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @return array{unlinked:bool} */
|
||||
public function unlinkBusiness(User $actor, string $draftId): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $draftId): array {
|
||||
$this->setContext($actor->id, null);
|
||||
$draft = $this->ownedQuery($actor->id, null)->whereKey($draftId)->lockForUpdate()->firstOrFail();
|
||||
$link = DB::table('simulation_draft_business_links')->where('draft_id', $draft->id)->whereNull('unlinked_at')->lockForUpdate()->first();
|
||||
if (! $link) {
|
||||
return ['unlinked' => false];
|
||||
}
|
||||
DB::table('simulation_draft_business_links')->where('id', $link->id)->update(['unlinked_at' => now(),
|
||||
'unlinked_by' => $actor->id, 'updated_at' => now()]);
|
||||
|
||||
return ['unlinked' => true];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function activeBusinessLink(User $actor, string $draftId): ?array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $draftId): ?array {
|
||||
$this->setContext($actor->id, null);
|
||||
$this->ownedQuery($actor->id, null)->whereKey($draftId)->firstOrFail();
|
||||
$row = DB::table('simulation_draft_business_links')->where('draft_id', $draftId)
|
||||
->where('owner_user_id', $actor->id)->whereNull('unlinked_at')->first();
|
||||
if (! $row) {
|
||||
return null;
|
||||
}
|
||||
$business = app(BusinessRepository::class)->find($row->business_id);
|
||||
if (! Gate::forUser($actor)->allows('owns', $business)) {
|
||||
return ['id' => $row->id, 'business_id' => $row->business_id,
|
||||
'title' => 'Negócio indisponível para esta conta',
|
||||
'linked_at' => Carbon::parse($row->linked_at)->toISOString()];
|
||||
}
|
||||
|
||||
return ['id' => $row->id, 'business_id' => $row->business_id,
|
||||
'title' => (string) ($business->public_title ?: ($business->payload['title'] ?? 'Negócio sem título')),
|
||||
'linked_at' => Carbon::parse($row->linked_at)->toISOString()];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -85,7 +329,7 @@ final class SimulationFormDrafts
|
||||
return DB::transaction(function () use ($id, $actorId, $tokenHash): SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
|
||||
return SimulationFormDraft::query()->whereNull('deleted_at')->findOrFail($id);
|
||||
return $this->ownedQuery($actorId, $tokenHash)->findOrFail($id);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -94,22 +338,28 @@ final class SimulationFormDrafts
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
DB::transaction(function () use ($id, $request, $actorId, $tokenHash): void {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$draft = SimulationFormDraft::query()->whereNull('deleted_at')->lockForUpdate()->findOrFail($id);
|
||||
$draft = $this->ownedQuery($actorId, $tokenHash)->lockForUpdate()->findOrFail($id);
|
||||
$this->requireMatch($request, $draft);
|
||||
$draft->update(['deleted_at' => now()]);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function present(SimulationFormDraft $draft): array
|
||||
public function present(SimulationFormDraft $draft, bool $includePersonal): array
|
||||
{
|
||||
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
$simulationSources = is_array($economic['simulation_sources'] ?? null) ? $economic['simulation_sources'] : [];
|
||||
unset($economic['simulation_sources']);
|
||||
|
||||
return [
|
||||
'id' => $draft->id,
|
||||
'version_no' => $draft->version_no,
|
||||
'snapshot_sha256' => $draft->snapshot_sha256,
|
||||
'personal_snapshot' => SimulationFormDraft::decryptSnapshot($draft->personal_snapshot),
|
||||
'economic_snapshot' => SimulationFormDraft::decryptSnapshot($draft->economic_snapshot),
|
||||
'personal_snapshot' => $includePersonal ? SimulationFormDraft::decryptSnapshot($draft->personal_snapshot) : [],
|
||||
'economic_snapshot' => $economic,
|
||||
'simulation_sources' => $simulationSources,
|
||||
'updated_at' => $draft->updated_at,
|
||||
'expires_at' => $draft->expires_at?->toISOString(),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -129,6 +379,14 @@ final class SimulationFormDrafts
|
||||
return [$actorId, $actorId === null ? hash_hmac('sha256', $token, (string) config('app.key')) : null];
|
||||
}
|
||||
|
||||
private function anonymousTokenHash(Request $request): string
|
||||
{
|
||||
$token = $request->header('X-Simulation-Token');
|
||||
abort_unless(is_string($token) && strlen($token) >= 32 && strlen($token) <= 256, 422, 'A recuperação do rascunho expirou. Reinicie pelo mesmo navegador ou dispositivo.');
|
||||
|
||||
return hash_hmac('sha256', $token, (string) config('app.key'));
|
||||
}
|
||||
|
||||
private function setContext(?int $actorId, ?string $tokenHash): void
|
||||
{
|
||||
DB::select("select set_config('app.actor_user_id', ?, true), set_config('app.simulation_token_hash', ?, true)", [(string) ($actorId ?? ''), (string) ($tokenHash ?? '')]);
|
||||
@@ -145,6 +403,26 @@ final class SimulationFormDrafts
|
||||
}
|
||||
}
|
||||
|
||||
/** @return Builder<SimulationFormDraft> */
|
||||
private function ownedQuery(?int $actorId, ?string $tokenHash): Builder
|
||||
{
|
||||
$query = SimulationFormDraft::query()->whereNull('deleted_at');
|
||||
|
||||
return $actorId === null
|
||||
? $query->whereNull('owner_user_id')->where('anonymous_token_hash', $tokenHash)->where('expires_at', '>', now())
|
||||
: $query->where('owner_user_id', $actorId)->whereNull('anonymous_token_hash');
|
||||
}
|
||||
|
||||
/** @return array{id:string,title:string,updated_at:string|null,expires_at:string|null,version_no:int} */
|
||||
private function summary(SimulationFormDraft $draft): array
|
||||
{
|
||||
$snapshot = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
|
||||
return ['id' => $draft->id, 'title' => (string) ($snapshot['project_title'] ?? 'Projecto sem título'),
|
||||
'updated_at' => $draft->updated_at?->toISOString(), 'expires_at' => $draft->expires_at?->toISOString(),
|
||||
'version_no' => (int) $draft->version_no];
|
||||
}
|
||||
|
||||
private function canonical(mixed $value): mixed
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
final class SimulationTaxGovernanceAccess
|
||||
{
|
||||
private const ROLES = ['editors', 'reviewers', 'approvers', 'publishers'];
|
||||
|
||||
public static function requireRole(User $user, string $role): void
|
||||
{
|
||||
abort_unless(in_array($role, self::ROLES, true), 500, 'Função de governação desconhecida.');
|
||||
abort_unless(in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true),
|
||||
403, 'O utilizador não está designado para esta função de governação fiscal.');
|
||||
}
|
||||
|
||||
public static function requireAnyRole(User $user): void
|
||||
{
|
||||
foreach (self::ROLES as $role) {
|
||||
if (in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
abort(403, 'O utilizador não está designado para consultar a governação fiscal.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Brick\Math\BigRational;
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/** Selects a published, date-effective parameter from an explicitly scoped candidate set. */
|
||||
final class SimulationTaxParameterResolver
|
||||
{
|
||||
/** @param array<array-key,mixed> $parameters */
|
||||
public function validateParameters(array $parameters): void
|
||||
{
|
||||
if ($parameters === [] || count($parameters) > 100) {
|
||||
throw new InvalidArgumentException('Provide between 1 and 100 versioned parameters.');
|
||||
}
|
||||
foreach ($parameters as $code => $parameter) {
|
||||
if (! is_string($code) || ! preg_match('/^[A-Z][A-Z0-9._-]{1,63}$/', $code) || ! is_array($parameter)
|
||||
|| array_diff(array_keys($parameter), ['value', 'unit', 'conditions']) !== []
|
||||
|| array_diff(['value', 'unit', 'conditions'], array_keys($parameter)) !== []) {
|
||||
throw new InvalidArgumentException('Each parameter requires only value, unit, and conditions.');
|
||||
}
|
||||
if ((! is_string($parameter['value']) && ! is_int($parameter['value'])) || (string) $parameter['value'] === ''
|
||||
|| ! is_string($parameter['unit']) || ! preg_match('/^[a-z][a-z0-9._-]{0,31}$/', $parameter['unit'])
|
||||
|| ! is_array($parameter['conditions'])) {
|
||||
throw new InvalidArgumentException('Invalid parameter value, unit, or conditions.');
|
||||
}
|
||||
$isNumericValue = preg_match('/^-?\d+(?:\.\d+)?$/', (string) $parameter['value']) === 1;
|
||||
if (in_array($parameter['unit'], ['percent', 'mzn', 'amount', 'days', 'count', 'mzn_per_unit', 'per_unit'], true) && ! $isNumericValue) {
|
||||
throw new InvalidArgumentException('Numeric parameter units require a plain decimal value.');
|
||||
}
|
||||
if ($isNumericValue) {
|
||||
$value = BigRational::of((string) $parameter['value']);
|
||||
if ($value->isNegative() || ($parameter['unit'] === 'percent' && $value->compareTo(100) > 0)) {
|
||||
throw new InvalidArgumentException('Numeric parameters cannot be negative; percentages must be between 0 and 100.');
|
||||
}
|
||||
}
|
||||
foreach ($parameter['conditions'] as $condition => $expected) {
|
||||
if (! is_string($condition) || ! is_string($expected)) {
|
||||
throw new InvalidArgumentException('Conditions must be a flat map of string assumptions.');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve only rows made visible by the published-only RLS policy. The method
|
||||
* never executes a tax formula and requires each parameter to declare context.
|
||||
*
|
||||
* @param array<string,string> $context
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function resolvePublishedForPeriod(string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
{
|
||||
$start = $this->date($periodStart);
|
||||
$end = $this->date($periodEnd);
|
||||
if ($end < $start || $start->diff($end)->days > 365) {
|
||||
throw new InvalidArgumentException('Invalid effective period.');
|
||||
}
|
||||
|
||||
$rows = DB::table('simulation_tax_rule_versions as rule')
|
||||
->join('investment_legal_sources as source', 'source.id', '=', 'rule.legal_source_id')
|
||||
->where('rule.component', $component)
|
||||
->where('rule.status', 'published')
|
||||
->whereDate('rule.valid_from', '<=', $periodEnd)
|
||||
->where(fn ($query) => $query->whereNull('rule.valid_until')->orWhereDate('rule.valid_until', '>=', $periodStart))
|
||||
->where('source.validation_status', 'validated')
|
||||
->whereColumn('source.version_no', 'rule.source_version_no')
|
||||
->whereDate('source.valid_from', '<=', $periodStart)
|
||||
->where(fn ($query) => $query->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', $periodEnd))
|
||||
->select([
|
||||
'rule.id', 'rule.rule_code', 'rule.rule_version', 'rule.component', 'rule.scope_key',
|
||||
'rule.valid_from', 'rule.valid_until', 'rule.parameters', 'rule.rule_definition',
|
||||
'rule.source_version_no', 'rule.source_sha256',
|
||||
'source.title as source_title', 'source.diploma as source_diploma', 'source.article as source_article',
|
||||
'source.url as source_url', 'source.validation_status as source_validation_status',
|
||||
'source.version_no as source_current_version', 'source.valid_from as source_valid_from',
|
||||
'source.valid_until as source_valid_until',
|
||||
])
|
||||
->orderBy('rule.rule_code')->orderBy('rule.rule_version')->limit(500)->get();
|
||||
|
||||
$versions = array_values($rows->map(function (object $row): array {
|
||||
$parameters = is_array($row->parameters)
|
||||
? $row->parameters
|
||||
: json_decode((string) $row->parameters, true, flags: JSON_THROW_ON_ERROR);
|
||||
$definition = is_array($row->rule_definition)
|
||||
? $row->rule_definition
|
||||
: json_decode((string) $row->rule_definition, true, flags: JSON_THROW_ON_ERROR);
|
||||
|
||||
return [
|
||||
'id' => $row->id,
|
||||
'rule_code' => $row->rule_code,
|
||||
'rule_version' => (int) $row->rule_version,
|
||||
'component' => $row->component,
|
||||
'scope_key' => $row->scope_key,
|
||||
'status' => 'published',
|
||||
'valid_from' => (string) $row->valid_from,
|
||||
'valid_until' => $row->valid_until === null ? null : (string) $row->valid_until,
|
||||
'rule_definition' => $definition,
|
||||
'parameters' => $parameters,
|
||||
'source_version_no' => (int) $row->source_version_no,
|
||||
'source_sha256' => $row->source_sha256,
|
||||
'source' => [
|
||||
'title' => $row->source_title,
|
||||
'diploma' => $row->source_diploma,
|
||||
'article' => $row->source_article,
|
||||
'url' => $row->source_url,
|
||||
'validation_status' => $row->source_validation_status,
|
||||
'version_no' => (int) $row->source_current_version,
|
||||
'valid_from' => (string) $row->source_valid_from,
|
||||
'valid_until' => $row->source_valid_until === null ? null : (string) $row->source_valid_until,
|
||||
],
|
||||
];
|
||||
})->all());
|
||||
|
||||
return $this->resolveAvailableParameters($versions, $component, $periodStart, $periodEnd, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $versions
|
||||
* @param array<string,string> $context
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function resolveAvailableParameters(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
{
|
||||
$start = $this->date($periodStart);
|
||||
$end = $this->date($periodEnd);
|
||||
$groups = [];
|
||||
|
||||
foreach ($versions as $version) {
|
||||
if (($version['component'] ?? null) !== $component
|
||||
|| ($version['status'] ?? null) !== 'published'
|
||||
|| ($version['source']['validation_status'] ?? null) !== 'validated'
|
||||
|| (int) ($version['source_version_no'] ?? 0) !== (int) ($version['source']['version_no'] ?? -1)
|
||||
|| ! $this->overlaps($version, $start, $end)
|
||||
|| ! $this->covers($version['source'], $start) || ! $this->covers($version['source'], $end)
|
||||
|| ($version['rule_definition']['language'] ?? null) !== 'investmoz.tax.v1'
|
||||
|| ! is_array($version['parameters'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$coversWholePeriod = $this->covers($version, $start) && $this->covers($version, $end);
|
||||
foreach ($version['parameters'] as $code => $parameter) {
|
||||
if (! is_string($code) || ! is_array($parameter) || ! is_array($parameter['conditions'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
$groups[$code] ??= ['matches' => [], 'partial' => false, 'saw_unscoped' => false, 'saw_context_mismatch' => false];
|
||||
$conditions = $parameter['conditions'];
|
||||
if (! $coversWholePeriod) {
|
||||
if ($conditions !== [] && $this->conditionsMatch($conditions, $context) && ($version['scope_key'] ?? '') !== '') {
|
||||
$groups[$code]['partial'] = true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($conditions === []) {
|
||||
$groups[$code]['saw_unscoped'] = true;
|
||||
} elseif (! $this->conditionsMatch($conditions, $context)) {
|
||||
$groups[$code]['saw_context_mismatch'] = true;
|
||||
} elseif (($version['scope_key'] ?? '') === '') {
|
||||
$groups[$code]['saw_unscoped'] = true;
|
||||
} else {
|
||||
$groups[$code]['matches'][] = [$version, $parameter];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
foreach ($groups as $code => $group) {
|
||||
if ($group['partial']) {
|
||||
$state = count($group['matches']) > 0 ? 'indeterminate_overlap' : 'indeterminate_period_change';
|
||||
$resolved[] = ['parameter_code' => $code, 'status' => $state, 'value' => null];
|
||||
|
||||
continue;
|
||||
}
|
||||
if (count($group['matches']) !== 1) {
|
||||
$state = count($group['matches']) > 1
|
||||
? 'indeterminate_overlap'
|
||||
: ($group['saw_unscoped'] ? 'indeterminate_scope' : ($group['saw_context_mismatch'] ? 'indeterminate_context' : 'indeterminate_missing'));
|
||||
$resolved[] = ['parameter_code' => $code, 'status' => $state, 'value' => null];
|
||||
|
||||
continue;
|
||||
}
|
||||
[$version, $parameter] = $group['matches'][0];
|
||||
if (! isset($parameter['value'], $parameter['unit']) || ! is_string($parameter['unit'])) {
|
||||
$resolved[] = ['parameter_code' => $code, 'status' => 'indeterminate_invalid', 'value' => null];
|
||||
|
||||
continue;
|
||||
}
|
||||
$resolved[] = [
|
||||
'parameter_code' => $code,
|
||||
'status' => 'resolved',
|
||||
'value' => (string) $parameter['value'],
|
||||
'unit' => $parameter['unit'],
|
||||
'conditions' => $parameter['conditions'],
|
||||
'scope_key' => $version['scope_key'],
|
||||
'rule_code' => $version['rule_code'],
|
||||
'rule_id' => $version['id'],
|
||||
'rule_version' => (int) $version['rule_version'],
|
||||
'period' => ['start' => $periodStart, 'end' => $periodEnd],
|
||||
'validity' => ['start' => $version['valid_from'], 'end' => $version['valid_until'] ?? null],
|
||||
'source' => [
|
||||
'title' => $version['source']['title'],
|
||||
'diploma' => $version['source']['diploma'],
|
||||
'article' => $version['source']['article'],
|
||||
'url' => $version['source']['url'],
|
||||
'declared_sha256' => $version['source_sha256'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
usort($resolved, static fn (array $left, array $right): int => $left['parameter_code'] <=> $right['parameter_code']);
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param iterable<array<string,mixed>> $publishedVersions Caller must supply only records visible under the applicable access policy.
|
||||
* @param array<string,scalar|null> $conditions
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function resolve(iterable $publishedVersions, string $component, string $scopeKey, string $asOf, string $parameterCode, array $conditions = []): array
|
||||
{
|
||||
$date = $this->date($asOf);
|
||||
$matches = [];
|
||||
foreach ($publishedVersions as $version) {
|
||||
if (($version['status'] ?? null) !== 'published'
|
||||
|| ($version['component'] ?? null) !== $component
|
||||
|| ($version['scope_key'] ?? null) !== $scopeKey
|
||||
|| ! $this->covers($version, $date)
|
||||
|| ($version['source']['validation_status'] ?? null) !== 'validated'
|
||||
|| (int) ($version['source_version_no'] ?? 0) !== (int) ($version['source']['version_no'] ?? -1)
|
||||
|| ! $this->covers($version['source'], $date)
|
||||
|| ! preg_match('/^[a-f0-9]{64}$/D', (string) ($version['source_sha256'] ?? ''))) {
|
||||
continue;
|
||||
}
|
||||
$parameter = $version['parameters'][$parameterCode] ?? null;
|
||||
if (! is_array($parameter) || ! isset($parameter['value'], $parameter['unit']) || ! is_string($parameter['unit'])
|
||||
|| ! is_array($parameter['conditions'] ?? null) || ! $this->conditionsMatch($parameter['conditions'], $conditions)) {
|
||||
continue;
|
||||
}
|
||||
$matches[] = [$version, $parameter];
|
||||
}
|
||||
|
||||
if (count($matches) !== 1) {
|
||||
return ['status' => count($matches) > 1 ? 'indeterminate_overlap' : 'indeterminate_missing', 'value' => null, 'parameter_code' => $parameterCode];
|
||||
}
|
||||
[$version, $parameter] = $matches[0];
|
||||
|
||||
return [
|
||||
'status' => 'resolved',
|
||||
'value' => (string) $parameter['value'],
|
||||
'unit' => $parameter['unit'],
|
||||
'parameter_code' => $parameterCode,
|
||||
'conditions' => $parameter['conditions'],
|
||||
'rule_code' => $version['rule_code'],
|
||||
'rule_version' => (int) $version['rule_version'],
|
||||
'rule_id' => $version['id'],
|
||||
'scope_key' => $scopeKey,
|
||||
'valid_from' => $version['valid_from'],
|
||||
'valid_until' => $version['valid_until'] ?? null,
|
||||
'source' => [
|
||||
'title' => $version['source']['title'],
|
||||
'diploma' => $version['source']['diploma'],
|
||||
'article' => $version['source']['article'],
|
||||
'url' => $version['source']['url'],
|
||||
'declared_sha256' => $version['source_sha256'],
|
||||
'validation_status' => $version['source']['validation_status'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $version */
|
||||
private function covers(array $version, DateTimeImmutable $date): bool
|
||||
{
|
||||
$fromValue = $version['valid_from'] ?? null;
|
||||
$untilValue = $version['valid_until'] ?? null;
|
||||
if (! is_string($fromValue) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/D', $fromValue)
|
||||
|| ($untilValue !== null && (! is_string($untilValue) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/D', $untilValue)))) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$from = DateTimeImmutable::createFromFormat('!Y-m-d', $fromValue);
|
||||
$until = $untilValue === null ? null : DateTimeImmutable::createFromFormat('!Y-m-d', $untilValue);
|
||||
if ($from === false || $from->format('Y-m-d') !== $fromValue
|
||||
|| ($untilValue !== null && ($until === false || $until->format('Y-m-d') !== $untilValue))) {
|
||||
return false;
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $date >= $from && ($until === null || $date <= $until);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $version */
|
||||
private function overlaps(array $version, DateTimeImmutable $start, DateTimeImmutable $end): bool
|
||||
{
|
||||
$fromValue = $version['valid_from'] ?? null;
|
||||
$untilValue = $version['valid_until'] ?? null;
|
||||
if (! is_string($fromValue) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/D', $fromValue)) {
|
||||
return false;
|
||||
}
|
||||
$from = $this->date($fromValue);
|
||||
$until = $untilValue === null ? null : (is_string($untilValue) ? $this->date($untilValue) : null);
|
||||
|
||||
return $from <= $end && ($until === null || $until >= $start);
|
||||
}
|
||||
|
||||
private function date(string $date): DateTimeImmutable
|
||||
{
|
||||
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $date);
|
||||
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
|
||||
throw new InvalidArgumentException('Effective date must use YYYY-MM-DD.');
|
||||
}
|
||||
|
||||
return $parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed>|null $required
|
||||
* @param array<string,scalar|null> $actual
|
||||
*/
|
||||
private function conditionsMatch(?array $required, array $actual): bool
|
||||
{
|
||||
if ($required === null) {
|
||||
return false;
|
||||
}
|
||||
foreach ($required as $key => $value) {
|
||||
if (! array_key_exists($key, $actual) || $actual[$key] !== $value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Brick\Math\BigRational;
|
||||
use Brick\Math\RoundingMode;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/** A deliberately small, data-only expression language for reviewed tax-rule drafts. */
|
||||
final class SimulationTaxRuleExpression
|
||||
{
|
||||
private const LANGUAGE = 'investmoz.tax.v1';
|
||||
|
||||
private const ROUNDING = [
|
||||
'UNNECESSARY' => RoundingMode::Unnecessary,
|
||||
'UP' => RoundingMode::Up,
|
||||
'DOWN' => RoundingMode::Down,
|
||||
'CEILING' => RoundingMode::Ceiling,
|
||||
'FLOOR' => RoundingMode::Floor,
|
||||
'HALF_UP' => RoundingMode::HalfUp,
|
||||
'HALF_DOWN' => RoundingMode::HalfDown,
|
||||
'HALF_CEILING' => RoundingMode::HalfCeiling,
|
||||
'HALF_FLOOR' => RoundingMode::HalfFloor,
|
||||
'HALF_EVEN' => RoundingMode::HalfEven,
|
||||
];
|
||||
|
||||
/** @param array<string,mixed> $definition */
|
||||
public function validate(array $definition): void
|
||||
{
|
||||
$this->topologicalOrder($definition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a validated expression. Missing values are reported as indeterminate;
|
||||
* callers must supply versioned parameters and provenance explicitly.
|
||||
*
|
||||
* @param array<string,mixed> $definition
|
||||
* @param array<string,string|int> $inputs
|
||||
* @param array<string,string|int> $parameters
|
||||
* @return array{status:string,result:?string,missing:list<string>,steps:list<array<string,mixed>>}
|
||||
*/
|
||||
public function evaluate(array $definition, array $inputs, array $parameters): array
|
||||
{
|
||||
$order = $this->topologicalOrder($definition);
|
||||
$nodes = $definition['nodes'];
|
||||
$values = [];
|
||||
$missing = [];
|
||||
$steps = [];
|
||||
|
||||
foreach ($order as $id) {
|
||||
$node = $nodes[$id];
|
||||
$op = $node['op'];
|
||||
if ($op === 'input' || $op === 'parameter') {
|
||||
$key = $node['key'];
|
||||
$source = $op === 'input' ? $inputs : $parameters;
|
||||
if (! array_key_exists($key, $source)) {
|
||||
$missing[] = $op.':'.$key;
|
||||
$steps[] = ['id' => $id, 'op' => $op, 'key' => $key, 'value' => null];
|
||||
|
||||
continue;
|
||||
}
|
||||
$value = $this->number($source[$key]);
|
||||
} elseif ($op === 'literal') {
|
||||
$value = $this->number($node['value']);
|
||||
} else {
|
||||
$args = array_values(array_map(static fn (string $ref): ?BigRational => $values[$ref] ?? null, $node['args'] ?? []));
|
||||
if (in_array(null, $args, true)) {
|
||||
$values[$id] = null;
|
||||
$steps[] = ['id' => $id, 'op' => $op, 'args' => $node['args'] ?? [], 'value' => null];
|
||||
|
||||
continue;
|
||||
}
|
||||
$value = $this->operate($op, $args, $node);
|
||||
}
|
||||
$values[$id] = $value;
|
||||
$steps[] = ['id' => $id, 'op' => $op, 'value' => (string) $value];
|
||||
}
|
||||
|
||||
$result = $values[$definition['result']] ?? null;
|
||||
|
||||
return [
|
||||
'status' => $missing === [] && $result !== null ? 'determinate' : 'indeterminate',
|
||||
'result' => $result === null ? null : (string) $result,
|
||||
'missing' => array_values(array_unique($missing)),
|
||||
'steps' => $steps,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $definition
|
||||
* @return list<string>
|
||||
*/
|
||||
private function topologicalOrder(array $definition): array
|
||||
{
|
||||
if (($definition['language'] ?? null) !== self::LANGUAGE || ! is_array($definition['nodes'] ?? null) || ! is_string($definition['result'] ?? null)) {
|
||||
throw new InvalidArgumentException('Unsupported expression definition.');
|
||||
}
|
||||
$nodes = $definition['nodes'];
|
||||
if ($nodes === [] || count($nodes) > 100) {
|
||||
throw new InvalidArgumentException('Expression must contain between 1 and 100 nodes.');
|
||||
}
|
||||
|
||||
foreach ($nodes as $id => $node) {
|
||||
if (! is_string($id) || ! preg_match('/^[a-z][a-z0-9_]{0,47}$/', $id) || ! is_array($node) || ! is_string($node['op'] ?? null)) {
|
||||
throw new InvalidArgumentException('Invalid expression node.');
|
||||
}
|
||||
$op = $node['op'];
|
||||
$allowedFields = match ($op) {
|
||||
'input', 'parameter' => ['op', 'key'],
|
||||
'literal' => ['op', 'value'],
|
||||
'add', 'subtract', 'multiply', 'divide', 'min', 'max' => ['op', 'args'],
|
||||
'round' => ['op', 'args', 'scale', 'mode'],
|
||||
default => throw new InvalidArgumentException('Expression operation is not allowed.'),
|
||||
};
|
||||
if (array_diff(array_keys($node), $allowedFields) !== [] || array_diff($allowedFields, array_keys($node)) !== []) {
|
||||
throw new InvalidArgumentException('Expression node has missing or unsupported fields.');
|
||||
}
|
||||
if (in_array($op, ['input', 'parameter'], true) && (! is_string($node['key']) || ! preg_match('/^[a-z][a-z0-9_.-]{0,79}$/', $node['key']))) {
|
||||
throw new InvalidArgumentException('Invalid input or parameter key.');
|
||||
}
|
||||
if ($op === 'literal') {
|
||||
$this->number($node['value']);
|
||||
}
|
||||
if (isset($node['args'])) {
|
||||
if (! is_array($node['args'])) {
|
||||
throw new InvalidArgumentException('Invalid expression arguments.');
|
||||
}
|
||||
$count = count($node['args']);
|
||||
$validCount = $op === 'round' ? $count === 1 : ($op === 'subtract' || $op === 'divide' ? $count === 2 : $count >= 2 && $count <= 20);
|
||||
if (! $validCount || count(array_filter($node['args'], 'is_string')) !== $count) {
|
||||
throw new InvalidArgumentException('Invalid expression arguments.');
|
||||
}
|
||||
}
|
||||
if ($op === 'round' && (! is_int($node['scale']) || $node['scale'] < 0 || $node['scale'] > 12 || ! isset(self::ROUNDING[$node['mode']]))) {
|
||||
throw new InvalidArgumentException('Invalid explicit rounding configuration.');
|
||||
}
|
||||
}
|
||||
|
||||
if (! array_key_exists($definition['result'], $nodes)) {
|
||||
throw new InvalidArgumentException('Expression result references an unknown node.');
|
||||
}
|
||||
$state = [];
|
||||
$order = [];
|
||||
$visit = function (string $id) use (&$visit, &$state, &$order, $nodes): void {
|
||||
if (($state[$id] ?? 0) === 1) {
|
||||
throw new InvalidArgumentException('Expression dependency graph contains a cycle.');
|
||||
}
|
||||
if (($state[$id] ?? 0) === 2) {
|
||||
return;
|
||||
}
|
||||
$state[$id] = 1;
|
||||
foreach ($nodes[$id]['args'] ?? [] as $dependency) {
|
||||
if (! is_string($dependency) || ! array_key_exists($dependency, $nodes)) {
|
||||
throw new InvalidArgumentException('Expression references an unknown node.');
|
||||
}
|
||||
$visit($dependency);
|
||||
}
|
||||
$state[$id] = 2;
|
||||
$order[] = $id;
|
||||
};
|
||||
foreach (array_keys($nodes) as $id) {
|
||||
$visit($id);
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<BigRational> $args
|
||||
* @param array<string,mixed> $node
|
||||
*/
|
||||
private function operate(string $op, array $args, array $node): BigRational
|
||||
{
|
||||
if ($op === 'round') {
|
||||
return BigRational::of((string) $args[0]->toScale($node['scale'], self::ROUNDING[$node['mode']]));
|
||||
}
|
||||
if ($op === 'add') {
|
||||
return array_reduce(array_slice($args, 1), static fn (BigRational $carry, BigRational $value): BigRational => $carry->plus($value), $args[0]);
|
||||
}
|
||||
if ($op === 'subtract') {
|
||||
return $args[0]->minus($args[1]);
|
||||
}
|
||||
if ($op === 'multiply') {
|
||||
return array_reduce(array_slice($args, 1), static fn (BigRational $carry, BigRational $value): BigRational => $carry->multipliedBy($value), $args[0]);
|
||||
}
|
||||
if ($op === 'divide') {
|
||||
return $args[0]->dividedBy($args[1]);
|
||||
}
|
||||
if ($op === 'min' || $op === 'max') {
|
||||
return array_reduce(array_slice($args, 1), static fn (BigRational $carry, BigRational $value): BigRational => ($op === 'min' ? $carry->compareTo($value) <= 0 : $carry->compareTo($value) >= 0) ? $carry : $value, $args[0]);
|
||||
}
|
||||
throw new InvalidArgumentException('Expression operation is not allowed.');
|
||||
}
|
||||
|
||||
private function number(mixed $value): BigRational
|
||||
{
|
||||
if ((! is_string($value) && ! is_int($value)) || ! preg_match('/^-?\d+(?:\.\d+)?$/', (string) $value)) {
|
||||
throw new InvalidArgumentException('Numbers must be plain decimal strings or integers.');
|
||||
}
|
||||
|
||||
return BigRational::of((string) $value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\SimulationTaxRuleVersion;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
final class SimulationTaxRuleGovernance
|
||||
{
|
||||
/** @param array<string,mixed> $data */
|
||||
public function create(User $actor, array $data): SimulationTaxRuleVersion
|
||||
{
|
||||
SimulationTaxGovernanceAccess::requireRole($actor, 'editors');
|
||||
|
||||
return DB::transaction(function () use ($actor, $data): SimulationTaxRuleVersion {
|
||||
$this->setContext($actor);
|
||||
$source = $this->sourceSnapshot($data);
|
||||
$rule = SimulationTaxRuleVersion::query()->create([
|
||||
...$data,
|
||||
'id' => (string) Str::uuid(),
|
||||
'status' => 'draft',
|
||||
'author_id' => $actor->id,
|
||||
'source_version_no' => $source->version_no,
|
||||
'version_no' => 1,
|
||||
]);
|
||||
$this->event($rule, $actor, 'created');
|
||||
|
||||
return $rule->refresh();
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
public function update(User $actor, string $id, int $version, array $data): SimulationTaxRuleVersion
|
||||
{
|
||||
SimulationTaxGovernanceAccess::requireRole($actor, 'editors');
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $data): SimulationTaxRuleVersion {
|
||||
$this->setContext($actor);
|
||||
$rule = SimulationTaxRuleVersion::query()->lockForUpdate()->findOrFail($id);
|
||||
$this->matchVersion($rule, $version);
|
||||
abort_unless((int) $rule->author_id === $actor->id && $rule->status === 'draft', 403,
|
||||
'Só o autor pode alterar um rascunho ainda não submetido. Crie uma nova versão da regra após revisão.');
|
||||
$source = $this->sourceSnapshot($data);
|
||||
$rule->fill([...$data, 'source_version_no' => $source->version_no, 'version_no' => $version + 1])->save();
|
||||
$this->event($rule, $actor, 'updated');
|
||||
|
||||
return $rule->refresh();
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function transition(User $actor, string $id, int $version, string $action, string $evidence): SimulationTaxRuleVersion
|
||||
{
|
||||
$role = match ($action) {
|
||||
'submit' => 'editors',
|
||||
'review', 'reject' => 'reviewers',
|
||||
'approve' => 'approvers',
|
||||
'publish', 'suspend', 'archive' => 'publishers',
|
||||
default => throw new HttpException(422, 'Transição de governação inválida.'),
|
||||
};
|
||||
SimulationTaxGovernanceAccess::requireRole($actor, $role);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $action, $evidence): SimulationTaxRuleVersion {
|
||||
$this->setContext($actor);
|
||||
$rule = SimulationTaxRuleVersion::query()->lockForUpdate()->findOrFail($id);
|
||||
$this->matchVersion($rule, $version);
|
||||
$next = ['version_no' => $version + 1];
|
||||
|
||||
switch ($action) {
|
||||
case 'submit':
|
||||
abort_unless((int) $rule->author_id === $actor->id && $rule->status === 'draft', 403,
|
||||
'Só o autor pode submeter o seu rascunho.');
|
||||
$this->sourceStillValid($rule);
|
||||
$next += ['status' => 'submitted', 'submitted_at' => now()];
|
||||
break;
|
||||
case 'review':
|
||||
case 'reject':
|
||||
abort_unless((int) $rule->author_id !== $actor->id, 403, 'O autor não pode rever a própria regra.');
|
||||
abort_unless($rule->status === 'submitted', 422, 'A regra tem de estar submetida para revisão.');
|
||||
$this->sourceStillValid($rule);
|
||||
$next += ['status' => $action === 'review' ? 'reviewed' : 'rejected', 'reviewer_id' => $actor->id,
|
||||
'review_evidence' => $evidence, 'reviewed_at' => now()];
|
||||
break;
|
||||
case 'approve':
|
||||
abort_unless((int) $rule->author_id !== $actor->id && (int) $rule->reviewer_id !== $actor->id, 403,
|
||||
'Autor e revisor não podem aprovar a mesma regra.');
|
||||
abort_unless($rule->status === 'reviewed', 422, 'A regra tem de estar revista antes da aprovação.');
|
||||
$this->sourceStillValid($rule);
|
||||
$next += ['status' => 'approved', 'approver_id' => $actor->id,
|
||||
'approval_evidence' => $evidence, 'approved_at' => now()];
|
||||
break;
|
||||
case 'publish':
|
||||
abort_unless($rule->status === 'approved', 422, 'A regra tem de estar aprovada antes da publicação.');
|
||||
abort_unless((int) $rule->author_id !== $actor->id && (int) $rule->reviewer_id !== $actor->id
|
||||
&& (int) $rule->approver_id !== $actor->id, 403,
|
||||
'Autor, revisor e aprovador não podem publicar a mesma regra.');
|
||||
$this->sourceStillValid($rule);
|
||||
$this->assertNoPublishedOverlap($rule);
|
||||
$next += ['status' => 'published', 'publisher_id' => $actor->id,
|
||||
'publication_evidence' => $evidence, 'published_at' => now()];
|
||||
break;
|
||||
case 'suspend':
|
||||
abort_unless($rule->status === 'published', 422, 'Só uma regra publicada pode ser suspensa.');
|
||||
$next += ['status' => 'suspended', 'closure_evidence' => $evidence, 'suspended_at' => now()];
|
||||
break;
|
||||
case 'archive':
|
||||
abort_unless(in_array($rule->status, ['published', 'suspended'], true), 422,
|
||||
'Só uma regra publicada ou suspensa pode ser arquivada.');
|
||||
$next += ['status' => 'archived', 'closure_evidence' => $evidence, 'archived_at' => now()];
|
||||
break;
|
||||
}
|
||||
|
||||
$rule->fill($next)->save();
|
||||
$this->event($rule, $actor, $action);
|
||||
|
||||
return $rule->refresh();
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters */
|
||||
public function listing(User $actor, array $filters): mixed
|
||||
{
|
||||
SimulationTaxGovernanceAccess::requireAnyRole($actor);
|
||||
|
||||
return DB::transaction(function () use ($actor, $filters) {
|
||||
$this->setContext($actor);
|
||||
$query = SimulationTaxRuleVersion::query()->orderByDesc('created_at');
|
||||
foreach (['rule_code', 'component', 'scope_key', 'status'] as $key) {
|
||||
if (isset($filters[$key])) {
|
||||
$query->where($key, $filters[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
return $query->paginate($filters['per_page'] ?? 20)->withQueryString();
|
||||
});
|
||||
}
|
||||
|
||||
public function show(User $actor, string $id): SimulationTaxRuleVersion
|
||||
{
|
||||
SimulationTaxGovernanceAccess::requireAnyRole($actor);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id): SimulationTaxRuleVersion {
|
||||
$this->setContext($actor);
|
||||
|
||||
return SimulationTaxRuleVersion::query()->findOrFail($id);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function sourceSnapshot(array $data): InvestmentLegalSource
|
||||
{
|
||||
$source = InvestmentLegalSource::query()->whereKey($data['legal_source_id'])->firstOrFail();
|
||||
abort_unless(preg_match('/^[a-f0-9]{64}$/D', (string) $data['source_sha256']) === 1, 422,
|
||||
'Indique o SHA-256 do exemplar oficial efectivamente revisto.');
|
||||
abort_unless($source->validation_status === 'validated', 422, 'A fonte jurídica ainda não foi validada.');
|
||||
abort_unless($source->valid_from <= $data['valid_from']
|
||||
&& ($source->valid_until === null || ($data['valid_until'] !== null && $source->valid_until >= $data['valid_until']))
|
||||
&& ($data['valid_until'] !== null || $source->valid_until === null), 422,
|
||||
'A vigência da fonte não cobre todo o período declarado para a regra.');
|
||||
|
||||
return $source;
|
||||
}
|
||||
|
||||
private function sourceStillValid(SimulationTaxRuleVersion $rule): void
|
||||
{
|
||||
$source = InvestmentLegalSource::query()->lockForUpdate()->find($rule->legal_source_id);
|
||||
abort_unless($source !== null && $source->validation_status === 'validated'
|
||||
&& (int) $source->version_no === (int) $rule->source_version_no
|
||||
&& $source->valid_from <= $rule->valid_from->format('Y-m-d')
|
||||
&& ($source->valid_until === null || ($rule->valid_until !== null && $source->valid_until >= $rule->valid_until->format('Y-m-d')))
|
||||
&& ($rule->valid_until !== null || $source->valid_until === null), 422,
|
||||
'A fonte aprovada foi revogada, alterada ou não cobre toda a vigência da regra.');
|
||||
}
|
||||
|
||||
private function assertNoPublishedOverlap(SimulationTaxRuleVersion $rule): void
|
||||
{
|
||||
DB::select('select pg_advisory_xact_lock(hashtext(?), hashtext(?))', [$rule->rule_code, $rule->scope_key]);
|
||||
$overlap = SimulationTaxRuleVersion::query()->where('id', '<>', $rule->id)->where('status', 'published')
|
||||
->where('component', $rule->component)->where('rule_code', $rule->rule_code)->where('scope_key', $rule->scope_key)
|
||||
->whereDate('valid_from', '<=', $rule->valid_until?->format('Y-m-d') ?? '9999-12-31')
|
||||
->where(fn ($query) => $query->whereNull('valid_until')->orWhereDate('valid_until', '>=', $rule->valid_from->format('Y-m-d')))
|
||||
->exists();
|
||||
abort_unless(! $overlap, 409, 'Já existe regra publicada com vigência sobreposta para o mesmo código, componente e scope_key.');
|
||||
}
|
||||
|
||||
private function matchVersion(SimulationTaxRuleVersion $rule, int $version): void
|
||||
{
|
||||
abort_unless((int) $rule->version_no === $version, 409, 'Versão alterada. Recarregue antes de continuar.');
|
||||
}
|
||||
|
||||
private function setContext(User $actor): void
|
||||
{
|
||||
DB::select("select set_config('app.actor_user_id', ?, true), set_config('app.simulation_tax_governance', 'on', true)", [(string) $actor->id]);
|
||||
}
|
||||
|
||||
private function event(SimulationTaxRuleVersion $rule, User $actor, string $action): void
|
||||
{
|
||||
$snapshot = $this->canonical($rule->attributesToArray());
|
||||
$json = json_encode($snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
$canonicalJson = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$json])->canonical;
|
||||
DB::table('simulation_tax_rule_events')->insert([
|
||||
'id' => (string) Str::uuid(), 'rule_version_id' => $rule->id, 'version_no' => $rule->version_no,
|
||||
'actor_user_id' => $actor->id, 'action' => $action, 'snapshot' => $json,
|
||||
'sha256' => hash('sha256', $canonicalJson), 'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function canonical(mixed $value): mixed
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (! array_is_list($value)) {
|
||||
ksort($value);
|
||||
}
|
||||
foreach ($value as $key => $item) {
|
||||
$value[$key] = $this->canonical($item);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user