Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f35313d06 | ||
|
|
a6afb4e97a | ||
|
|
cbae1ce77b | ||
|
|
5e6b32b493 | ||
|
|
3395424d82 | ||
|
|
3dc7c5c649 | ||
|
|
67dad461d9 | ||
|
|
e780e67e98 | ||
|
|
2e0217b486 | ||
|
|
b77714b156 | ||
|
|
a2692704d9 | ||
|
|
439918d143 | ||
|
|
2640dd6109 | ||
|
|
519b256ffd | ||
|
|
24a0ef1db3 |
@@ -66,6 +66,15 @@ VITE_APP_NAME="${APP_NAME}"
|
||||
|
||||
# Comma-separated emails of verified accounts authorised to manage the portal.
|
||||
PORTAL_MANAGER_EMAILS=
|
||||
# Explicit, separate application workflow designations. Empty means no access.
|
||||
INVESTMOZ_MNE_TRIAGERS=
|
||||
INVESTMOZ_MNE_REVIEWERS=
|
||||
INVESTMOZ_MNE_APPROVERS_L1=
|
||||
INVESTMOZ_MNE_APPROVERS_L2=
|
||||
INVESTMOZ_MNE_PUBLISHERS=
|
||||
INVESTMOZ_CONSENT_POLICY_VERSION=2026-09-30
|
||||
INVESTMOZ_SHARING_POLICY_VERSION=2026-09-30
|
||||
INVESTMOZ_SLA_ESCALATION_ENABLED=false
|
||||
PORTAL_NOTIFICATIONS_ENABLED=false
|
||||
PORTAL_NOTIFICATION_RECIPIENTS=
|
||||
PORTAL_SUPPORT_EMAIL=
|
||||
|
||||
@@ -66,5 +66,10 @@ jobs:
|
||||
- name: Run CI Checks
|
||||
run: composer ci:check
|
||||
|
||||
- name: Validate PostgreSQL/PostGIS schema lifecycle
|
||||
env:
|
||||
INVESTMOZ_SCHEMA_TESTS: '1'
|
||||
run: php vendor/bin/phpunit --configuration=phpunit.investmoz.xml --do-not-cache-result
|
||||
|
||||
- name: Test frontend API contracts
|
||||
run: node --test tests/frontend/portal-api.test.mjs
|
||||
|
||||
@@ -0,0 +1,864 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: InvestMoz API
|
||||
version: 1.0.0
|
||||
summary: Contrato consolidado da API do InvestMoz
|
||||
description: |
|
||||
Contrato consolidado para catálogos, oportunidades, manifestações de interesse,
|
||||
simulações, legislação, jobs, relatórios e administração. Valores de taxas,
|
||||
reduções e parâmetros de simulação são fornecidos pelo utilizador; não são
|
||||
taxas oficiais nem decisões de elegibilidade.
|
||||
contact:
|
||||
name: Equipa InvestMoz
|
||||
license:
|
||||
name: MIT
|
||||
identifier: MIT
|
||||
servers:
|
||||
- url: /
|
||||
description: Mesmo host da aplicação
|
||||
security:
|
||||
- sessionCookie: []
|
||||
tags:
|
||||
- name: Catálogos
|
||||
description: Referências versionadas, estáveis e localizadas em pt-MZ.
|
||||
- name: Oportunidades
|
||||
description: Consulta pública de oportunidades de investimento.
|
||||
- name: Manifestações
|
||||
description: Submissão de interesse em oportunidades.
|
||||
- name: Simulações
|
||||
description: Execuções indicativas com snapshots e controlo de concorrência.
|
||||
- name: Jobs
|
||||
description: Estado dos trabalhos assíncronos associados a uma simulação.
|
||||
- name: Relatórios
|
||||
description: Leitura de snapshots imutáveis de relatórios.
|
||||
- name: Legislação
|
||||
description: Fontes legais publicadas e versionadas.
|
||||
- name: Administração
|
||||
description: Operações administrativas protegidas por sessão e autorização.
|
||||
paths:
|
||||
/api/v1/catalogs/{catalog}:
|
||||
get:
|
||||
tags: [Catálogos]
|
||||
operationId: listReferenceCatalog
|
||||
summary: Consultar catálogo versionado
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/CatalogName'
|
||||
- $ref: '#/components/parameters/Version'
|
||||
- $ref: '#/components/parameters/CatalogType'
|
||||
- $ref: '#/components/parameters/ParentId'
|
||||
- $ref: '#/components/parameters/JurisdictionId'
|
||||
- $ref: '#/components/parameters/Page'
|
||||
- $ref: '#/components/parameters/PerPage'
|
||||
- $ref: '#/components/parameters/Search'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Página do catálogo na versão solicitada
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/CatalogPage'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'422': {$ref: '#/components/responses/ValidationError'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/questionnaires/{code}:
|
||||
get:
|
||||
tags: [Simulações]
|
||||
operationId: getPublishedQuestionnaire
|
||||
summary: Consultar questionário publicado e versão imutável
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/QuestionnaireCode'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Questionário publicado em pt-MZ
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/QuestionnaireResponse'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/simulations:
|
||||
post:
|
||||
tags: [Simulações]
|
||||
operationId: createSimulation
|
||||
summary: Criar simulação rastreável
|
||||
description: Requer Idempotency-Key. Acesso anónimo requer token opaco gerado pelo cliente.
|
||||
x-implementation-status: implemented
|
||||
security:
|
||||
- sessionCookie: []
|
||||
- {}
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/IdempotencyKey'
|
||||
- $ref: '#/components/parameters/SimulationToken'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SimulationInput'}
|
||||
examples:
|
||||
BoundaryValues:
|
||||
summary: Exemplo técnico nos limites mínimos
|
||||
description: Valores mínimos para demonstrar a forma do payload; não são valores fiscais recomendados.
|
||||
value: {base: 0, rate: 0, reduction: 0}
|
||||
responses:
|
||||
'202':
|
||||
description: Simulação aceite para processamento
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
Location: {$ref: '#/components/headers/Location'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SimulationAccepted'}
|
||||
'200':
|
||||
description: Repetição idempotente da resposta original
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SimulationAccepted'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'409': {$ref: '#/components/responses/Conflict'}
|
||||
'422': {$ref: '#/components/responses/ValidationError'}
|
||||
'428': {$ref: '#/components/responses/PreconditionRequired'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/simulations/{id}:
|
||||
get:
|
||||
tags: [Simulações]
|
||||
operationId: getSimulation
|
||||
summary: Consultar simulação, cenários e estado de execução
|
||||
x-implementation-status: implemented
|
||||
security:
|
||||
- sessionCookie: []
|
||||
- {}
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SimulationId'
|
||||
- $ref: '#/components/parameters/SimulationToken'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Simulação dentro do âmbito autorizado
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/SimulationResponse'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/simulations/{id}/scenarios/{scenarioId}:
|
||||
patch:
|
||||
tags: [Simulações]
|
||||
operationId: updateSimulationScenario
|
||||
summary: Actualizar cenário com controlo optimista de concorrência
|
||||
x-implementation-status: implemented
|
||||
security:
|
||||
- sessionCookie: []
|
||||
- {}
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SimulationId'
|
||||
- $ref: '#/components/parameters/ScenarioId'
|
||||
- $ref: '#/components/parameters/IfMatch'
|
||||
- $ref: '#/components/parameters/SimulationToken'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/UpdateScenarioInput'}
|
||||
responses:
|
||||
'202':
|
||||
description: Alteração aceite e reexecução colocada em fila
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Scenario'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'412': {$ref: '#/components/responses/PreconditionFailed'}
|
||||
'422': {$ref: '#/components/responses/ValidationError'}
|
||||
'428': {$ref: '#/components/responses/PreconditionRequired'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/simulations/{id}/jobs:
|
||||
get:
|
||||
tags: [Jobs]
|
||||
operationId: listSimulationJobs
|
||||
summary: Consultar jobs de execução e geração de relatórios
|
||||
description: Contrato reservado para consulta dos jobs associados à simulação.
|
||||
x-implementation-status: contract-only
|
||||
security:
|
||||
- sessionCookie: []
|
||||
- {}
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SimulationId'
|
||||
- $ref: '#/components/parameters/SimulationToken'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Jobs visíveis no âmbito autorizado
|
||||
headers:
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/JobCollection'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/simulations/{id}/reports/{reportId}:
|
||||
get:
|
||||
tags: [Relatórios]
|
||||
operationId: getSimulationReport
|
||||
summary: Obter snapshot imutável de relatório
|
||||
x-implementation-status: implemented
|
||||
security:
|
||||
- sessionCookie: []
|
||||
- {}
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SimulationId'
|
||||
- $ref: '#/components/parameters/ReportId'
|
||||
- $ref: '#/components/parameters/SimulationToken'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Snapshot e hash do relatório
|
||||
headers:
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/ReportResponse'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/legislation/sources:
|
||||
get:
|
||||
tags: [Legislação]
|
||||
operationId: listLegislationSources
|
||||
summary: Consultar fontes legais publicadas e versionadas
|
||||
description: Contrato reservado para catálogo público de fontes; administração usa a API v2 existente.
|
||||
x-implementation-status: contract-only
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/Page'
|
||||
- $ref: '#/components/parameters/PerPage'
|
||||
- $ref: '#/components/parameters/Search'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Fontes legais publicadas
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/LegislationPage'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'422': {$ref: '#/components/responses/ValidationError'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v2/investment/admin/legal-sources:
|
||||
get:
|
||||
tags: [Administração, Legislação]
|
||||
operationId: adminListLegalSources
|
||||
summary: Listar fontes legais para administração
|
||||
x-implementation-status: implemented
|
||||
security: [{sessionCookie: []}]
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Lista de fontes legais
|
||||
headers:
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/AdminLegalSourcePage'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
post:
|
||||
tags: [Administração, Legislação]
|
||||
operationId: adminCreateLegalSource
|
||||
summary: Registar fonte legal para validação
|
||||
x-implementation-status: implemented
|
||||
security: [{sessionCookie: []}]
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/LegalSourceInput'}
|
||||
responses:
|
||||
'201':
|
||||
description: Fonte legal registada
|
||||
headers:
|
||||
Location: {$ref: '#/components/headers/Location'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/LegalSource'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'409': {$ref: '#/components/responses/Conflict'}
|
||||
'422': {$ref: '#/components/responses/ValidationError'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v2/investment/admin/legal-sources/{id}/{action}:
|
||||
post:
|
||||
tags: [Administração, Legislação]
|
||||
operationId: adminTransitionLegalSource
|
||||
summary: Validar ou revogar uma fonte legal
|
||||
x-implementation-status: implemented
|
||||
security: [{sessionCookie: []}]
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SourceId'
|
||||
- name: action
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, enum: [validate, revoke]}
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/LegalSourceTransitionInput'}
|
||||
responses:
|
||||
'200':
|
||||
description: Estado actualizado
|
||||
headers:
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/LegalSource'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'409': {$ref: '#/components/responses/Conflict'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/interest-requests:
|
||||
post:
|
||||
tags: [Manifestações]
|
||||
operationId: submitInterestRequest
|
||||
summary: Submeter manifestação de interesse
|
||||
x-implementation-status: implemented
|
||||
security: []
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/IdempotencyKeyOptional'
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/InterestRequestInput'}
|
||||
responses:
|
||||
'201':
|
||||
description: Manifestação submetida
|
||||
headers:
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/InterestRequestResponse'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'403': {$ref: '#/components/responses/Forbidden'}
|
||||
'409': {$ref: '#/components/responses/Conflict'}
|
||||
'422': {$ref: '#/components/responses/ValidationError'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
/api/v1/opportunities/{slug}:
|
||||
get:
|
||||
tags: [Oportunidades]
|
||||
operationId: getOpportunity
|
||||
summary: Consultar oportunidade publicada
|
||||
x-implementation-status: implemented
|
||||
security: []
|
||||
parameters:
|
||||
- name: slug
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, minLength: 1, maxLength: 180}
|
||||
- $ref: '#/components/parameters/CorrelationId'
|
||||
responses:
|
||||
'200':
|
||||
description: Oportunidade publicada
|
||||
headers:
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/OpportunityResponse'}
|
||||
'404': {$ref: '#/components/responses/NotFound'}
|
||||
'429': {$ref: '#/components/responses/RateLimited'}
|
||||
'500': {$ref: '#/components/responses/ServerError'}
|
||||
components:
|
||||
securitySchemes:
|
||||
sessionCookie:
|
||||
type: apiKey
|
||||
in: cookie
|
||||
name: laravel-session
|
||||
description: Sessão Laravel; o nome pode ser substituído por SESSION_COOKIE. Rotas públicas e simulações anónimas substituem explicitamente este requisito.
|
||||
parameters:
|
||||
CatalogName:
|
||||
name: catalog
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, enum: [authorities, jurisdictions, economic-activities]}
|
||||
Version:
|
||||
name: version
|
||||
in: query
|
||||
required: false
|
||||
description: Versão estável publicada do catálogo
|
||||
schema: {type: integer, minimum: 1}
|
||||
CatalogType:
|
||||
name: type
|
||||
in: query
|
||||
required: false
|
||||
description: Obrigatório para jurisdictions.
|
||||
schema: {type: string, enum: [country, province, district, admin_post, locality]}
|
||||
ParentId:
|
||||
name: parent_id
|
||||
in: query
|
||||
schema: {type: string, format: uuid}
|
||||
JurisdictionId:
|
||||
name: jurisdiction_id
|
||||
in: query
|
||||
schema: {type: string, format: uuid}
|
||||
Page:
|
||||
name: page
|
||||
in: query
|
||||
schema: {type: integer, minimum: 1, default: 1}
|
||||
PerPage:
|
||||
name: per_page
|
||||
in: query
|
||||
schema: {type: integer, minimum: 1, maximum: 100, default: 20}
|
||||
Search:
|
||||
name: q
|
||||
in: query
|
||||
schema: {type: string, maxLength: 100}
|
||||
QuestionnaireCode:
|
||||
name: code
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, pattern: '^[a-z0-9][a-z0-9-]{0,79}$'}
|
||||
SimulationId:
|
||||
name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, format: uuid}
|
||||
ScenarioId:
|
||||
name: scenarioId
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, format: uuid}
|
||||
ReportId:
|
||||
name: reportId
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, format: uuid}
|
||||
SourceId:
|
||||
name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, format: uuid}
|
||||
IdempotencyKey:
|
||||
name: Idempotency-Key
|
||||
in: header
|
||||
required: true
|
||||
description: Repetições com a mesma chave e payload devolvem a resposta original; payload diferente produz conflito.
|
||||
schema: {type: string, minLength: 16, maxLength: 128}
|
||||
IdempotencyKeyOptional:
|
||||
name: Idempotency-Key
|
||||
in: header
|
||||
required: false
|
||||
description: Se fornecida, deve ser UUID; uma chave repetida com outro payload produz conflito.
|
||||
schema: {type: string, format: uuid}
|
||||
SimulationToken:
|
||||
name: X-Simulation-Token
|
||||
in: header
|
||||
required: false
|
||||
description: Obrigatório para acesso anónimo; token opaco do cliente, guardado apenas como hash.
|
||||
schema: {type: string, minLength: 32, maxLength: 256}
|
||||
IfMatch:
|
||||
name: If-Match
|
||||
in: header
|
||||
required: true
|
||||
description: ETag forte da representação lida previamente.
|
||||
schema: {type: string, minLength: 1, maxLength: 128}
|
||||
CorrelationId:
|
||||
name: X-Correlation-ID
|
||||
in: header
|
||||
required: false
|
||||
description: UUID opcional propagado pela aplicação; quando ausente, a aplicação cria um identificador.
|
||||
schema: {type: string, format: uuid}
|
||||
headers:
|
||||
ETag:
|
||||
description: Validador da representação; usado com If-Match em alterações concorrentes.
|
||||
schema: {type: string}
|
||||
Location:
|
||||
description: URI relativa do recurso criado ou aceite.
|
||||
schema: {type: string, format: uri-reference}
|
||||
RetryAfter:
|
||||
description: Segundos até à próxima tentativa.
|
||||
schema: {type: integer, minimum: 0}
|
||||
CorrelationId:
|
||||
description: Identificador de correlação da operação.
|
||||
schema: {type: string, format: uuid}
|
||||
responses:
|
||||
Unauthorized:
|
||||
description: Autenticação necessária ou sessão inválida
|
||||
headers: {X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}}
|
||||
content: {application/json: {schema: {$ref: '#/components/schemas/Problem'}}}
|
||||
Forbidden:
|
||||
description: Actor autenticado sem autorização para a operação
|
||||
headers: {X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}}
|
||||
content: {application/json: {schema: {$ref: '#/components/schemas/Problem'}}}
|
||||
NotFound:
|
||||
description: Recurso inexistente ou fora do âmbito visível
|
||||
headers: {X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}}
|
||||
content: {application/json: {schema: {$ref: '#/components/schemas/Problem'}}}
|
||||
Conflict:
|
||||
description: Conflito de estado, versão ou chave idempotente
|
||||
headers: {X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Problem'}
|
||||
example: {message: A chave foi reutilizada com conteúdo diferente., code: idempotency_conflict}
|
||||
PreconditionFailed:
|
||||
description: If-Match não corresponde ao ETag actual
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Problem'}
|
||||
example: {message: A representação mudou; volte a consultar o recurso., code: stale_etag}
|
||||
ValidationError:
|
||||
description: Dados inválidos
|
||||
headers: {X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}}
|
||||
content: {application/json: {schema: {$ref: '#/components/schemas/ValidationProblem'}}}
|
||||
RateLimited:
|
||||
description: Limite de pedidos excedido
|
||||
headers:
|
||||
Retry-After: {$ref: '#/components/headers/RetryAfter'}
|
||||
X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}
|
||||
content: {application/json: {schema: {$ref: '#/components/schemas/Problem'}}}
|
||||
ServerError:
|
||||
description: Erro interno; resposta não contém detalhes sensíveis
|
||||
headers: {X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}}
|
||||
content: {application/json: {schema: {$ref: '#/components/schemas/Problem'}}}
|
||||
PreconditionRequired:
|
||||
description: Header obrigatório em falta, como If-Match ou Idempotency-Key
|
||||
headers: {X-Correlation-ID: {$ref: '#/components/headers/CorrelationId'}}
|
||||
content: {application/json: {schema: {$ref: '#/components/schemas/Problem'}}}
|
||||
schemas:
|
||||
Problem:
|
||||
type: object
|
||||
required: [message]
|
||||
properties:
|
||||
message: {type: string}
|
||||
code: {type: string}
|
||||
correlation_id: {type: string, format: uuid}
|
||||
additionalProperties: true
|
||||
ValidationProblem:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Problem'
|
||||
- type: object
|
||||
properties:
|
||||
errors:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: array
|
||||
items: {type: string}
|
||||
CatalogItem:
|
||||
type: object
|
||||
required: [id, value, code, name, label, locale, version_no]
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
value: {type: string}
|
||||
code: {type: string}
|
||||
name: {type: string, description: Rótulo apresentado em português de Moçambique.}
|
||||
label: {type: string}
|
||||
locale: {type: string, const: pt-MZ}
|
||||
parent_id: {type: [string, 'null']}
|
||||
type: {type: [string, 'null'], enum: [country, province, district, admin_post, locality, 'null']}
|
||||
authority_type: {type: [string, 'null']}
|
||||
organization_id: {type: [string, 'null'], format: uuid}
|
||||
jurisdiction_id: {type: [string, 'null'], format: uuid}
|
||||
jurisdiction_name: {type: [string, 'null']}
|
||||
source_code: {type: [string, 'null']}
|
||||
sector_id: {type: [string, 'null']}
|
||||
version_no: {type: integer}
|
||||
CatalogPage:
|
||||
type: object
|
||||
required: [data, meta]
|
||||
properties:
|
||||
data: {type: array, items: {$ref: '#/components/schemas/CatalogItem'}}
|
||||
links:
|
||||
type: object
|
||||
properties:
|
||||
next: {type: [string, 'null'], format: uri-reference}
|
||||
previous: {type: [string, 'null'], format: uri-reference}
|
||||
next_page_url: {type: [string, 'null'], format: uri-reference}
|
||||
prev_page_url: {type: [string, 'null'], format: uri-reference}
|
||||
current_page: {type: integer}
|
||||
per_page: {type: integer}
|
||||
total: {type: integer}
|
||||
last_page: {type: integer}
|
||||
meta:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/Pagination'
|
||||
- type: object
|
||||
properties:
|
||||
catalog: {type: string}
|
||||
version: {type: [integer, 'null']}
|
||||
locale: {type: string, const: pt-MZ}
|
||||
source_version: {type: [string, 'null']}
|
||||
status: {type: string, enum: [published, not_published]}
|
||||
Pagination:
|
||||
type: object
|
||||
required: [current_page, per_page, total]
|
||||
properties:
|
||||
current_page: {type: integer, minimum: 1}
|
||||
per_page: {type: integer, minimum: 1}
|
||||
total: {type: integer, minimum: 0}
|
||||
version: {type: string}
|
||||
QuestionnaireResponse:
|
||||
type: object
|
||||
required: [data]
|
||||
properties:
|
||||
data:
|
||||
type: object
|
||||
required: [id, code, version_no, locale, schema_snapshot, status]
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
code: {type: string}
|
||||
version_no: {type: integer, minimum: 1}
|
||||
locale: {type: string, const: pt-MZ}
|
||||
schema_snapshot: {type: object, additionalProperties: true}
|
||||
status: {type: string, const: published}
|
||||
valid_from: {type: [string, 'null'], format: date}
|
||||
valid_to: {type: [string, 'null'], format: date}
|
||||
SimulationInput:
|
||||
type: object
|
||||
required: [base, rate]
|
||||
properties:
|
||||
base: {type: number, minimum: 0, description: Valor de entrada sem moeda inferida.}
|
||||
rate: {type: number, minimum: 0, maximum: 100, description: Parâmetro fornecido pelo utilizador; não representa taxa oficial.}
|
||||
reduction: {type: number, minimum: 0, maximum: 100, default: 0}
|
||||
organization_id: {type: [string, 'null'], format: uuid}
|
||||
additionalProperties: false
|
||||
UpdateScenarioInput:
|
||||
type: object
|
||||
required: [label, base, rate]
|
||||
properties:
|
||||
label: {type: string, minLength: 1, maxLength: 100}
|
||||
base: {type: number, minimum: 0}
|
||||
rate: {type: number, minimum: 0, maximum: 100}
|
||||
reduction: {type: number, minimum: 0, maximum: 100, default: 0}
|
||||
additionalProperties: false
|
||||
SimulationAccepted:
|
||||
type: object
|
||||
required: [data, replayed]
|
||||
properties:
|
||||
data: {$ref: '#/components/schemas/Simulation'}
|
||||
replayed: {type: boolean}
|
||||
access_token: {type: string, minLength: 32, maxLength: 256, description: Devolvido apenas para execução anónima.}
|
||||
SimulationResponse:
|
||||
type: object
|
||||
required: [data]
|
||||
properties:
|
||||
data: {$ref: '#/components/schemas/Simulation'}
|
||||
Simulation:
|
||||
type: object
|
||||
required: [id, status, version_no, created_at, updated_at]
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
questionnaire_version_id: {type: [string, 'null'], format: uuid}
|
||||
organization_id: {type: [string, 'null'], format: uuid}
|
||||
version_no: {type: integer, minimum: 1}
|
||||
status: {type: string, enum: [queued, running, completed, failed, cancelled]}
|
||||
input_snapshot: {type: object, additionalProperties: true}
|
||||
result_snapshot: {type: [object, 'null'], additionalProperties: true}
|
||||
calculation_snapshot: {type: [object, 'null'], additionalProperties: true}
|
||||
scenarios: {type: array, items: {$ref: '#/components/schemas/Scenario'}}
|
||||
created_at: {type: string, format: date-time}
|
||||
updated_at: {type: string, format: date-time}
|
||||
Scenario:
|
||||
type: object
|
||||
required: [id, code, label, version_no, parameters]
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
code: {type: string}
|
||||
label: {type: string}
|
||||
version_no: {type: integer, minimum: 1}
|
||||
parameters: {type: object, additionalProperties: true}
|
||||
JobCollection:
|
||||
type: object
|
||||
required: [data]
|
||||
properties:
|
||||
data: {type: array, items: {$ref: '#/components/schemas/SimulationJob'}}
|
||||
SimulationJob:
|
||||
type: object
|
||||
required: [id, simulation_id, job_type, status, attempts, available_at]
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
simulation_id: {type: string, format: uuid}
|
||||
job_type: {type: string, enum: [execute, report]}
|
||||
status: {type: string, enum: [pending, running, succeeded, failed]}
|
||||
attempts: {type: integer, minimum: 0, maximum: 3}
|
||||
available_at: {type: string, format: date-time}
|
||||
started_at: {type: [string, 'null'], format: date-time}
|
||||
finished_at: {type: [string, 'null'], format: date-time}
|
||||
error_code: {type: [string, 'null']}
|
||||
ReportResponse:
|
||||
type: object
|
||||
required: [data]
|
||||
properties:
|
||||
data: {$ref: '#/components/schemas/SimulationReport'}
|
||||
SimulationReport:
|
||||
type: object
|
||||
required: [id, simulation_id, version_no, status]
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
simulation_id: {type: string, format: uuid}
|
||||
version_no: {type: integer, minimum: 1}
|
||||
status: {type: string, enum: [queued, ready, failed]}
|
||||
report_snapshot: {type: [object, 'null'], additionalProperties: true}
|
||||
report_sha256: {type: [string, 'null'], pattern: '^[0-9a-f]{64}$'}
|
||||
LegislationPage:
|
||||
type: object
|
||||
required: [data, meta]
|
||||
properties:
|
||||
data: {type: array, items: {$ref: '#/components/schemas/LegalSource'}}
|
||||
meta: {$ref: '#/components/schemas/Pagination'}
|
||||
AdminLegalSourcePage:
|
||||
type: object
|
||||
required: [data]
|
||||
properties:
|
||||
data: {type: array, items: {$ref: '#/components/schemas/LegalSource'}}
|
||||
current_page: {type: integer}
|
||||
per_page: {type: integer}
|
||||
total: {type: integer}
|
||||
last_page: {type: integer}
|
||||
first_page_url: {type: [string, 'null'], format: uri-reference}
|
||||
last_page_url: {type: [string, 'null'], format: uri-reference}
|
||||
next_page_url: {type: [string, 'null'], format: uri-reference}
|
||||
prev_page_url: {type: [string, 'null'], format: uri-reference}
|
||||
LegalSourceInput:
|
||||
type: object
|
||||
required: [title, url, diploma, article, competent_entity, valid_from]
|
||||
properties:
|
||||
title: {type: string, minLength: 1, maxLength: 255}
|
||||
url: {type: string, format: uri, pattern: '^https://', maxLength: 2000}
|
||||
diploma: {type: string, maxLength: 255}
|
||||
article: {type: string, maxLength: 255}
|
||||
competent_entity: {type: string, maxLength: 255}
|
||||
valid_from: {type: string, format: date}
|
||||
valid_until: {type: [string, 'null'], format: date}
|
||||
additionalProperties: false
|
||||
LegalSourceTransitionInput:
|
||||
type: object
|
||||
required: [version_no]
|
||||
properties:
|
||||
version_no: {type: integer, minimum: 1}
|
||||
additionalProperties: false
|
||||
LegalSource:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
title: {type: string}
|
||||
url: {type: string, format: uri}
|
||||
diploma: {type: string}
|
||||
article: {type: string}
|
||||
competent_entity: {type: string}
|
||||
validation_status: {type: string, enum: [pending, validated, revoked]}
|
||||
version_no: {type: integer}
|
||||
valid_until: {type: [string, 'null'], format: date}
|
||||
validator_id: {type: [integer, 'null']}
|
||||
validated_at: {type: [string, 'null'], format: date-time}
|
||||
valid_from: {type: [string, 'null'], format: date}
|
||||
InterestRequestInput:
|
||||
type: object
|
||||
required: [fullName, email, investorType, country, sectorInterest, message, privacyConsent]
|
||||
properties:
|
||||
fullName: {type: string, minLength: 3, maxLength: 150, writeOnly: true}
|
||||
email: {type: string, format: email, maxLength: 150, writeOnly: true}
|
||||
phone: {type: [string, 'null'], maxLength: 30, writeOnly: true}
|
||||
investorType: {type: string, enum: [individual, empresa, fundo, entidade_publica, outro]}
|
||||
country: {type: string, maxLength: 100}
|
||||
sectorInterest: {type: string, maxLength: 150}
|
||||
opportunityReference: {type: [string, 'null'], maxLength: 80}
|
||||
existingBusinessId: {type: [string, 'null'], format: uuid}
|
||||
modality: {type: [string, 'null'], maxLength: 50}
|
||||
investmentRange: {type: [string, 'null'], maxLength: 80}
|
||||
message: {type: string, minLength: 20, maxLength: 2000, writeOnly: true}
|
||||
privacyConsent: {type: boolean, const: true}
|
||||
shareWithProponent: {type: boolean, default: false}
|
||||
additionalProperties: false
|
||||
not:
|
||||
allOf:
|
||||
- required: [opportunityReference]
|
||||
properties:
|
||||
opportunityReference: {type: string, minLength: 1}
|
||||
- required: [existingBusinessId]
|
||||
properties:
|
||||
existingBusinessId: {type: string, format: uuid}
|
||||
allOf:
|
||||
- if:
|
||||
required: [existingBusinessId]
|
||||
properties:
|
||||
existingBusinessId: {type: string}
|
||||
then:
|
||||
required: [modality]
|
||||
properties:
|
||||
modality: {type: string, minLength: 1, maxLength: 50}
|
||||
InterestRequestResponse:
|
||||
type: object
|
||||
required: [success, message, data]
|
||||
properties:
|
||||
success: {type: boolean, const: true}
|
||||
message: {type: string}
|
||||
data:
|
||||
type: object
|
||||
required: [reference, status]
|
||||
properties:
|
||||
reference: {type: string}
|
||||
status: {type: string, const: received}
|
||||
OpportunityResponse:
|
||||
type: object
|
||||
required: [success, data]
|
||||
properties:
|
||||
success: {type: boolean, const: true}
|
||||
data:
|
||||
type: object
|
||||
required: [id, slug, title]
|
||||
properties:
|
||||
id: {type: [string, integer]}
|
||||
slug: {type: string}
|
||||
title: {type: string}
|
||||
summary: {type: [string, 'null']}
|
||||
status: {type: string}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\TerritorialCsvAudit;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
class AuditTerritorialCsv extends Command
|
||||
{
|
||||
protected $signature = 'geo:audit-csv {path : CSV UTF-8 do contrato INE}';
|
||||
|
||||
protected $description = 'Arquivar e validar um CSV territorial sem alterar o cadastro';
|
||||
|
||||
public function handle(TerritorialCsvAudit $audit): int
|
||||
{
|
||||
$path = (string) $this->argument('path');
|
||||
if (! is_file($path) || ! is_readable($path) || filesize($path) > 20 * 1024 * 1024) {
|
||||
$this->error('CSV inacessível ou superior a 20 MiB.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$directory = storage_path('app/private/geo-csv-audits/'.Str::uuid());
|
||||
File::ensureDirectoryExists($directory, 0700);
|
||||
try {
|
||||
if (! copy($path, $directory.'/original.csv')) {
|
||||
throw new \RuntimeException('Não foi possível arquivar o original.');
|
||||
}
|
||||
$codes = DB::table('geo_locations as p')->join('geo_locations as c', 'p.parent_id', '=', 'c.id')
|
||||
->where('p.location_type', 'province')->where('c.location_type', 'country')->where('c.code', '508')
|
||||
->whereNull('p.deleted_at')->whereNull('c.deleted_at')->pluck('p.code')->map(fn ($code) => (string) $code)->all();
|
||||
$report = $audit->inspect($directory.'/original.csv', array_values($codes));
|
||||
} catch (Throwable $exception) {
|
||||
$report = ['status' => 'rejected', 'error' => $exception->getMessage()];
|
||||
}
|
||||
File::put($directory.'/report.json', json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
$this->info('Relatório privado: '.$directory.'/report.json');
|
||||
$this->info('Nenhum território foi criado ou aprovado.');
|
||||
|
||||
return $report['status'] === 'rejected' ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\Mne\CompatibilityBackfill;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class BackfillMneCompatibility extends Command
|
||||
{
|
||||
protected $signature = 'mne:backfill-compatibility {--batch=100} {--dry-run : Execute validation and roll back all changes}';
|
||||
|
||||
protected $description = 'Reconcile compatibility identifiers without copying canonical business records';
|
||||
|
||||
public function handle(CompatibilityBackfill $backfill): int
|
||||
{
|
||||
$batch = filter_var($this->option('batch'), FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000]]);
|
||||
if ($batch === false) {
|
||||
$this->error('Batch must be between 1 and 1000');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if ($this->option('dry-run')) {
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$counts = $backfill->run($batch);
|
||||
} finally {
|
||||
DB::rollBack();
|
||||
}
|
||||
$this->line(json_encode(['dry_run' => true, 'rolled_back' => true, 'counts' => $counts], JSON_THROW_ON_ERROR));
|
||||
} else {
|
||||
$this->line(json_encode($backfill->run($batch), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class EscalateOverdueInvestmentTasks extends Command
|
||||
{
|
||||
protected $signature = 'investmoz:escalate-overdue-tasks';
|
||||
|
||||
protected $description = 'Eleva a prioridade de tarefas operacionais vencidas, quando activado.';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! config('existing-business.sla_escalation_enabled')) {
|
||||
$this->components->info('Escalada SLA desactivada.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$count = DB::table('tasks')->whereIn('task_type', ['triage', 'interest_follow_up'])
|
||||
->whereIn('status', ['open', 'in_progress'])->whereNotNull('due_at')->where('due_at', '<', now())
|
||||
->where('priority', '>', 1)->update(['priority' => 1, 'outcome' => 'sla_overdue', 'updated_at' => now()]);
|
||||
|
||||
$this->components->info("Tarefas elevadas para prioridade máxima: {$count}.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
class ImportTerritoryWorkbook extends Command
|
||||
{
|
||||
protected $signature = 'geo:import-workbook {--inspect : Inspect the authorised workbook without database writes} {--python=python : Python executable}';
|
||||
|
||||
protected $description = 'Inspect and idempotently import the authorised cartography workbook, preserving existing IDs';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! app()->environment('local', 'testing')) {
|
||||
$this->error('Local/testing only.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
foreach ([[strval($this->option('python')), base_path('tools/prepare-territory-workbook.py')],
|
||||
...($this->option('inspect') ? [] : [[PHP_BINARY, base_path('tools/import-territory-workbook.php')]])] as $command) {
|
||||
$process = new Process($command, base_path());
|
||||
$process->setTimeout(300);
|
||||
$process->run();
|
||||
$this->output->write($process->getOutput());
|
||||
if (! $process->isSuccessful()) {
|
||||
$this->error($process->getErrorOutput());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class ReconcileMneCompatibility extends Command
|
||||
{
|
||||
protected $signature = 'mne:reconcile-compatibility {--fail-on-difference : Return failure while any reconciliation or activation gate remains open}';
|
||||
|
||||
protected $description = 'Read-only compatibility counts, fingerprints and activation blockers';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$report = DB::transaction(function (): array {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
$domains = [];
|
||||
foreach (['identity' => ['users', 'identity_links', 'user_id'], 'sector' => ['sectors', 'sector_links', 'sector_id'],
|
||||
'business' => ['existing_businesses', 'business_links', 'legacy_business_id']] as $domain => [$source, $target, $key]) {
|
||||
$checksums = [];
|
||||
$stale = 0;
|
||||
$missing = 0;
|
||||
foreach (DB::table('public.'.$source)->orderBy('id')->cursor() as $row) {
|
||||
$checksum = hash('sha256', json_encode((array) $row, JSON_THROW_ON_ERROR));
|
||||
$checksums[] = $checksum;
|
||||
$link = DB::table('mne.'.$target)->where($key, $row->id)->first();
|
||||
$missing += $link === null ? 1 : 0;
|
||||
$stale += $link !== null && $link->source_checksum !== $checksum ? 1 : 0;
|
||||
}
|
||||
$domains[$domain] = ['source_count' => count($checksums), 'link_count' => DB::table('mne.'.$target)->count(),
|
||||
'pending_count' => DB::table('mne.'.$target)->where('status', '<>', 'active')->count(),
|
||||
'missing' => $missing, 'stale_checksums' => $stale, 'checksum' => hash('sha256', implode('', $checksums))];
|
||||
}
|
||||
$role = DB::selectOne('SELECT rolsuper,rolcreaterole FROM pg_roles WHERE rolname=current_user');
|
||||
|
||||
return ['domains' => $domains, 'unresolved_rejections' => DB::table('mne.compatibility_rejections')->whereNull('resolved_at')->count(),
|
||||
'runtime_is_superuser' => (bool) $role->rolsuper, 'runtime_can_create_roles' => (bool) $role->rolcreaterole,
|
||||
'canonical_reads_ready' => false, 'canonical_writes_ready' => false,
|
||||
'blockers' => ['Full canonical response mapping and authorization parity not certified',
|
||||
'Legacy intake does not capture a sector', 'Runtime privilege separation requires verification with deployment credentials']];
|
||||
});
|
||||
$this->line(json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
|
||||
// This release has no certified canonical adapter: strict gate checks cannot succeed yet.
|
||||
return $this->option('fail-on-difference') ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Interests\Enums;
|
||||
|
||||
enum InterestStatus: string
|
||||
{
|
||||
case Received = 'received';
|
||||
case Submitted = 'submitted';
|
||||
case InReview = 'in_review';
|
||||
case Reviewed = 'reviewed';
|
||||
case Qualification = 'qualification';
|
||||
case Qualified = 'qualified';
|
||||
case Contacted = 'contacted';
|
||||
case ContactAccepted = 'contact_accepted';
|
||||
case Referred = 'referred';
|
||||
case DueDiligence = 'due_diligence';
|
||||
case Negotiation = 'negotiation';
|
||||
case Pending = 'pending';
|
||||
case Refused = 'refused';
|
||||
case Converted = 'converted';
|
||||
case Cancelled = 'cancelled';
|
||||
case Closed = 'closed';
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Opportunities\Enums;
|
||||
|
||||
enum OpportunityStatus: string
|
||||
{
|
||||
case Draft = 'draft';
|
||||
case Submitted = 'submitted';
|
||||
case Triage = 'triage';
|
||||
case InformationPending = 'information_pending';
|
||||
case InReview = 'in_review';
|
||||
case Review = 'review';
|
||||
case ApprovalL1 = 'approval_l1';
|
||||
case ApprovalL2 = 'approval_l2';
|
||||
case Approved = 'approved';
|
||||
case Published = 'published';
|
||||
case NeedsInformation = 'needs_information';
|
||||
case Suspended = 'suspended';
|
||||
case Rejected = 'rejected';
|
||||
case Withdrawn = 'withdrawn';
|
||||
case Cancelled = 'cancelled';
|
||||
case Archived = 'archived';
|
||||
}
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Domain\Interests\Enums\InterestStatus;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StoreInterestRequestRequest;
|
||||
use App\Jobs\NotifyInterestReceived;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\IdempotencyConflict;
|
||||
use App\Services\InterestSubmission;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
@@ -33,8 +36,17 @@ class InterestRequestController extends Controller
|
||||
throw ValidationException::withMessages(['opportunityReference' => 'A oportunidade seleccionada já não está disponível.']);
|
||||
}
|
||||
|
||||
$business = ! empty($validated['existingBusinessId'])
|
||||
? ExistingBusiness::published()->whereKey($validated['existingBusinessId'])->first()
|
||||
: null;
|
||||
if (! empty($validated['existingBusinessId']) && ! $business) {
|
||||
throw ValidationException::withMessages(['existingBusinessId' => 'A oportunidade seleccionada já não está disponível.']);
|
||||
}
|
||||
|
||||
$interest = InterestRequest::create([
|
||||
'opportunity_id' => $opportunity?->id,
|
||||
'existing_business_id' => $business?->id,
|
||||
'modality' => $business ? $validated['modality'] : null,
|
||||
'reference' => $this->generateReference(),
|
||||
'full_name' => trim($validated['fullName']),
|
||||
'email' => strtolower(trim($validated['email'])),
|
||||
@@ -47,7 +59,7 @@ class InterestRequestController extends Controller
|
||||
'message' => trim($validated['message']),
|
||||
'privacy_consent' => (bool) $validated['privacyConsent'],
|
||||
'consented_at' => now(),
|
||||
'status' => 'received',
|
||||
'status' => InterestStatus::Received->value,
|
||||
'source_page' => Str::limit($request->headers->get('referer', ''), 255, ''),
|
||||
'ip_address' => $request->ip(),
|
||||
'user_agent' => $request->userAgent(),
|
||||
@@ -78,6 +90,12 @@ class InterestRequestController extends Controller
|
||||
} catch (IdempotencyConflict) {
|
||||
return response()->json(['success' => false, 'message' => 'A chave de envio já foi usada com dados diferentes.'], 409);
|
||||
} catch (ValidationException $exception) {
|
||||
throw $exception;
|
||||
} catch (QueryException $exception) {
|
||||
if ($exception->getCode() === '23505') {
|
||||
return response()->json(['success' => false, 'message' => 'Já existe uma manifestação activa para esta oportunidade e modalidade.'], 409);
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
} catch (\Throwable $exception) {
|
||||
Log::error('Erro ao registar manifestação de interesse', [
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class LegislationSourceController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:100'],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
]);
|
||||
|
||||
$today = today()->toDateString();
|
||||
$query = InvestmentLegalSource::query()
|
||||
->where('validation_status', 'validated')
|
||||
->whereDate('valid_from', '<=', $today)
|
||||
->where(fn ($query) => $query->whereNull('valid_until')->orWhereDate('valid_until', '>=', $today));
|
||||
|
||||
if (! empty($filters['q'])) {
|
||||
$term = '%'.addcslashes($filters['q'], '%_\\').'%';
|
||||
$query->where(fn ($query) => $query
|
||||
->whereRaw('title ILIKE ?', [$term])
|
||||
->orWhereRaw('diploma ILIKE ?', [$term])
|
||||
->orWhereRaw('article ILIKE ?', [$term])
|
||||
->orWhereRaw('competent_entity ILIKE ?', [$term]));
|
||||
}
|
||||
|
||||
$page = $query->orderBy('title')->orderBy('id')->paginate($filters['per_page'] ?? 25)->withQueryString();
|
||||
$data = collect($page->items())->map(fn (InvestmentLegalSource $source): array => [
|
||||
'id' => $source->id,
|
||||
'title' => $source->title,
|
||||
'url' => $source->url,
|
||||
'diploma' => $source->diploma,
|
||||
'article' => $source->article,
|
||||
'competent_entity' => $source->competent_entity,
|
||||
'validation_status' => $source->validation_status,
|
||||
'version_no' => (int) $source->version_no,
|
||||
'valid_from' => $source->valid_from,
|
||||
'valid_until' => $source->valid_until,
|
||||
'validator_id' => $source->validator_id === null ? null : (int) $source->validator_id,
|
||||
'validated_at' => $source->validated_at,
|
||||
])->values();
|
||||
$body = [
|
||||
'data' => $data,
|
||||
'meta' => [
|
||||
'current_page' => $page->currentPage(),
|
||||
'per_page' => $page->perPage(),
|
||||
'total' => $page->total(),
|
||||
],
|
||||
];
|
||||
$etag = 'W/"legal-sources-'.hash('sha256', json_encode([
|
||||
'filters' => $filters,
|
||||
'data' => $data,
|
||||
'total' => $page->total(),
|
||||
], JSON_THROW_ON_ERROR)).'"';
|
||||
|
||||
return response()->json($body)
|
||||
->header('ETag', $etag)
|
||||
->header('Cache-Control', 'public, max-age=300');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ReferenceCatalogController extends Controller
|
||||
{
|
||||
private const CATALOGS = ['authorities', 'jurisdictions', 'economic-activities'];
|
||||
|
||||
public function index(Request $request, string $catalog): JsonResponse
|
||||
{
|
||||
abort_unless(in_array($catalog, self::CATALOGS, true), 404);
|
||||
|
||||
$rules = [
|
||||
'q' => ['nullable', 'string', 'max:100'],
|
||||
'version' => ['nullable', 'integer', 'min:1'],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'parent_id' => ['nullable', 'uuid'],
|
||||
'jurisdiction_id' => ['nullable', 'uuid'],
|
||||
];
|
||||
if ($catalog === 'jurisdictions') {
|
||||
$rules['type'] = ['required', 'in:country,province,district,admin_post,locality'];
|
||||
$rules['parent_id'][] = 'prohibited_if:type,country';
|
||||
$rules['parent_id'][] = 'required_if:type,district,admin_post,locality';
|
||||
}
|
||||
if ($catalog === 'economic-activities') {
|
||||
$rules['sector_id'] = ['nullable', 'integer', 'exists:sectors,id'];
|
||||
}
|
||||
$data = $request->validate($rules);
|
||||
|
||||
$versionQuery = DB::table('reference_catalog_versions')->where('catalog_code', $catalog)->where('locale', 'pt-MZ');
|
||||
if (isset($data['version'])) {
|
||||
$versionQuery->where('version_no', $data['version'])->whereIn('status', ['published', 'retired']);
|
||||
} else {
|
||||
$versionQuery->where('status', 'published')
|
||||
->where(fn (Builder $query) => $query->whereNull('valid_from')->orWhere('valid_from', '<=', today()->toDateString()))
|
||||
->where(fn (Builder $query) => $query->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString()));
|
||||
}
|
||||
$version = $versionQuery->orderByDesc('version_no')->first();
|
||||
|
||||
if (isset($data['version']) && ! $version) {
|
||||
abort(404, 'Versão publicada do catálogo não encontrada.');
|
||||
}
|
||||
|
||||
if (! $version) {
|
||||
return response()->json([
|
||||
'data' => [],
|
||||
'links' => ['next' => null, 'previous' => null],
|
||||
'next_page_url' => null,
|
||||
'prev_page_url' => null,
|
||||
'current_page' => 1,
|
||||
'per_page' => $data['per_page'] ?? 20,
|
||||
'total' => 0,
|
||||
'last_page' => 1,
|
||||
'meta' => ['catalog' => $catalog, 'version' => null, 'locale' => 'pt-MZ', 'status' => 'not_published',
|
||||
'current_page' => 1, 'per_page' => $data['per_page'] ?? 20, 'total' => 0, 'last_page' => 1],
|
||||
])->header('Cache-Control', 'public, max-age=60');
|
||||
}
|
||||
|
||||
$query = match ($catalog) {
|
||||
'authorities' => $this->authorities((string) $version->id, $data),
|
||||
'jurisdictions' => $this->jurisdictions($data),
|
||||
'economic-activities' => $this->economicActivities((string) $version->id, $data),
|
||||
};
|
||||
|
||||
$page = $query->orderBy('code')->orderBy('id')->paginate($data['per_page'] ?? 20)->withQueryString();
|
||||
$items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, $row))->values();
|
||||
|
||||
return response()->json([
|
||||
'data' => $items,
|
||||
'links' => ['next' => $page->nextPageUrl(), 'previous' => $page->previousPageUrl()],
|
||||
'next_page_url' => $page->nextPageUrl(),
|
||||
'prev_page_url' => $page->previousPageUrl(),
|
||||
'current_page' => $page->currentPage(),
|
||||
'per_page' => $page->perPage(),
|
||||
'total' => $page->total(),
|
||||
'last_page' => $page->lastPage(),
|
||||
'meta' => ['catalog' => $catalog, 'version' => (int) $version->version_no, 'locale' => $version->locale,
|
||||
'source_version' => $version->source_version, 'valid_from' => $version->valid_from, 'valid_to' => $version->valid_to,
|
||||
'current_page' => $page->currentPage(), 'per_page' => $page->perPage(), 'total' => $page->total(), 'last_page' => $page->lastPage()],
|
||||
])->header('Cache-Control', 'public, max-age=300')
|
||||
->header('ETag', 'W/"catalog-'.substr(hash('sha256', $catalog.'|'.$version->version_no.'|'.json_encode($data, JSON_THROW_ON_ERROR)), 0, 32).'"');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function authorities(string $versionId, array $data): Builder
|
||||
{
|
||||
$query = DB::table('authorities as a')->join('organizations as o', 'o.id', '=', 'a.organization_id')
|
||||
->leftJoin('geo_locations as g', 'g.id', '=', 'a.jurisdiction_id')
|
||||
->where('a.catalog_version_id', $versionId)->where('a.status', 'published')
|
||||
->where('o.data_classification', 'public')->whereNull('o.deleted_at')
|
||||
->where('a.valid_from', '<=', today()->toDateString())
|
||||
->where(fn (Builder $builder) => $builder->whereNull('a.valid_to')->orWhere('a.valid_to', '>', today()->toDateString()))
|
||||
->select(['a.id', 'a.code', 'a.authority_type', 'a.label_pt_mz as name', 'a.organization_id', 'a.jurisdiction_id',
|
||||
'g.name as jurisdiction_name', 'a.version_no']);
|
||||
if (! empty($data['jurisdiction_id'])) {
|
||||
$query->where('a.jurisdiction_id', $data['jurisdiction_id']);
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$this->search($query, $data['q'], ['a.code', 'a.label_pt_mz', 'o.name']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function jurisdictions(array $data): Builder
|
||||
{
|
||||
$query = DB::table('geo_locations')->where('source_system', 'cartografia-workbook')
|
||||
->where('data_classification', 'public')->whereNull('deleted_at')->where('location_type', $data['type'])
|
||||
->select(['id', 'code', 'name', 'parent_id', 'location_type', 'source_code', 'version_no']);
|
||||
$parentType = ['province' => 'country', 'district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$data['type']] ?? null;
|
||||
if ($data['type'] !== 'country' && ! empty($data['parent_id'])) {
|
||||
$validParent = DB::table('geo_locations')->where('id', $data['parent_id'])->where('location_type', $parentType)
|
||||
->where('source_system', 'cartografia-workbook')->where('data_classification', 'public')->whereNull('deleted_at')->exists();
|
||||
if (! $validParent) {
|
||||
throw ValidationException::withMessages(['parent_id' => 'Seleccione um território pai activo do nível anterior.']);
|
||||
}
|
||||
$query->where('parent_id', $data['parent_id']);
|
||||
} elseif (in_array($data['type'], ['district', 'admin_post', 'locality'], true)) {
|
||||
throw ValidationException::withMessages(['parent_id' => 'Seleccione primeiro o território pai.']);
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$this->search($query, $data['q'], ['code', 'name', 'source_code']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function economicActivities(string $versionId, array $data): Builder
|
||||
{
|
||||
$query = DB::table('economic_activities')->where('catalog_version_id', $versionId)->where('status', 'published')
|
||||
->where('valid_from', '<=', today()->toDateString())
|
||||
->where(fn (Builder $builder) => $builder->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString()))
|
||||
->select(['id', 'code', 'label_pt_mz as name', 'parent_id', 'sector_id', 'version_no']);
|
||||
if (array_key_exists('parent_id', $data) && $data['parent_id'] !== null) {
|
||||
$query->where('parent_id', $data['parent_id']);
|
||||
} else {
|
||||
$query->whereNull('parent_id');
|
||||
}
|
||||
if (! empty($data['sector_id'])) {
|
||||
$query->where('sector_id', $data['sector_id']);
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$this->search($query, $data['q'], ['code', 'label_pt_mz']);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** @param list<string> $columns */
|
||||
private function search(Builder $query, string $search, array $columns): void
|
||||
{
|
||||
$term = '%'.addcslashes($search, '%_\\').'%';
|
||||
$query->where(function (Builder $nested) use ($columns, $term): void {
|
||||
foreach ($columns as $index => $column) {
|
||||
$method = $index === 0 ? 'whereRaw' : 'orWhereRaw';
|
||||
$nested->{$method}($column.' ILIKE ?', [$term]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function present(string $catalog, object $row): array
|
||||
{
|
||||
return match ($catalog) {
|
||||
'jurisdictions' => ['id' => $row->id, 'value' => $row->id, 'code' => $row->code, 'name' => $row->name,
|
||||
'label' => $row->name, 'locale' => 'pt-MZ', 'parent_id' => $row->parent_id, 'type' => $row->location_type,
|
||||
'source_code' => $row->source_code, 'version_no' => $row->version_no],
|
||||
'economic-activities' => ['id' => $row->id, 'value' => $row->code, 'code' => $row->code, 'name' => $row->name,
|
||||
'label' => $row->name, 'locale' => 'pt-MZ', 'parent_id' => $row->parent_id, 'sector_id' => $row->sector_id,
|
||||
'version_no' => $row->version_no],
|
||||
'authorities' => ['id' => $row->id, 'value' => $row->code, 'code' => $row->code, 'name' => $row->name,
|
||||
'label' => $row->name, 'locale' => 'pt-MZ', 'authority_type' => $row->authority_type,
|
||||
'organization_id' => $row->organization_id, 'jurisdiction_id' => $row->jurisdiction_id,
|
||||
'jurisdiction_name' => $row->jurisdiction_name, 'version_no' => $row->version_no],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StoreSimulationRequest;
|
||||
use App\Http\Requests\UpdateSimulationScenarioRequest;
|
||||
use App\Models\QuestionnaireVersion;
|
||||
use App\Models\SimulationJob;
|
||||
use App\Policies\SimulationPolicy;
|
||||
use App\Services\SimulationExecution;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SimulationController extends Controller
|
||||
{
|
||||
public function questionnaire(string $code): JsonResponse
|
||||
{
|
||||
abort_unless(preg_match('/^[a-z0-9][a-z0-9-]{0,79}$/', $code) === 1, 404);
|
||||
$version = QuestionnaireVersion::query()->where('code', $code)->where('locale', 'pt-MZ')->where('status', 'published')
|
||||
->where(fn ($query) => $query->whereNull('valid_from')->orWhereDate('valid_from', '<=', today()))
|
||||
->where(fn ($query) => $query->whereNull('valid_to')->orWhereDate('valid_to', '>', today()))
|
||||
->orderByDesc('version_no')->firstOrFail();
|
||||
$etag = '"questionnaire-'.$version->id.'-v'.$version->version_no.'"';
|
||||
|
||||
return response()->json(['data' => $version])->header('ETag', $etag)->header('Cache-Control', 'private, max-age=60');
|
||||
}
|
||||
|
||||
public function store(StoreSimulationRequest $request, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
$key = $request->header('Idempotency-Key');
|
||||
abort_unless(is_string($key) && strlen($key) >= 16 && strlen($key) <= 128, 428, 'Idempotency-Key é obrigatório.');
|
||||
$actorId = $request->user()?->id;
|
||||
$token = $actorId === null ? $request->header('X-Simulation-Token') : null;
|
||||
abort_if($actorId === null && (! is_string($token) || strlen($token) < 32 || strlen($token) > 256), 422, 'X-Simulation-Token opaco gerado pelo cliente é obrigatório para execução anónima.');
|
||||
$validated = $request->validated();
|
||||
$data = ['base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
|
||||
'reduction' => (string) ($validated['reduction'] ?? '0'), 'organization_id' => $validated['organization_id'] ?? null];
|
||||
$organizationId = $data['organization_id'] ?? null;
|
||||
$execution->authorizeOrganization($actorId, $organizationId);
|
||||
$result = $execution->create($data, $actorId, $organizationId, $token, $key);
|
||||
$simulation = $result['simulation'];
|
||||
$body = ['data' => $simulation, 'replayed' => $result['replayed']];
|
||||
if ($actorId === null) {
|
||||
$body['access_token'] = $token;
|
||||
}
|
||||
|
||||
return response()->json($body, $result['replayed'] ? 200 : 202)
|
||||
->header('ETag', $execution->etag($simulation))
|
||||
->header('Location', url('/api/v1/simulations/'.$simulation->id));
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->view($request->user(), $simulation), 404);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
|
||||
return response()->json(['data' => $simulation])->header('ETag', $execution->etag($simulation));
|
||||
}
|
||||
|
||||
public function updateScenario(UpdateSimulationScenarioRequest $request, string $id, string $scenarioId, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id) && Str::isUuid($scenarioId), 404);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->update($request->user(), $simulation), 403);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
$validated = $request->validated();
|
||||
$data = ['label' => (string) $validated['label'], 'base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
|
||||
'reduction' => (string) ($validated['reduction'] ?? '0')];
|
||||
$updated = $execution->updateScenario($id, $scenarioId, $data, $request);
|
||||
|
||||
return response()->json(['data' => $updated], 202)->header('ETag', $execution->etag($updated));
|
||||
}
|
||||
|
||||
public function report(Request $request, string $id, string $reportId, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id) && Str::isUuid($reportId), 404);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->view($request->user(), $simulation), 404);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
$report = $simulation->reports->firstWhere('id', $reportId);
|
||||
abort_if($report === null, 404);
|
||||
|
||||
return response()->json(['data' => $report]);
|
||||
}
|
||||
|
||||
public function jobs(Request $request, string $id, SimulationExecution $execution): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$simulation = $execution->find($id, $request);
|
||||
if ($request->user()) {
|
||||
abort_unless(app(SimulationPolicy::class)->view($request->user(), $simulation), 404);
|
||||
} else {
|
||||
abort_unless($simulation->anonymous_token_hash !== null && hash_equals($simulation->anonymous_token_hash, (string) $execution->tokenHash($request)), 404);
|
||||
}
|
||||
|
||||
$jobs = DB::transaction(function () use ($request, $id, $execution) {
|
||||
$execution->setContext($request->user()?->id, $execution->tokenHash($request));
|
||||
|
||||
return SimulationJob::query()->where('simulation_id', $id)
|
||||
->orderBy('created_at')->orderBy('id')->get();
|
||||
});
|
||||
|
||||
return response()->json(['data' => $jobs]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StoreSimulationFormDraftRequest;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Services\SimulationFormDrafts;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SimulationFormDraftController extends Controller
|
||||
{
|
||||
public function store(StoreSimulationFormDraftRequest $request, SimulationFormDrafts $drafts): JsonResponse
|
||||
{
|
||||
$key = $request->header('Idempotency-Key');
|
||||
abort_unless(is_string($key) && strlen($key) >= 16 && strlen($key) <= 128, 428, 'Idempotency-Key é obrigatório.');
|
||||
$result = $drafts->create($request->validated(), $request, $key);
|
||||
$draft = $result['draft'];
|
||||
|
||||
return response()->json(['data' => ['id' => $draft->id, 'version_no' => $draft->version_no, 'replayed' => $result['replayed']]], $result['replayed'] ? 200 : 201)
|
||||
->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
|
||||
public function current(Request $request, SimulationFormDrafts $drafts): JsonResponse
|
||||
{
|
||||
$draft = $drafts->current($request);
|
||||
if (! $draft) {
|
||||
return response()->json(['data' => null], 200)->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
|
||||
return response()->json(['data' => $drafts->present($draft)])->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$draft = $drafts->find($id, $request);
|
||||
|
||||
return response()->json(['data' => $drafts->present($draft)])->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
|
||||
public function update(StoreSimulationFormDraftRequest $request, string $id, SimulationFormDrafts $drafts): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$draft = $drafts->update($id, $request->validated(), $request);
|
||||
|
||||
return response()->json(['data' => ['id' => $draft->id, 'version_no' => $draft->version_no]])
|
||||
->header('ETag', $drafts->etag($draft))->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
|
||||
public function destroy(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$drafts->delete($id, $request);
|
||||
|
||||
return response()->json([], 204)->header('Cache-Control', 'no-store, private');
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,9 @@ class EducationController extends Controller
|
||||
'providers' => TrainingProvider::where('status', '!=', 'inactive')->orderBy('name')->get(['id', 'name']),
|
||||
'courses' => Course::where('status', '!=', 'retired')->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id'))->orderBy('title')->get(['id', 'title', 'provider_id']),
|
||||
'projects' => Project::orderBy('name')->get(['id', 'code', 'name']),
|
||||
'territories' => DB::table('geo_locations')->whereNull('deleted_at')->orderBy('name')->get(['id', 'name', 'code']),
|
||||
'territories' => DB::table('geo_locations')->whereNull('deleted_at')
|
||||
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])
|
||||
->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']),
|
||||
'today' => now()->toDateString(),
|
||||
]);
|
||||
}
|
||||
@@ -148,6 +150,7 @@ class EducationController extends Controller
|
||||
return Inertia::render('education/analysis', ['demand' => $demand, 'candidates' => $candidates,
|
||||
'proposal' => EducationInvestmentProposal::where('labour_demand_id', $id)->first(),
|
||||
'sectors' => Sector::orderBy('name')->get(['id', 'name']),
|
||||
'territoryPath' => app(InvestmentGeography::class)->path($demand->getAttribute('geo_location_id'), true),
|
||||
'eligible' => $eligible, 'gap' => $calculator->observed((int) $demand->getAttribute('quantity'), null, $eligible, $current)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
|
||||
use App\Models\EducationInvestmentProposal;
|
||||
use App\Models\LabourDemand;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\PortalAudit;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -27,6 +28,10 @@ class EducationInvestmentController extends Controller
|
||||
'risks' => ['required', 'string', 'min:10', 'max:5000'],
|
||||
'source' => ['required', 'string', 'min:10', 'max:5000'],
|
||||
'currency' => ['required', Rule::in(['MZN', 'USD', 'EUR', 'ZAR'])],
|
||||
'province_id' => ['required', 'uuid'],
|
||||
'district_id' => ['nullable', 'uuid'],
|
||||
'admin_post_id' => ['nullable', 'uuid'],
|
||||
'locality_id' => ['nullable', 'uuid'],
|
||||
]);
|
||||
|
||||
DB::transaction(function () use ($request, $id, $data): void {
|
||||
@@ -38,6 +43,10 @@ class EducationInvestmentController extends Controller
|
||||
if (EducationInvestmentProposal::withTrashed()->where('labour_demand_id', $id)->exists()) {
|
||||
return;
|
||||
}
|
||||
$territory = app(InvestmentGeography::class)->selection($data, true);
|
||||
$province = $territory[0];
|
||||
$district = $territory[1] ?? null;
|
||||
$primaryTerritory = $territory[array_key_last($territory)];
|
||||
$reference = 'EDU-'.Str::uuid();
|
||||
$opportunity = new Opportunity;
|
||||
PortalAudit::save($opportunity, [
|
||||
@@ -45,6 +54,8 @@ class EducationInvestmentController extends Controller
|
||||
'slug' => strtolower($reference), 'title' => $data['title'],
|
||||
'summary' => 'Proposta educativa em preparação. Lacuna e viabilidade pendentes de validação institucional.',
|
||||
'description' => $data['intervention'], 'estimated_investment_currency' => $data['currency'],
|
||||
'province' => $province->name, 'district' => $district?->name,
|
||||
'primary_territory_id' => $primaryTerritory->id, 'territory_version' => 1,
|
||||
'status' => 'draft', 'is_featured' => false,
|
||||
], $request->user()->id);
|
||||
PortalAudit::save(new EducationInvestmentProposal, [
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\Sector;
|
||||
use App\Services\BusinessFormSchema;
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use App\Services\ExistingBusinessIntake;
|
||||
use App\Services\ExistingBusinessObjects;
|
||||
use App\Services\ExistingBusinessVerification;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use App\Services\Mne\CompatibilityShadow;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class ExistingBusinessController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|JsonResponse
|
||||
{
|
||||
$management = $request->is('management/*', 'api/v1/existing-business/review*');
|
||||
$query = app(BusinessRepository::class)->query();
|
||||
if ($management) {
|
||||
Gate::authorize('reviewQueue', ExistingBusiness::class);
|
||||
$query->where('owner_user_id', '<>', $request->user()->id)->whereIn('status', [
|
||||
'submitted', 'triage', 'in_review', 'needs_information', 'approval_l1', 'approval_l2', 'approved',
|
||||
]);
|
||||
} else {
|
||||
$query->where('owner_user_id', $request->user()->id);
|
||||
}
|
||||
$props = ['records' => $query->orderByDesc('updated_at')->paginate(20)->through(fn ($row) => $this->record($row)),
|
||||
'management' => $management, 'modalities' => ExistingBusinessDrafts::MODALITIES];
|
||||
|
||||
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/businesses', $props);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id): Response|JsonResponse
|
||||
{
|
||||
$business = app(BusinessRepository::class)->find($id);
|
||||
Gate::authorize('view', $business);
|
||||
app(CompatibilityShadow::class)->schedule($id);
|
||||
$props = ['sectors' => Sector::where('is_active', true)->orderBy('name')->get(['id', 'name']), 'formSchema' => BusinessFormSchema::fields(), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
||||
'canTriage' => $request->user()->can('triage', $business),
|
||||
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
|
||||
'canApproveLevelTwo' => $request->user()->can('approveLevelTwo', $business),
|
||||
'canPublish' => $request->user()->can('publish', $business),
|
||||
'modalities' => ExistingBusinessDrafts::MODALITIES,
|
||||
'objectKinds' => ExistingBusinessObjects::KINDS,
|
||||
'verificationChecks' => ExistingBusinessVerification::CHECKS,
|
||||
'verifications' => app(ExistingBusinessVerification::class)->findings($business),
|
||||
'objects' => ExistingBusinessObject::where('business_id', $id)->orderBy('created_at')->get()->map(fn ($object) => [
|
||||
...$object->only(['id', 'kind', 'verification_status']), 'payload' => $object->payload]),
|
||||
'history' => DB::table('existing_business_revisions')->where('business_id', $id)->orderByDesc('version_no')->limit(50)
|
||||
->get(['version_no', 'action', 'created_at', 'reason'])->map(fn ($row) => ['version_no' => $row->version_no,
|
||||
'action' => $row->action, 'created_at' => $row->created_at, 'note' => Crypt::decryptString($row->reason)])];
|
||||
|
||||
return $request->expectsJson() ? response()->json($props) : Inertia::render('investment/business', $props);
|
||||
}
|
||||
|
||||
public function save(Request $request, ExistingBusinessDrafts $drafts, ?string $id = null): JsonResponse
|
||||
{
|
||||
$business = $drafts->save($request->user(), $request->all(), $id);
|
||||
|
||||
return response()->json($this->record($business), $id ? 200 : 201);
|
||||
}
|
||||
|
||||
public function transition(Request $request, ExistingBusinessIntake $intake, string $id): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'action' => ['required', 'string'],
|
||||
'note' => ['required', 'string'], 'review_consent' => ['nullable', 'boolean'], 'confirmation_code' => ['nullable', 'string', 'max:100']]);
|
||||
$business = $intake->transition($request->user(), $id, $data['version_no'], $data['action'], $data['note'], (bool) ($data['review_consent'] ?? false), $data['confirmation_code'] ?? null);
|
||||
|
||||
return response()->json($this->record($business));
|
||||
}
|
||||
|
||||
public function verify(Request $request, ExistingBusinessVerification $verification, string $id): JsonResponse
|
||||
{
|
||||
return response()->json($this->record($verification->save($request->user(), $id, $request->all())));
|
||||
}
|
||||
|
||||
public function saveObject(Request $request, ExistingBusinessObjects $objects, string $id, ?string $object = null): JsonResponse
|
||||
{
|
||||
$saved = $objects->save($request->user(), $id, $request->all(), $object);
|
||||
|
||||
return response()->json(['id' => $saved->id, 'verification_status' => 'pending',
|
||||
'version_no' => app(BusinessRepository::class)->find($id)->version_no], $object ? 200 : 201);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function record(ExistingBusiness $business): array
|
||||
{
|
||||
return [...$business->only([
|
||||
'id', 'code', 'modality', 'status', 'classification', 'version_no', 'sector_id', 'public_title', 'public_slug',
|
||||
'activity_code', 'stage', 'objective', 'currency', 'amount_min', 'amount_max', 'available_percentage',
|
||||
'funds_use', 'submitted_at', 'published_at', 'expires_at', 'next_action', 'next_action_due_at', 'assigned_to',
|
||||
]), 'payload' => $business->payload];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class InvestmentCoordinatesController extends Controller
|
||||
{
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
Opportunity::findOrFail($id);
|
||||
$point = DB::table('geo_locations as g')->join('geo_geometries as s', 's.geo_location_id', '=', 'g.id')
|
||||
->where('g.source_system', 'investment-site-editor')->where('g.external_id', (string) $id)->whereNull('g.deleted_at')->whereNull('s.deleted_at')
|
||||
->first(['s.version_no', 's.properties', DB::raw('ST_X(s.geom) as longitude'), DB::raw('ST_Y(s.geom) as latitude')]);
|
||||
|
||||
return response()->json(['version' => $point->version_no ?? 0, 'latitude' => $point?->latitude, 'longitude' => $point?->longitude,
|
||||
'source_reference' => $point ? (json_decode($point->properties, true)['source_reference'] ?? '') : '']);
|
||||
}
|
||||
|
||||
public function save(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'latitude' => ['required', 'numeric', 'between:-90,90'],
|
||||
'longitude' => ['required', 'numeric', 'between:-180,180'], 'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'confirmed_site' => ['accepted']]);
|
||||
$version = DB::transaction(function () use ($data, $id, $request) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
|
||||
$opportunity = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
$location = DB::table('geo_locations')->where('source_system', 'investment-site-editor')->where('external_id', (string) $id)->first();
|
||||
abort_if($location && $location->deleted_at, 409, 'Local arquivado; requer reconciliação.');
|
||||
abort_if($location && $location->data_classification !== 'public', 409, 'Local retirado de divulgação; requer revisão da classificação.');
|
||||
$geometry = $location ? DB::table('geo_geometries')->where('geo_location_id', $location->id)->where('geometry_type', 'point')->first() : null;
|
||||
abort_if($geometry && $geometry->deleted_at, 409, 'Geometria arquivada; requer reconciliação.');
|
||||
abort_if($geometry && $geometry->data_classification !== 'public', 409, 'Geometria retirada de divulgação; requer revisão da classificação.');
|
||||
abort_unless((int) ($geometry->version_no ?? 0) === $data['version'], 409, 'Coordenadas alteradas. Recarregue.');
|
||||
$locationId = $location->id ?? (string) Str::uuid();
|
||||
if (! $location) {
|
||||
DB::table('geo_locations')->insert(['id' => $locationId, 'source_system' => 'investment-site-editor', 'external_id' => (string) $id,
|
||||
'name' => $opportunity->title, 'location_type' => 'site', 'code' => 'SITE-OPP-'.$id, 'data_classification' => 'public', 'parent_id' => $opportunity->primary_territory_id]);
|
||||
}
|
||||
$version = $data['version'] + 1;
|
||||
$geometryId = $geometry->id ?? (string) Str::uuid();
|
||||
DB::statement("INSERT INTO geo_geometries(id,geo_location_id,geometry_type,geom,data_classification,version_no,properties)
|
||||
VALUES(?,?,'point',ST_SetSRID(ST_MakePoint(?,?),4326),'public',?,?::jsonb)
|
||||
ON CONFLICT(id) DO UPDATE SET geom=EXCLUDED.geom,version_no=EXCLUDED.version_no,properties=EXCLUDED.properties,updated_at=now()",
|
||||
[$geometryId, $locationId, $data['longitude'], $data['latitude'], $version, json_encode(['source_reference' => $data['source_reference'], 'accuracy' => 'site_confirmed_by_editor'], JSON_THROW_ON_ERROR)]);
|
||||
DB::table('opportunity_locations')->updateOrInsert(['opportunity_id' => $id, 'geo_location_id' => $locationId], []);
|
||||
DB::table('audit_events')->insert(['source_system' => 'investment-coordinates', 'entity_type' => 'geo_geometries', 'entity_id' => $geometryId,
|
||||
'actor_user_id' => $request->user()->id, 'action' => 'site_coordinates_saved',
|
||||
'before_data' => $geometry ? json_encode(['version' => $geometry->version_no, 'geometry_hex' => $geometry->geom], JSON_THROW_ON_ERROR) : null,
|
||||
'after_data' => json_encode(['opportunity_id' => $id, 'version' => $version, 'latitude' => $data['latitude'], 'longitude' => $data['longitude'], 'source_sha256' => hash('sha256', $data['source_reference'])], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $version;
|
||||
});
|
||||
|
||||
return response()->json(['version' => $version]);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentZones;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -23,7 +24,8 @@ class InvestmentDiscoveryController extends Controller
|
||||
$filters['education'] = true;
|
||||
}
|
||||
|
||||
return Inertia::render('investment/catalogue', ['filters' => $filters, 'references' => $catalogue->references(),
|
||||
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(),
|
||||
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
|
||||
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
|
||||
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
|
||||
'territorial' => $this->territorial($filters)]);
|
||||
@@ -36,6 +38,15 @@ class InvestmentDiscoveryController extends Controller
|
||||
private function territorial(array $filters): Collection
|
||||
{
|
||||
$query = InvestmentPortfolioController::visible();
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->where(function ($query) use ($ids) {
|
||||
foreach (['project_id' => 'projects', 'cluster_id' => 'economic_clusters', 'corridor_id' => 'development_corridors'] as $foreign => $table) {
|
||||
$query->orWhereIn($foreign, DB::table($table)->whereNull('deleted_at')->whereIn('primary_territory_id', $ids)->select('id'));
|
||||
}
|
||||
});
|
||||
}
|
||||
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
|
||||
return $query->whereRaw('false')->get();
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ class InvestmentLegalSourceController extends Controller
|
||||
$source->refresh();
|
||||
$this->audit($source, $request->user()->id, 'created');
|
||||
|
||||
return response()->json($source->fresh(), 201);
|
||||
return response()->json($source->fresh(), 201)
|
||||
->header('Location', url('/api/v2/investment/admin/legal-sources/'.$source->id));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Models\EconomicCluster;
|
||||
use App\Models\InvestmentGap;
|
||||
use App\Models\Project;
|
||||
use App\Models\ValueChain;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\PortalAudit;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -74,7 +75,19 @@ class InvestmentStructureController extends Controller
|
||||
} else {
|
||||
$rules['sector'] = ['required', 'string', 'max:200'];
|
||||
}
|
||||
PortalAudit::save($record, $request->validate($rules), $request->user()->id);
|
||||
if (! $id) {
|
||||
foreach (InvestmentGeography::FIELDS as $field => $type) {
|
||||
$rules[$field] = ['nullable', 'uuid'];
|
||||
}
|
||||
}
|
||||
$data = $request->validate($rules);
|
||||
if (! $id && $request->has('province_id')) {
|
||||
$path = app(InvestmentGeography::class)->selection($data, true);
|
||||
$data = array_diff_key($data, InvestmentGeography::FIELDS);
|
||||
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
$data['territory_version'] = $path === [] ? 0 : 1;
|
||||
}
|
||||
PortalAudit::save($record, $data, $request->user()->id);
|
||||
|
||||
return redirect('/management/'.$structure.'/'.$record->getKey().'/edit')->with('success', 'Registo guardado.');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\InvestmentZones;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class InvestmentTerritoryController extends Controller
|
||||
{
|
||||
private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones'];
|
||||
|
||||
public function subjects(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['kind' => ['required', 'in:'.implode(',', array_keys(self::TABLES))], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$column = $data['kind'] === 'opportunities' ? 'title' : 'name';
|
||||
$query = DB::table(self::TABLES[$data['kind']])->whereNull('deleted_at');
|
||||
if (! empty($data['q'])) {
|
||||
$query->whereRaw($column.' ILIKE ?', ['%'.addcslashes($data['q'], '%_\\').'%']);
|
||||
}
|
||||
|
||||
return response()->json($query->orderBy($column)->orderBy('id')->paginate(50, ['id', $column.' as name']));
|
||||
}
|
||||
|
||||
public function options(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$query = DB::table('geo_locations')->whereNull('deleted_at')->where('location_type', $data['type'])
|
||||
->whereIn('data_classification', ['public', 'internal']);
|
||||
if ($data['type'] !== 'province') {
|
||||
$parentType = ['district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$data['type']];
|
||||
if (! DB::table('geo_locations')->where('id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000')->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])->where('location_type', $parentType)->exists()) {
|
||||
throw ValidationException::withMessages(['parent_id' => 'Seleccione um pai activo do nível anterior.']);
|
||||
}
|
||||
$query->where('parent_id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000');
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$term = '%'.addcslashes($data['q'], '%_\\').'%';
|
||||
$query->where(fn ($q) => $q->whereRaw('name ILIKE ?', [$term])->orWhereRaw('code ILIKE ?', [$term])->orWhereRaw('source_code ILIKE ?', [$term]));
|
||||
}
|
||||
|
||||
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code']));
|
||||
}
|
||||
|
||||
public function show(string $kind, string $id): JsonResponse
|
||||
{
|
||||
$table = self::TABLES[$kind] ?? abort(404);
|
||||
$record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->first();
|
||||
abort_unless($record !== null, 404);
|
||||
$path = [];
|
||||
$current = $record->primary_territory_id;
|
||||
for ($i = 0; $current && $i < 5; $i++) {
|
||||
$location = DB::table('geo_locations')->where('id', $current)->first(['id', 'name', 'parent_id', 'location_type', 'deleted_at']);
|
||||
if (! $location) {
|
||||
break;
|
||||
}
|
||||
$path[] = $location;
|
||||
$current = $location->parent_id;
|
||||
}
|
||||
|
||||
return response()->json(['version' => $record->territory_version, 'path' => $path]);
|
||||
}
|
||||
|
||||
public function save(Request $request, string $kind, string $id): JsonResponse
|
||||
{
|
||||
$table = self::TABLES[$kind] ?? abort(404);
|
||||
if ($kind === 'zones') {
|
||||
abort_unless($request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403);
|
||||
}
|
||||
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'path' => ['present', 'array', 'max:4'], 'path.*' => ['required', 'uuid', 'distinct']]);
|
||||
$version = DB::transaction(function () use ($request, $table, $id, $data) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
|
||||
$record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
abort_unless($record !== null, 404);
|
||||
abort_unless((int) $record->territory_version === $data['version'], 409, 'Localização alterada. Recarregue a ficha.');
|
||||
$parent = null;
|
||||
$names = [];
|
||||
foreach (array_values($data['path']) as $index => $locationId) {
|
||||
$location = DB::table('geo_locations')->where('id', $locationId)->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])->first();
|
||||
if (! $location || $location->location_type !== ['province', 'district', 'admin_post', 'locality'][$index] || ($index > 0 && $location->parent_id !== $parent)) {
|
||||
throw ValidationException::withMessages(['path' => 'Seleccione uma hierarquia territorial coerente e activa.']);
|
||||
}
|
||||
$parent = $locationId;
|
||||
$names[] = $location->name;
|
||||
}
|
||||
$version = $data['version'] + 1;
|
||||
$changes = ['primary_territory_id' => $parent, 'territory_version' => $version, 'updated_at' => now()];
|
||||
if (in_array($table, ['opportunities', 'investment_zones'], true)) {
|
||||
$changes['province'] = $names[0] ?? null;
|
||||
$changes['district'] = $names[1] ?? null;
|
||||
}
|
||||
if ($table === 'investment_zones') {
|
||||
app(InvestmentZones::class)->save($id, [...$changes, 'version_no' => $record->version_no], $request->user()->id);
|
||||
} else {
|
||||
DB::table($table)->where('id', $id)->update($changes);
|
||||
}
|
||||
DB::table('audit_events')->insert(['source_system' => 'investment-territory', 'entity_type' => $table,
|
||||
'actor_user_id' => $request->user()->id, 'action' => 'primary_territory_saved',
|
||||
'after_data' => json_encode(['record_id' => $id, 'territory_id' => $parent, 'version' => $version], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $version;
|
||||
});
|
||||
|
||||
return response()->json(['version' => $version]);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Models\InvestmentDossier;
|
||||
use App\Models\InvestmentZone;
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentZoneAccess;
|
||||
use App\Services\InvestmentZones;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -49,13 +50,18 @@ class InvestmentZoneController extends Controller
|
||||
|
||||
public function index(Request $request, InvestmentZones $zones): Response|JsonResponse
|
||||
{
|
||||
$filters = $request->validate(['category' => ['nullable', 'in:zee,zfi,industrial_park'], 'q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$filters = $request->validate(['category' => ['nullable', 'in:zee,zfi,industrial_park'], 'q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
|
||||
$management = $request->is('management/*', 'api/v2/investment/admin/*');
|
||||
$query = $management ? InvestmentZone::query() : $zones->visible();
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$query->whereIn('primary_territory_id', app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
|
||||
}
|
||||
$rows = $query->when($filters['category'] ?? null, fn ($q, $v) => $q->where('category', $v))
|
||||
->when($filters['q'] ?? null, fn ($q, $v) => $q->where(fn ($q) => $q->where('name', 'ilike', '%'.$v.'%')->orWhere('code', 'ilike', '%'.$v.'%')))
|
||||
->orderBy('name')->orderBy('id')->paginate(12, $management ? ['*'] : ['id', 'code', 'name', 'name_en', 'category', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'])->withQueryString();
|
||||
$props = ['records' => $rows, 'filters' => $filters, 'management' => $management];
|
||||
$props = ['records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path];
|
||||
|
||||
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props);
|
||||
}
|
||||
@@ -70,6 +76,15 @@ class InvestmentZoneController extends Controller
|
||||
'operator_id' => ['nullable', 'uuid', Rule::exists('organizations', 'id')->whereNull('deleted_at')],
|
||||
'legal_source_id' => ['nullable', 'uuid', 'exists:investment_legal_sources,id']]);
|
||||
|
||||
if (! $id && $request->has('province_id')) {
|
||||
$geo = $request->validate(['province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
|
||||
$path = app(InvestmentGeography::class)->selection($geo, true);
|
||||
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
$data['territory_version'] = $path === [] ? 0 : 1;
|
||||
$data['province'] = $path[0]->name ?? null;
|
||||
$data['district'] = $path[1]->name ?? null;
|
||||
}
|
||||
|
||||
return response()->json($zones->save($id, $data, $request->user()->id), $id ? 200 : 201);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,11 +6,16 @@ use App\Models\InterestRequest;
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\InterestWorkflow;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\InvestmentWorkspace;
|
||||
use App\Services\PortalAudit;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -21,7 +26,7 @@ use Inertia\Response;
|
||||
|
||||
class PortalManagementController extends Controller
|
||||
{
|
||||
private const STATES = ['received', 'in_review', 'contacted', 'closed'];
|
||||
private const STATES = ['received', 'submitted', 'in_review', 'reviewed', 'qualification', 'qualified', 'contacted', 'contact_accepted', 'referred', 'due_diligence', 'negotiation', 'pending', 'refused', 'converted', 'cancelled', 'closed'];
|
||||
|
||||
public function history(): Response
|
||||
{
|
||||
@@ -49,9 +54,10 @@ class PortalManagementController extends Controller
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:150'],
|
||||
'status' => ['nullable', Rule::in(self::STATES)],
|
||||
'follow_up' => ['nullable', Rule::in(['overdue', 'upcoming', 'unassigned'])],
|
||||
]);
|
||||
$query = InterestRequest::query()->select([
|
||||
'id', 'reference', 'full_name', 'email', 'sector_interest', 'status', 'created_at',
|
||||
$query = InterestRequest::query()->with('assignee:id,name')->select([
|
||||
'id', 'reference', 'full_name', 'email', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
|
||||
]);
|
||||
if ($term = $filters['q'] ?? null) {
|
||||
$query->where(fn ($q) => $q->whereLike('reference', "%{$term}%")
|
||||
@@ -60,6 +66,15 @@ class PortalManagementController extends Controller
|
||||
if ($status = $filters['status'] ?? null) {
|
||||
$query->where('status', $status);
|
||||
}
|
||||
if (($filters['follow_up'] ?? null) === 'overdue') {
|
||||
$query->whereNotNull('next_action_due_at')->where('next_action_due_at', '<', now())
|
||||
->whereNotIn('status', ['refused', 'converted', 'cancelled', 'closed']);
|
||||
} elseif (($filters['follow_up'] ?? null) === 'upcoming') {
|
||||
$query->whereNotNull('next_action_due_at')->where('next_action_due_at', '>=', now())
|
||||
->whereNotIn('status', ['refused', 'converted', 'cancelled', 'closed']);
|
||||
} elseif (($filters['follow_up'] ?? null) === 'unassigned') {
|
||||
$query->whereNull('assigned_to')->whereNotIn('status', ['refused', 'converted', 'cancelled', 'closed']);
|
||||
}
|
||||
|
||||
return Inertia::render('management/interests', [
|
||||
'requests' => $query->orderByDesc('id')->paginate(20)->withQueryString(),
|
||||
@@ -69,31 +84,94 @@ class PortalManagementController extends Controller
|
||||
|
||||
public function interest(InterestRequest $interest): Response
|
||||
{
|
||||
$history = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)
|
||||
->orderByDesc('created_at')->limit(50)->get(['from_status', 'to_status', 'actor_id', 'reason', 'created_at'])
|
||||
->map(function ($row) {
|
||||
$row->note = $row->reason ? Crypt::decryptString($row->reason) : null;
|
||||
unset($row->reason);
|
||||
|
||||
return $row;
|
||||
});
|
||||
$consents = DB::table('consents')->where('interest_request_id', $interest->id)
|
||||
->orderBy('created_at')->get(['purpose', 'policy_version', 'status', 'granted_at', 'withdrawn_at']);
|
||||
|
||||
return Inertia::render('management/interest', [
|
||||
'interest' => $interest->only([
|
||||
'id', 'reference', 'full_name', 'email', 'phone', 'investor_type', 'country',
|
||||
'sector_interest', 'opportunity_reference', 'investment_range', 'message',
|
||||
'privacy_consent', 'consented_at', 'status', 'created_at', 'reviewed_at', 'reviewed_by', 'metadata',
|
||||
'existing_business_id', 'modality', 'assigned_to', 'next_action', 'next_action_due_at',
|
||||
]),
|
||||
'history' => $history,
|
||||
'consents' => $consents,
|
||||
'assignees' => $this->interestAssignees()->get(['id', 'name']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function review(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||
public function review(Request $request, InterestRequest $interest, InterestWorkflow $workflow): RedirectResponse|JsonResponse
|
||||
{
|
||||
$validated = $request->validate(['status' => ['required', Rule::in(self::STATES)]]);
|
||||
DB::transaction(function () use ($request, $interest, $validated) {
|
||||
$locked = InterestRequest::whereKey($interest->id)->lockForUpdate()->firstOrFail();
|
||||
$changed = $locked->status !== $validated['status'];
|
||||
PortalAudit::save($locked, [
|
||||
...$validated, 'reviewed_at' => now(), 'reviewed_by' => $request->user()->id,
|
||||
], $request->user()->id);
|
||||
$submission = InvestmentSubmission::where('interest_request_id', $interest->id)->first();
|
||||
if ($changed && $submission) {
|
||||
app(InvestmentWorkspace::class)->notify($submission->user_id, $submission, 'status', (string) Str::uuid(), ['status' => $validated['status']]);
|
||||
$validated = $request->validate([
|
||||
'status' => ['required', Rule::in(self::STATES)],
|
||||
'note' => ['nullable', 'string', 'min:10', 'max:2000'],
|
||||
'next_action' => ['nullable', 'required_with:next_action_due_at', 'string', 'max:180'],
|
||||
'next_action_due_at' => ['nullable', 'required_with:next_action', 'date', 'after_or_equal:today'],
|
||||
'assigned_to' => ['nullable', 'integer', Rule::in($this->interestAssignees()->pluck('id'))],
|
||||
]);
|
||||
$before = $interest->status;
|
||||
$updated = $workflow->transition($request->user(), $interest, $validated['status'], $validated['note'] ?? null,
|
||||
$validated['next_action'] ?? null, $validated['next_action_due_at'] ?? null, isset($validated['assigned_to']) ? (int) $validated['assigned_to'] : null,
|
||||
$request->exists('assigned_to'), $request->exists('next_action') || $request->exists('next_action_due_at'));
|
||||
PortalAudit::save($updated, ['status' => $updated->status, 'reviewed_at' => $updated->reviewed_at, 'reviewed_by' => $updated->reviewed_by], $request->user()->id);
|
||||
$submission = InvestmentSubmission::where('interest_request_id', $interest->id)->first();
|
||||
if ($before !== $updated->status && $submission) {
|
||||
app(InvestmentWorkspace::class)->notify($submission->user_id, $submission, 'status', (string) Str::uuid(), ['status' => $updated->status]);
|
||||
}
|
||||
|
||||
return $request->expectsJson() ? response()->json(['reference' => $updated->reference, 'status' => $updated->status]) : back()->with('success', 'Estado do pedido actualizado.');
|
||||
}
|
||||
|
||||
public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||
DB::transaction(function () use ($request, $interest, $data) {
|
||||
$consent = DB::table('consents')->where('interest_request_id', $interest->id)
|
||||
->where('purpose', 'share_contact_with_proponent')->where('status', 'granted')->lockForUpdate()->first();
|
||||
if (! $consent) {
|
||||
return;
|
||||
}
|
||||
DB::table('consents')->where('id', $consent->id)->update(['status' => 'withdrawn', 'withdrawn_at' => now(), 'updated_at' => now()]);
|
||||
$correlationId = (string) Str::uuid();
|
||||
DB::table('business_workflow_transitions')->insert([
|
||||
'id' => (string) Str::uuid(), 'interest_request_id' => $interest->id,
|
||||
'from_status' => $interest->status, 'to_status' => $interest->status,
|
||||
'actor_id' => $request->user()->id, 'reason' => Crypt::encryptString($data['reason']),
|
||||
'correlation_id' => $correlationId,
|
||||
'metadata' => json_encode(['source' => 'management-interest', 'action' => 'consent_withdrawn',
|
||||
'purpose' => 'share_contact_with_proponent'], JSON_THROW_ON_ERROR),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
DB::table('outbox_events')->insertOrIgnore([
|
||||
'source_system' => 'portal-intake', 'external_id' => 'InterestConsentWithdrawn:'.$consent->id,
|
||||
'aggregate_type' => 'interest_consent', 'aggregate_id' => $consent->id,
|
||||
'event_type' => 'InterestConsentWithdrawn', 'data_classification' => 'confidential',
|
||||
'correlation_id' => $correlationId, 'status' => 'pending',
|
||||
'payload' => json_encode(['schema_version' => 1, 'consent_id' => $consent->id,
|
||||
'interest_id' => $interest->integration_id, 'purpose' => 'share_contact_with_proponent'], JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
});
|
||||
|
||||
return $request->expectsJson() ? response()->json(['reference' => $interest->reference, 'status' => $validated['status']]) : back()->with('success', 'Estado do pedido actualizado.');
|
||||
return $request->expectsJson() ? response()->json(['reference' => $interest->reference, 'sharing_consent' => 'withdrawn'])
|
||||
: back()->with('success', 'Consentimento de partilha revogado.');
|
||||
}
|
||||
|
||||
private function interestAssignees(): Builder
|
||||
{
|
||||
$emails = array_unique(array_merge(config('portal.managers', []), ...array_map(
|
||||
fn (string $designation) => config('existing-business.'.$designation, []),
|
||||
['triagers', 'reviewers', 'approvers_l1', 'approvers_l2', 'publishers'],
|
||||
)));
|
||||
|
||||
return User::query()->whereNotNull('email_verified_at')->whereIn(DB::raw('lower(email)'), $emails)->orderBy('name');
|
||||
}
|
||||
|
||||
public function catalog(Request $request, string $resource): Response
|
||||
@@ -139,10 +217,12 @@ class PortalManagementController extends Controller
|
||||
public function edit(string $resource, ?int $id = null): Response
|
||||
{
|
||||
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
|
||||
$record = $id ? $model::findOrFail($id) : null;
|
||||
|
||||
return Inertia::render('management/editor', [
|
||||
'resource' => $resource,
|
||||
'record' => $id ? $model::findOrFail($id) : null,
|
||||
'record' => $record,
|
||||
'territoryPath' => $record instanceof Opportunity ? app(InvestmentGeography::class)->path($record->primary_territory_id, true) : [],
|
||||
'sectors' => Sector::orderBy('name')->get(['id', 'name']),
|
||||
]);
|
||||
}
|
||||
@@ -177,6 +257,12 @@ class PortalManagementController extends Controller
|
||||
'status' => ['required', Rule::in(['draft', 'published', 'archived'])],
|
||||
'is_featured' => ['required', 'boolean'],
|
||||
];
|
||||
if ($resource === 'opportunities') {
|
||||
foreach (InvestmentGeography::FIELDS as $field => $type) {
|
||||
$rules[$field] = ['nullable', 'uuid'];
|
||||
}
|
||||
$rules['territory_version'] = [$id && $request->hasAny(array_keys(InvestmentGeography::FIELDS)) ? 'required' : 'nullable', 'integer', 'min:0'];
|
||||
}
|
||||
$data = $request->validate($rules);
|
||||
if ($resource === 'opportunities' && $data['status'] === 'published' && $record->exists
|
||||
&& Schema::hasTable('education_investment_proposals')
|
||||
@@ -191,7 +277,24 @@ class PortalManagementController extends Controller
|
||||
$data['maturity_label'] = $labels[$data['maturity_level'] ?? 0] ?? null;
|
||||
$data['published_at'] = $data['status'] === 'published' ? ($record->published_at ?? now()) : null;
|
||||
}
|
||||
PortalAudit::save($record, $data, $request->user()->id);
|
||||
DB::transaction(function () use ($record, $data, $request, $resource) {
|
||||
if ($resource === 'opportunities' && $request->hasAny(array_keys(InvestmentGeography::FIELDS))) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
|
||||
if ($record->exists) {
|
||||
$current = Opportunity::whereKey($record->id)->lockForUpdate()->firstOrFail();
|
||||
abort_unless((int) $current->territory_version === (int) $data['territory_version'], 409, 'Localização alterada. Recarregue a ficha.');
|
||||
}
|
||||
$path = app(InvestmentGeography::class)->selection($data, true);
|
||||
$data = array_diff_key($data, InvestmentGeography::FIELDS);
|
||||
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
|
||||
$data['territory_version'] = (int) ($data['territory_version'] ?? 0) + 1;
|
||||
$data['province'] = $path[0]->name ?? null;
|
||||
$data['district'] = $path[1]->name ?? null;
|
||||
} else {
|
||||
unset($data['territory_version']);
|
||||
}
|
||||
PortalAudit::save($record, $data, $request->user()->id);
|
||||
});
|
||||
|
||||
return redirect('/management/'.$resource)->with('success', 'Registo guardado.');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Resources\PublicBusinessOpportunityResource;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class PublicBusinessOpportunityController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response|JsonResponse
|
||||
{
|
||||
$filters = $request->validate([
|
||||
'q' => ['nullable', 'string', 'max:120'],
|
||||
'sector' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
]);
|
||||
|
||||
$query = $this->publishedQuery();
|
||||
if (! empty($filters['q'])) {
|
||||
$term = trim($filters['q']);
|
||||
$query->where(fn (Builder $builder) => $builder->whereLike('existing_businesses.public_title', '%'.$term.'%')
|
||||
->orWhereLike('existing_businesses.activity_code', '%'.$term.'%')
|
||||
->orWhereLike('existing_businesses.objective', '%'.$term.'%'));
|
||||
}
|
||||
if (! empty($filters['sector'])) {
|
||||
$query->where('existing_businesses.sector_id', $filters['sector']);
|
||||
}
|
||||
|
||||
$results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->withQueryString());
|
||||
if ($request->expectsJson()) {
|
||||
return $results->response();
|
||||
}
|
||||
|
||||
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters]);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $slug): Response|JsonResponse
|
||||
{
|
||||
$record = $this->publishedQuery()->where('existing_businesses.public_slug', $slug)->firstOrFail();
|
||||
$resource = new PublicBusinessOpportunityResource($record);
|
||||
if ($request->expectsJson()) {
|
||||
return $resource->response();
|
||||
}
|
||||
|
||||
return Inertia::render('investment/business-opportunity', ['record' => $resource]);
|
||||
}
|
||||
|
||||
public function interest(Request $request, string $slug): Response
|
||||
{
|
||||
$record = $this->publishedQuery()->where('existing_businesses.public_slug', $slug)->firstOrFail();
|
||||
|
||||
return Inertia::render('investment/business-interest', [
|
||||
'record' => (new PublicBusinessOpportunityResource($record))->resolve($request),
|
||||
'modalities' => ExistingBusinessDrafts::MODALITIES,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return Builder<ExistingBusiness> */
|
||||
private function publishedQuery(): Builder
|
||||
{
|
||||
$publicLocations = DB::table('existing_business_locations as locations')
|
||||
->leftJoin('geo_locations as province', 'province.id', '=', 'locations.province_id')
|
||||
->leftJoin('geo_locations as district', 'district.id', '=', 'locations.district_id')
|
||||
->leftJoin('geo_locations as locality', 'locality.id', '=', 'locations.locality_id')
|
||||
->where('locations.is_public', true)->where('locations.is_primary', true)
|
||||
->whereNull('province.deleted_at')->whereNull('district.deleted_at')->whereNull('locality.deleted_at')
|
||||
->select('locations.existing_business_id', 'province.name as province')
|
||||
->selectRaw("CASE WHEN locations.precision_level IN ('district','admin_post','locality','exact') THEN district.name ELSE NULL END AS district")
|
||||
->selectRaw('NULL::text AS locality');
|
||||
|
||||
return ExistingBusiness::query()->published()->with('sector:id,name,slug')
|
||||
->leftJoinSub($publicLocations, 'public_location', 'public_location.existing_business_id', '=', 'existing_businesses.id')
|
||||
->select(['existing_businesses.id', 'existing_businesses.public_slug', 'existing_businesses.public_title',
|
||||
'existing_businesses.activity_code', 'existing_businesses.stage', 'existing_businesses.objective',
|
||||
'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max',
|
||||
'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id',
|
||||
'public_location.province', 'public_location.district', 'public_location.locality']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\InvestmentGeography;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PublicGeographyController extends Controller
|
||||
{
|
||||
public function options(Request $request, InvestmentGeography $geography): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$query = $geography->publicReferences()->where('location_type', $data['type']);
|
||||
if ($data['type'] !== 'province') {
|
||||
$parentType = ['district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$data['type']];
|
||||
$parent = $geography->publicReferences()->where('id', $data['parent_id'] ?? '00000000-0000-0000-0000-000000000000')->where('location_type', $parentType)->value('id');
|
||||
$query->where('parent_id', $parent ?? '00000000-0000-0000-0000-000000000000');
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$term = '%'.addcslashes($data['q'], '%_\\').'%';
|
||||
$query->where(fn ($q) => $q->whereRaw('name ILIKE ?', [$term])->orWhereRaw('code ILIKE ?', [$term])->orWhereRaw('source_code ILIKE ?', [$term]));
|
||||
}
|
||||
|
||||
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code']));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\TerritorialRegistry;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class TerritorialRegistryController extends Controller
|
||||
{
|
||||
public function sources(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]);
|
||||
|
||||
return response()->json(DB::table('geo_sources')->orderBy('id')->cursorPaginate($data['limit'] ?? 20)->withQueryString());
|
||||
}
|
||||
|
||||
public function drafts(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]);
|
||||
|
||||
return response()->json(DB::table('geo_locations as g')->join('geo_territory_profiles as p', 'p.geo_location_id', '=', 'g.id')->whereNull('g.deleted_at')
|
||||
->select(['g.id', 'g.name', 'g.code', 'g.location_type', 'g.parent_id', 'g.version_no', 'p.source_id', 'p.status', 'p.valid_from', 'p.valid_to', 'p.editor_id', 'p.reviewer_id', 'p.publisher_id'])
|
||||
->orderBy('g.id')->cursorPaginate($data['limit'] ?? 20)->withQueryString());
|
||||
}
|
||||
|
||||
public function index(Request $request, TerritorialRegistry $registry, ?string $collection = null): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['q' => ['nullable', 'string', 'max:150'], 'cursor' => ['nullable', 'string', 'max:512'],
|
||||
'limit' => ['nullable', 'integer', 'between:1,100'], 'parent_id' => ['nullable', 'uuid'],
|
||||
'country_id' => ['nullable', 'uuid'], 'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'],
|
||||
'include_geometry' => ['nullable', 'in:0,false'], 'bbox' => ['prohibited'], 'near' => ['prohibited'], 'radius' => ['prohibited']]);
|
||||
$types = ['countries' => 'country', 'provinces' => 'province', 'districts' => 'district', 'admin-posts' => 'admin_post', 'localities' => 'locality'];
|
||||
$query = $registry->published()->select(['g.id', 'g.name', 'g.code', 'g.location_type', 'g.parent_id', 'g.version_no', 'p.valid_from', 'p.valid_to']);
|
||||
if (isset($types[$collection])) {
|
||||
$query->where('g.location_type', $types[$collection]);
|
||||
}
|
||||
if (! empty($data['q'])) {
|
||||
$term = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $data['q']).'%';
|
||||
$query->where(fn ($q) => $q->where('g.name', 'ilike', $term)->orWhere('g.code', 'ilike', $term)
|
||||
->orWhereExists(fn ($n) => $n->selectRaw('1')->from('geo_names')->whereColumn('geo_location_id', 'g.id')->where('name', 'ilike', $term)));
|
||||
}
|
||||
foreach (['parent_id', 'country_id', 'province_id', 'district_id', 'admin_post_id'] as $key) {
|
||||
if (! empty($data[$key])) {
|
||||
if ($key === 'parent_id') {
|
||||
$query->where('g.parent_id', $data[$key]);
|
||||
} else {
|
||||
$type = ['country_id' => 'country', 'province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post'][$key];
|
||||
$query->whereRaw('EXISTS (WITH RECURSIVE a AS (SELECT id,parent_id,location_type,1 AS depth FROM geo_locations WHERE id=g.parent_id UNION ALL SELECT l.id,l.parent_id,l.location_type,a.depth+1 FROM geo_locations l JOIN a ON l.id=a.parent_id WHERE a.depth<5) SELECT 1 FROM a WHERE id=? AND location_type=?)', [$data[$key], $type]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json($query->orderBy('g.id')->cursorPaginate($data['limit'] ?? 20)->withQueryString());
|
||||
}
|
||||
|
||||
public function show(Request $request, TerritorialRegistry $registry, string $type, string $id): JsonResponse
|
||||
{
|
||||
abort_unless(array_key_exists($type, TerritorialRegistry::PARENTS), 404);
|
||||
$row = $registry->published()->where('g.id', $id)->where('g.location_type', $type)
|
||||
->first(['g.id', 'g.name', 'g.code', 'g.parent_id', 'g.location_type', 'g.version_no', 'p.valid_from', 'p.valid_to', 'p.capital_territory_id']);
|
||||
abort_unless($row !== null, 404);
|
||||
// An unapproved capital must not leak through a published province.
|
||||
if ($row->capital_territory_id && ! $registry->published()->where('g.id', $row->capital_territory_id)->exists()) {
|
||||
$row->capital_territory_id = null;
|
||||
}
|
||||
|
||||
return response()->json(['territory' => $row, 'names' => DB::table('geo_names')->where('geo_location_id', $id)->get(['language', 'name', 'official'])]);
|
||||
}
|
||||
|
||||
public function save(Request $request, TerritorialRegistry $registry, ?string $id = null): JsonResponse
|
||||
{
|
||||
$id = $registry->save($request->user(), $request->all(), $id);
|
||||
|
||||
return response()->json(['id' => $id, 'status' => 'draft', 'version_no' => DB::table('geo_locations')->where('id', $id)->value('version_no')]);
|
||||
}
|
||||
|
||||
public function source(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['name' => ['required', 'string', 'max:255'], 'responsible_entity' => ['nullable', 'string', 'max:255'],
|
||||
'reference' => ['required', 'string', 'min:10', 'max:2000'], 'license' => ['nullable', 'string', 'max:2000'],
|
||||
'checksum' => ['required', 'regex:/^[0-9a-f]{64}$/'], 'source_version' => ['required', 'string', 'max:255'],
|
||||
'collected_at' => ['required', 'date_format:Y-m-d', 'before_or_equal:today'], 'original_crs' => ['nullable', 'string', 'max:255']]);
|
||||
$id = (string) Str::uuid();
|
||||
DB::transaction(function () use ($data, $id, $request) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, hashtext(?))', [$data['checksum'].':'.$data['source_version']]);
|
||||
abort_if(DB::table('geo_sources')->where('checksum', $data['checksum'])->where('source_version', $data['source_version'])->exists(), 422, 'Fonte e versão já registadas.');
|
||||
DB::table('geo_sources')->insert([...$data, 'id' => $id, 'editor_id' => $request->user()->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
});
|
||||
|
||||
return response()->json(['id' => $id, 'status' => 'pending'], 201);
|
||||
}
|
||||
|
||||
public function transition(Request $request, TerritorialRegistry $registry, string $id): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['action' => ['required', 'in:pending_review,approved,published,rejected,archived'],
|
||||
'version_no' => ['required', 'integer', 'min:1'], 'reason' => ['required', 'string', 'min:10', 'max:1000']]);
|
||||
|
||||
return DB::transaction(function () use ($request, $registry, $id, $data) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
|
||||
$location = DB::table('geo_locations')->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
|
||||
$profile = DB::table('geo_territory_profiles')->where('geo_location_id', $id)->lockForUpdate()->first();
|
||||
abort_unless($location && $profile, 404);
|
||||
abort_unless($location->version_no === $data['version_no'], 409);
|
||||
$from = ['pending_review' => ['draft', 'rejected'], 'approved' => ['pending_review'], 'published' => ['approved'],
|
||||
'rejected' => ['pending_review'], 'archived' => ['draft', 'pending_review', 'approved', 'published', 'rejected']];
|
||||
abort_unless(in_array($profile->status, $from[$data['action']], true), 409);
|
||||
$actor = $request->user()->id;
|
||||
$changes = ['status' => $data['action'], 'updated_at' => now()];
|
||||
if ($data['action'] === 'pending_review') {
|
||||
abort_unless($profile->editor_id === $actor, 403);
|
||||
}
|
||||
if (in_array($data['action'], ['approved', 'rejected'], true)) {
|
||||
abort_if($profile->editor_id === $actor, 403, 'Revisão independente obrigatória.');
|
||||
$changes['reviewer_id'] = $actor;
|
||||
}
|
||||
if ($data['action'] === 'published') {
|
||||
abort_if(in_array($actor, [$profile->editor_id, $profile->reviewer_id], true), 403, 'Publicação exige terceiro interveniente.');
|
||||
abort_unless(DB::table('geo_sources')->where('id', $profile->source_id)->where('status', 'approved')->exists(), 422, 'Fonte não aprovada.');
|
||||
abort_if($profile->valid_from > today()->toDateString() || ($profile->valid_to && $profile->valid_to < today()->toDateString()), 422, 'Vigência inválida.');
|
||||
abort_if($location->parent_id && ! $registry->published()->where('g.id', $location->parent_id)->exists(), 422, 'Ascendente não publicado.');
|
||||
$changes['publisher_id'] = $actor;
|
||||
}
|
||||
DB::table('geo_territory_profiles')->where('geo_location_id', $id)->update($changes);
|
||||
$version = $location->version_no + 1;
|
||||
DB::table('geo_locations')->where('id', $id)->update(['version_no' => $version, 'data_classification' => $data['action'] === 'published' ? 'public' : 'internal']);
|
||||
$registry->snapshot($id, $version, $request->user(), $data['reason']);
|
||||
|
||||
return response()->json(['id' => $id, 'status' => $data['action'], 'version_no' => $version]);
|
||||
});
|
||||
}
|
||||
|
||||
public function sourceTransition(Request $request, string $id): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['action' => ['required', 'in:approved,revoked'], 'approval_reference' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||
|
||||
return DB::transaction(function () use ($request, $id, $data) {
|
||||
$source = DB::table('geo_sources')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($source !== null, 404);
|
||||
if ($data['action'] === 'approved') {
|
||||
abort_unless($source->status === 'pending', 409);
|
||||
abort_if($source->editor_id === $request->user()->id, 403);
|
||||
abort_unless($source->responsible_entity && $source->license, 422, 'Entidade e licença em falta.');
|
||||
}
|
||||
DB::table('geo_sources')->where('id', $id)->update(['status' => $data['action'], 'reviewer_id' => $request->user()->id,
|
||||
'approval_reference' => $data['approval_reference'], 'updated_at' => now()]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'territorial-registry', 'entity_type' => 'geo_sources', 'entity_id' => $id,
|
||||
'actor_user_id' => $request->user()->id, 'action' => $data['action'], 'after_data' => json_encode(['status' => $data['action']], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return response()->json(['id' => $id, 'status' => $data['action']]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CorrelationId
|
||||
{
|
||||
/** @param Closure(Request): Response $next */
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$provided = $request->header('X-Correlation-ID');
|
||||
$correlationId = is_string($provided) && Str::isUuid($provided)
|
||||
? $provided
|
||||
: (string) Str::uuid();
|
||||
|
||||
if ($provided !== null && ! Str::isUuid($provided)) {
|
||||
return response()->json([
|
||||
'message' => 'O identificador de correlação deve ser um UUID válido.',
|
||||
'code' => 'invalid_correlation_id',
|
||||
'correlation_id' => $correlationId,
|
||||
], 422)->header('X-Correlation-ID', $correlationId);
|
||||
}
|
||||
|
||||
$request->attributes->set('correlation_id', $correlationId);
|
||||
$response = $next($request);
|
||||
$response->headers->set('X-Correlation-ID', $correlationId);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ExistingBusinessEnabled
|
||||
{
|
||||
/** @param Closure(Request): Response $next */
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
abort_unless(config('existing-business.enabled'), 404);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ class HandleInertiaRequests extends Middleware
|
||||
'name' => config('app.name'),
|
||||
'educationEnabled' => (bool) config('education.enabled', false),
|
||||
'aiEnabled' => (bool) config('investmoz_ai.enabled', false),
|
||||
'existingBusinessEnabled' => (bool) config('existing-business.enabled', false),
|
||||
'flash' => ['success' => fn () => $request->session()->get('success')],
|
||||
'auth' => [
|
||||
'user' => $request->user(),
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class PreserveFormFeedback
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
// Auxiliary JSON reads must not consume feedback intended for the next Inertia page.
|
||||
if ($request->isMethod('GET') && $request->expectsJson() && ! $request->header('X-Inertia') && $request->hasSession()) {
|
||||
$request->session()->keep(['errors', '_old_input', 'success']);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
class TerritorialRequest
|
||||
{
|
||||
/** @param Closure(Request): Response $next */
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$correlation = (string) Str::uuid();
|
||||
try {
|
||||
abort_unless(config('territorial.enabled'), 404);
|
||||
if ($request->isMethodSafe()) {
|
||||
$response = $next($request);
|
||||
} else {
|
||||
abort_unless($request->user()->can('manage-portal') && $request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403);
|
||||
$role = $request->is('*/transitions') ? match ($request->input('action')) {
|
||||
'approved', 'rejected' => 'reviewers', 'published', 'archived', 'revoked' => 'publishers', default => 'editors',
|
||||
} : 'editors';
|
||||
abort_unless(in_array(strtolower($request->user()->email), config('territorial.'.$role, []), true), 403, 'Função editorial não atribuída.');
|
||||
$key = $request->header('Idempotency-Key', '');
|
||||
abort_unless(Str::isUuid($key), 422, 'Idempotency-Key UUID obrigatório.');
|
||||
$scope = $request->method().':'.$request->path();
|
||||
$actor = $request->user()->id;
|
||||
$hash = hash('sha256', json_encode($request->all(), JSON_THROW_ON_ERROR));
|
||||
$response = DB::transaction(function () use ($request, $next, $key, $scope, $actor, $hash) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, hashtext(?))', [$actor.':'.$key.':'.$scope]);
|
||||
$query = DB::table('geo_write_receipts')->where('actor_id', $actor)->where('idempotency_key', $key)->where('scope', $scope);
|
||||
$existing = $query->first();
|
||||
if ($existing) {
|
||||
abort_unless(hash_equals($existing->request_hash, $hash), 409, 'Chave reutilizada com conteúdo diferente.');
|
||||
|
||||
return response(Crypt::decryptString($existing->response), $existing->http_status, ['Content-Type' => 'application/json']);
|
||||
}
|
||||
$result = $next($request);
|
||||
if ($result->isSuccessful()) {
|
||||
$body = $result->getContent();
|
||||
if (! is_string($body)) {
|
||||
throw new \RuntimeException('Expected JSON response body.');
|
||||
}
|
||||
DB::table('geo_write_receipts')->insert(['id' => (string) Str::uuid(), 'actor_id' => $actor, 'idempotency_key' => $key,
|
||||
'scope' => $scope, 'request_hash' => $hash, 'response' => Crypt::encryptString($body), 'http_status' => $result->getStatusCode()]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
} catch (ValidationException $exception) {
|
||||
$response = response()->json(['type' => 'about:blank', 'title' => 'Dados inválidos', 'status' => 422, 'errors' => $exception->errors(), 'correlation_id' => $correlation], 422, ['Content-Type' => 'application/problem+json']);
|
||||
} catch (HttpExceptionInterface $exception) {
|
||||
$status = $exception->getStatusCode();
|
||||
$response = response()->json(['type' => 'about:blank', 'title' => Response::$statusTexts[$status] ?? 'Request failed', 'status' => $status,
|
||||
'detail' => $exception->getMessage(), 'correlation_id' => $correlation], $status, ['Content-Type' => 'application/problem+json']);
|
||||
}
|
||||
$response->headers->set('X-Correlation-ID', $correlation);
|
||||
$response->headers->set('Cache-Control', 'private, no-store');
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Services\ExistingBusinessDrafts;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class StoreInterestRequestRequest extends FormRequest
|
||||
{
|
||||
@@ -36,12 +38,28 @@ class StoreInterestRequestRequest extends FormRequest
|
||||
->where('status', 'published')->whereNotNull('published_at')
|
||||
->where('published_at', '<=', now())->whereNull('deleted_at')),
|
||||
])],
|
||||
'existingBusinessId' => ['nullable', 'uuid', ...($knownKey ? [] : [
|
||||
Rule::exists('existing_businesses', 'id')->where(fn ($query) => $query
|
||||
->where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now())->whereNull('deleted_at')),
|
||||
])],
|
||||
'modality' => ['nullable', 'required_with:existingBusinessId', 'string', 'max:50', Rule::in(ExistingBusinessDrafts::MODALITIES)],
|
||||
'investmentRange' => ['nullable', 'string', 'max:80'],
|
||||
'message' => ['required', 'string', 'min:20', 'max:2000'],
|
||||
'privacyConsent' => ['required', 'accepted'],
|
||||
'shareWithProponent' => ['sometimes', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return list<callable(Validator): void> */
|
||||
public function after(): array
|
||||
{
|
||||
return [function (Validator $validator): void {
|
||||
if ($this->filled('existingBusinessId') && $this->filled('opportunityReference')) {
|
||||
$validator->errors()->add('existingBusinessId', 'Seleccione apenas uma oportunidade.');
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class StoreSimulationFormDraftRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
public function rules(): array
|
||||
{
|
||||
$personal = [
|
||||
'person_type', 'investor_origin', 'tax_residency_country', 'entity_stage', 'legal_form', 'nuit',
|
||||
'investor_profile_id', 'profile_confirmation', 'legal_name', 'commercial_name', 'registration_number',
|
||||
'representative_name', 'representative_capacity', 'email', 'phone', 'address', 'contact_country', 'selection_labels',
|
||||
'contact_province', 'contact_district', 'preferred_channel',
|
||||
];
|
||||
$economic = [
|
||||
'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'selection_labels', 'project_type',
|
||||
'project_type_other', 'sector_id', 'activity_id', 'products_services', 'maturity_stage', 'expected_start_date',
|
||||
'project_duration_years', 'existing_project_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id',
|
||||
'site_known', 'latitude', 'longitude', 'area_required', 'area_unit', 'special_zone_id', 'land_status',
|
||||
'infrastructure_needs', 'currency', 'total_investment', 'own_capital', 'domestic_debt', 'foreign_debt',
|
||||
'grants', 'secured_amount', 'sought_amount', 'annual_revenue', 'annual_operating_costs', 'expected_profit',
|
||||
'financing_term_months', 'funds_origin_countries', 'direct_jobs', 'indirect_jobs', 'national_jobs',
|
||||
'foreign_jobs', 'skills_needed', 'local_content_percentage', 'exports_value', 'import_substitution_value',
|
||||
'environmental_category', 'community_benefits', 'tax_calculation', 'base', 'rate', 'reduction',
|
||||
'sales_taxable', 'sales_exempt', 'sales_zero_rate', 'exports', 'deductible_costs', 'non_deductible_costs',
|
||||
'carried_losses', 'payroll', 'outbound_payments', 'imports', 'claimed_benefits', 'reference_date',
|
||||
'offer_or_demand', 'opportunity_type', 'opportunity_type_other', 'opportunity_description',
|
||||
'opportunity_value', 'opportunity_currency', 'opportunity_conditions', 'opportunity_deadline',
|
||||
'required_documents', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration', 'reuse_simulation',
|
||||
'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged',
|
||||
'final_declaration_name',
|
||||
];
|
||||
|
||||
$rules = [
|
||||
'personal_snapshot' => ['required', 'array:'.implode(',', $personal)],
|
||||
'economic_snapshot' => ['required', 'array:'.implode(',', $economic)],
|
||||
'economic_snapshot.purpose' => ['required', 'in:simulate_only,own_investment,seek_investor,seek_partner,present_opportunity,request_facilitation'],
|
||||
'economic_snapshot.manifestation_type' => ['nullable', 'in:investment,business'],
|
||||
'economic_snapshot.preferred_language' => ['nullable', 'in:pt-MZ,en'],
|
||||
'economic_snapshot.project_type' => ['nullable', 'in:new,expansion,acquisition,partnership,concession,supplier,buyer,other'],
|
||||
'economic_snapshot.maturity_stage' => ['nullable', 'in:idea,concept,pre_feasibility,feasibility,financing,implementation,operation'],
|
||||
'economic_snapshot.land_status' => ['nullable', 'in:owned,duat,leased,requested,unknown'],
|
||||
'economic_snapshot.offer_or_demand' => ['nullable', 'in:offer,demand,both'],
|
||||
'economic_snapshot.opportunity_type' => ['nullable', 'in:capital,partner,buyer,supplier,land,technology,licence,services,other'],
|
||||
'economic_snapshot.confidentiality' => ['nullable', 'in:public,registered_users,restricted,confidential'],
|
||||
'economic_snapshot.site_known' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.tax_calculation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.publish_requested' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.terms_accepted' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.truth_declaration' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.reuse_simulation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.contact_authorisation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.publication_authorisation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.public_fields_confirmation' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.validation_acknowledged' => ['nullable', 'in:yes,no'],
|
||||
'economic_snapshot.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||
'economic_snapshot.opportunity_currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
|
||||
'economic_snapshot.rate' => ['nullable', 'numeric', 'between:0,100'],
|
||||
'economic_snapshot.reduction' => ['nullable', 'numeric', 'between:0,100'],
|
||||
'economic_snapshot.local_content_percentage' => ['nullable', 'numeric', 'between:0,100'],
|
||||
'economic_snapshot.latitude' => ['nullable', 'numeric', 'between:-90,90'],
|
||||
'economic_snapshot.longitude' => ['nullable', 'numeric', 'between:-180,180'],
|
||||
'economic_snapshot.expected_start_date' => ['nullable', 'date'],
|
||||
'economic_snapshot.opportunity_deadline' => ['nullable', 'date'],
|
||||
'economic_snapshot.reference_date' => ['nullable', 'date'],
|
||||
'economic_snapshot.*' => ['nullable'],
|
||||
];
|
||||
|
||||
foreach (['base', 'area_required', 'total_investment', 'own_capital', 'domestic_debt', 'foreign_debt', 'grants',
|
||||
'secured_amount', 'sought_amount', 'annual_revenue', 'annual_operating_costs', 'expected_profit', 'exports_value',
|
||||
'import_substitution_value', 'sales_taxable', 'sales_exempt', 'sales_zero_rate', 'exports', 'deductible_costs',
|
||||
'non_deductible_costs', 'carried_losses', 'opportunity_value'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'numeric', 'min:0'];
|
||||
}
|
||||
foreach (['direct_jobs', 'indirect_jobs', 'national_jobs', 'foreign_jobs', 'financing_term_months', 'project_duration_years'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'integer', 'min:0'];
|
||||
}
|
||||
foreach (['infrastructure_needs', 'funds_origin_countries', 'required_documents'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'array', 'max:100'];
|
||||
$rules['economic_snapshot.'.$field.'.*'] = ['nullable', 'string', 'max:3000'];
|
||||
}
|
||||
$rules['economic_snapshot.infrastructure_needs.*'] = ['nullable', 'in:energia,água,estrada,porto,ferrovia,telecomunicações,armazenamento'];
|
||||
$rules['economic_snapshot.required_documents.*'] = ['nullable', 'in:identity_document,company_registration,nuit_certificate,company_profile,business_plan,feasibility_study,proof_of_funds,special_zone_certificate,licence,site_map'];
|
||||
foreach (['skills_needed', 'payroll', 'outbound_payments', 'imports', 'claimed_benefits', 'opportunity_conditions'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000'];
|
||||
}
|
||||
$rules['economic_snapshot.selection_labels'] = ['nullable', 'array'];
|
||||
foreach (['project_summary', 'opportunity_description', 'products_services', 'community_benefits'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:10000'];
|
||||
}
|
||||
$rules['personal_snapshot.email'] = ['nullable', 'email:rfc', 'max:254'];
|
||||
$rules['personal_snapshot.nuit'] = ['nullable', 'string', 'max:32'];
|
||||
$rules['personal_snapshot.investor_profile_id'] = ['nullable', 'uuid'];
|
||||
$rules['personal_snapshot.profile_confirmation'] = ['nullable', 'boolean'];
|
||||
$rules['personal_snapshot.selection_labels'] = ['nullable', 'array'];
|
||||
$rules['personal_snapshot.person_type'] = ['nullable', 'in:singular,collective,sole_trader,consortium'];
|
||||
$rules['personal_snapshot.investor_origin'] = ['nullable', 'in:national,foreign,mixed'];
|
||||
$rules['personal_snapshot.entity_stage'] = ['nullable', 'in:existing,being_formed'];
|
||||
$rules['economic_snapshot.sector_id'] = ['nullable', 'integer', 'exists:sectors,id'];
|
||||
$rules['economic_snapshot.activity_id'] = ['nullable', 'uuid', 'exists:economic_activities,id'];
|
||||
foreach (['existing_project_id', 'special_zone_id'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'string', 'max:100'];
|
||||
}
|
||||
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id'] as $field) {
|
||||
$rules['economic_snapshot.'.$field] = ['nullable', 'uuid', 'exists:geo_locations,id'];
|
||||
}
|
||||
foreach (['person_type', 'investor_origin', 'tax_residency_country', 'entity_stage', 'legal_form', 'commercial_name',
|
||||
'registration_number', 'representative_name', 'representative_capacity', 'phone', 'address', 'contact_country',
|
||||
'contact_province', 'contact_district', 'preferred_channel'] as $field) {
|
||||
$rules['personal_snapshot.'.$field] = ['nullable', 'string', 'max:3000'];
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator): void {
|
||||
$economic = $this->input('economic_snapshot', []);
|
||||
if (! is_array($economic)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$allowedLabels = [
|
||||
'economic_snapshot.selection_labels' => ['purpose', 'manifestation_type', 'preferred_language', 'project_type', 'sector_id', 'activity_id',
|
||||
'province_id', 'district_id', 'admin_post_id', 'locality_id', 'site_known', 'land_status', 'infrastructure_needs',
|
||||
'area_unit', 'required_documents', 'opportunity_currency',
|
||||
'currency', 'funds_origin_countries', 'environmental_category', 'tax_calculation', 'offer_or_demand',
|
||||
'opportunity_type', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration',
|
||||
'reuse_simulation', 'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged'],
|
||||
'personal_snapshot.selection_labels' => ['person_type', 'investor_origin', 'tax_residency_country', 'entity_stage', 'legal_form', 'preferred_channel'],
|
||||
];
|
||||
foreach ($allowedLabels as $path => $allowedFields) {
|
||||
$snapshot = str_starts_with($path, 'personal_') ? $this->input('personal_snapshot.selection_labels', []) : ($economic['selection_labels'] ?? []);
|
||||
foreach (is_array($snapshot) ? $snapshot : [] as $field => $label) {
|
||||
$labels = is_array($label) ? $label : [$label];
|
||||
if (! is_string($field) || ! in_array($field, $allowedFields, true) || count($labels) > 100
|
||||
|| collect($labels)->contains(fn ($value) => ! is_string($value) || mb_strlen($value) > 255)) {
|
||||
$validator->errors()->add($path, 'Os rótulos de selecção não são válidos.');
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($economic['activity_id'], $economic['sector_id'])) {
|
||||
$matchesSector = DB::table('economic_activities as a')
|
||||
->join('reference_catalog_versions as v', 'v.id', '=', 'a.catalog_version_id')
|
||||
->where('a.id', $economic['activity_id'])->where('a.sector_id', $economic['sector_id'])
|
||||
->where('a.status', 'published')->where('v.status', 'published')
|
||||
->whereDate('a.valid_from', '<=', today())
|
||||
->where(fn ($query) => $query->whereNull('a.valid_to')->orWhereDate('a.valid_to', '>', today()))->exists();
|
||||
if (! $matchesSector) {
|
||||
$validator->errors()->add('economic_snapshot.activity_id', 'A actividade não pertence ao sector seleccionado ou já não está publicada.');
|
||||
}
|
||||
} elseif (! empty($economic['activity_id'])) {
|
||||
$validator->errors()->add('economic_snapshot.sector_id', 'Seleccione o sector antes da actividade económica.');
|
||||
}
|
||||
|
||||
$parents = ['district_id' => ['province_id', 'district'], 'admin_post_id' => ['district_id', 'admin_post'], 'locality_id' => ['admin_post_id', 'locality']];
|
||||
foreach ($parents as $child => [$parentField, $type]) {
|
||||
if (empty($economic[$child])) {
|
||||
continue;
|
||||
}
|
||||
$parentType = ['district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'][$type];
|
||||
$valid = ! empty($economic[$parentField]) && DB::table('geo_locations as child')
|
||||
->join('geo_locations as parent', 'parent.id', '=', 'child.parent_id')
|
||||
->where('child.id', $economic[$child])->where('child.location_type', $type)
|
||||
->where('child.source_system', 'cartografia-workbook')->where('child.data_classification', 'public')->whereNull('child.deleted_at')
|
||||
->where('parent.id', $economic[$parentField])->where('parent.location_type', $parentType)
|
||||
->where('parent.source_system', 'cartografia-workbook')->where('parent.data_classification', 'public')->whereNull('parent.deleted_at')->exists();
|
||||
if (! $valid) {
|
||||
$validator->errors()->add('economic_snapshot.'.$child, 'Seleccione uma opção publicada dependente do nível territorial anterior.');
|
||||
}
|
||||
}
|
||||
|
||||
$financeKeys = ['total_investment', 'own_capital', 'domestic_debt', 'foreign_debt', 'grants'];
|
||||
if (collect($financeKeys)->every(fn (string $key) => array_key_exists($key, $economic) && $economic[$key] !== null && $economic[$key] !== '')) {
|
||||
$funding = (float) $economic['own_capital'] + (float) $economic['domestic_debt'] + (float) $economic['foreign_debt'] + (float) $economic['grants'];
|
||||
if (abs($funding - (float) $economic['total_investment']) > 0.01) {
|
||||
$validator->errors()->add('economic_snapshot.total_investment', 'A soma do capital, dívida e subvenções deve reconciliar com o investimento total.');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreSimulationRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'base' => ['required', 'numeric', 'min:0'],
|
||||
'rate' => ['required', 'numeric', 'between:0,100'],
|
||||
'reduction' => ['required', 'numeric', 'between:0,100'],
|
||||
'organization_id' => ['nullable', 'uuid', 'exists:organizations,id'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateSimulationScenarioRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'label' => ['required', 'string', 'min:1', 'max:100'],
|
||||
'base' => ['required', 'numeric', 'min:0'],
|
||||
'rate' => ['required', 'numeric', 'between:0,100'],
|
||||
'reduction' => ['required', 'numeric', 'between:0,100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class PublicBusinessOpportunityResource extends JsonResource
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'slug' => $this->public_slug,
|
||||
'title' => $this->public_title,
|
||||
'activity_code' => $this->activity_code,
|
||||
'stage' => $this->stage,
|
||||
'objective' => $this->objective,
|
||||
'currency' => $this->currency,
|
||||
'amount_min' => $this->amount_min,
|
||||
'amount_max' => $this->amount_max,
|
||||
'available_percentage' => $this->available_percentage,
|
||||
'published_at' => $this->published_at,
|
||||
'sector' => $this->whenLoaded('sector', fn () => $this->sector?->only(['name', 'slug'])),
|
||||
'province' => $this->province,
|
||||
'district' => $this->district,
|
||||
'locality' => $this->locality,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Services\Mne\LegacyBusinessRepository;
|
||||
use App\Services\Mne\MneBusinessRepository;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
final class CompareMneBusiness implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public int $tries = 1;
|
||||
|
||||
public function __construct(public string $businessId) {}
|
||||
|
||||
public function handle(LegacyBusinessRepository $legacy, MneBusinessRepository $canonical): void
|
||||
{
|
||||
$start = hrtime(true);
|
||||
try {
|
||||
$source = $legacy->find($this->businessId);
|
||||
$comparison = $canonical->comparison($this->businessId);
|
||||
$expected = $source->only(['code', 'modality', 'status', 'classification', 'version_no']);
|
||||
$outcome = $comparison === null ? 'unmapped' : ($expected == $comparison ? 'core_match' : 'divergence');
|
||||
} catch (\Throwable) {
|
||||
$outcome = 'comparison_error';
|
||||
}
|
||||
// No payloads, query parameters, identifiers or exception messages in telemetry.
|
||||
Log::info('mne.compatibility.shadow', ['outcome' => $outcome, 'latency_ms' => (hrtime(true) - $start) / 1000000]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Simulation;
|
||||
use App\Services\SimulationExecution;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class RunSimulation implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
|
||||
public int $timeout = 30;
|
||||
|
||||
public function __construct(public string $simulationId, public ?int $actorId, public ?string $tokenHash) {}
|
||||
|
||||
/** @return list<int> */
|
||||
public function backoff(): array
|
||||
{
|
||||
return [10, 60];
|
||||
}
|
||||
|
||||
public function handle(SimulationExecution $execution): void
|
||||
{
|
||||
$shouldRun = DB::transaction(function () use ($execution): bool {
|
||||
$execution->setContext($this->actorId, $this->tokenHash);
|
||||
$job = DB::table('simulation_jobs')->where('simulation_id', $this->simulationId)->where('job_type', 'execute')->lockForUpdate()->first();
|
||||
if (! $job || in_array($job->status, ['succeeded', 'failed'], true)) {
|
||||
return false;
|
||||
}
|
||||
DB::table('simulation_jobs')->where('id', $job->id)->update([
|
||||
'status' => 'running', 'attempts' => min(3, max((int) $job->attempts + 1, (int) $this->attempts())),
|
||||
'started_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return true;
|
||||
});
|
||||
if (! $shouldRun) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($execution): void {
|
||||
$execution->setContext($this->actorId, $this->tokenHash);
|
||||
$simulation = Simulation::whereNull('deleted_at')->lockForUpdate()->find($this->simulationId);
|
||||
if (! $simulation || $simulation->status === 'completed') {
|
||||
return;
|
||||
}
|
||||
$job = DB::table('simulation_jobs')->where('simulation_id', $this->simulationId)->where('job_type', 'execute')->lockForUpdate()->first();
|
||||
if (! $job || in_array($job->status, ['succeeded', 'failed'], true)) {
|
||||
return;
|
||||
}
|
||||
$scenario = DB::table('simulation_scenarios')->where('simulation_id', $simulation->id)->orderBy('code')->first();
|
||||
if (! $scenario) {
|
||||
throw new \RuntimeException('Simulation has no scenario.');
|
||||
}
|
||||
$input = json_decode($scenario->parameters, true, flags: JSON_THROW_ON_ERROR);
|
||||
$row = DB::selectOne('select (CAST(? AS numeric) * CAST(? AS numeric) / 100 * (1 - CAST(? AS numeric) / 100))::text as value', [$input['base'], $input['rate'], $input['reduction']]);
|
||||
$result = ['base' => $input['base'], 'rate_percent' => $input['rate'], 'reduction_percent' => $input['reduction'], 'indicative_total' => $row->value,
|
||||
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-tax-arithmetic-v1'];
|
||||
$json = json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
|
||||
$canonicalResult = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$json])->canonical;
|
||||
$resultHash = hash('sha256', $canonicalResult);
|
||||
$resultId = (string) Str::uuid();
|
||||
$engineVersion = 'portal-tax-arithmetic-v1+simulation-v'.$simulation->version_no;
|
||||
DB::table('simulation_results')->insert([
|
||||
'id' => $resultId, 'simulation_id' => $simulation->id, 'scenario_id' => $scenario->id, 'engine_version' => $engineVersion,
|
||||
'result_snapshot' => $json, 'result_sha256' => $resultHash, 'created_at' => now(),
|
||||
]);
|
||||
$simulation->update(['status' => 'completed', 'version_no' => $simulation->version_no + 1, 'result_snapshot' => $result, 'error_code' => null]);
|
||||
DB::table('simulation_jobs')->where('id', $job->id)->update(['status' => 'succeeded', 'finished_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('simulation_reports')->insert(['id' => (string) Str::uuid(), 'simulation_id' => $simulation->id, 'version_no' => $scenario->version_no,
|
||||
'status' => 'ready', 'report_snapshot' => $json, 'report_sha256' => $resultHash, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$sourceJson = json_encode($input, JSON_THROW_ON_ERROR);
|
||||
$canonicalSource = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$sourceJson])->canonical;
|
||||
DB::table('simulation_result_sources')->insertOrIgnore(['id' => (string) Str::uuid(), 'result_id' => $resultId,
|
||||
'source_type' => 'user_input', 'source_id' => $scenario->id, 'source_version' => (string) $scenario->version_no,
|
||||
'source_snapshot' => $sourceJson, 'source_sha256' => hash('sha256', $canonicalSource), 'created_at' => now()]);
|
||||
DB::table('simulation_audit_events')->insert(['simulation_id' => $simulation->id, 'actor_user_id' => $simulation->owner_user_id,
|
||||
'action' => 'simulation.completed', 'correlation_id' => $simulation->id, 'data' => json_encode(['result_sha256' => hash('sha256', $json), 'attempt' => $job->attempts + 1], JSON_THROW_ON_ERROR), 'occurred_at' => now()]);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function failed(\Throwable $exception): void
|
||||
{
|
||||
DB::transaction(function (): void {
|
||||
app(SimulationExecution::class)->setContext($this->actorId, $this->tokenHash);
|
||||
$job = DB::table('simulation_jobs')->where('simulation_id', $this->simulationId)->where('job_type', 'execute')->lockForUpdate()->first();
|
||||
if (! $job || $job->status === 'succeeded') {
|
||||
return;
|
||||
}
|
||||
DB::table('simulation_jobs')->where('id', $job->id)->update(['status' => 'failed', 'attempts' => 3, 'finished_at' => now(), 'error_code' => 'execution_failed', 'updated_at' => now()]);
|
||||
$simulation = Simulation::where('id', $this->simulationId)->lockForUpdate()->first();
|
||||
if ($simulation) {
|
||||
if ($simulation->status !== 'failed') {
|
||||
$simulation->update(['status' => 'failed', 'version_no' => $simulation->version_no + 1, 'error_code' => 'execution_failed']);
|
||||
}
|
||||
DB::table('simulation_audit_events')->insert(['simulation_id' => $simulation->id, 'actor_user_id' => $this->actorId,
|
||||
'action' => 'simulation.failed', 'correlation_id' => $simulation->id, 'data' => json_encode(['error_code' => 'execution_failed'], JSON_THROW_ON_ERROR), 'occurred_at' => now()]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class ExistingBusiness extends DomainRecord
|
||||
{
|
||||
protected $hidden = ['payload'];
|
||||
|
||||
protected $casts = [
|
||||
'payload' => 'encrypted:array',
|
||||
'version_no' => 'integer',
|
||||
'amount_min' => 'decimal:2',
|
||||
'amount_max' => 'decimal:2',
|
||||
'available_percentage' => 'decimal:2',
|
||||
'submitted_at' => 'immutable_datetime',
|
||||
'published_at' => 'immutable_datetime',
|
||||
'expires_at' => 'immutable_datetime',
|
||||
'next_action_due_at' => 'immutable_datetime',
|
||||
];
|
||||
|
||||
/** @return BelongsTo<Sector, $this> */
|
||||
public function sector(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Sector::class);
|
||||
}
|
||||
|
||||
/** @param Builder<ExistingBusiness> $query
|
||||
* @return Builder<ExistingBusiness>
|
||||
*/
|
||||
public function scopePublished(Builder $query): Builder
|
||||
{
|
||||
return $query->where('status', 'published')->whereNotNull('published_at')->where('published_at', '<=', now())
|
||||
->where(fn (Builder $q) => $q->whereNull('expires_at')->orWhere('expires_at', '>=', today()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ExistingBusinessMandate extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected $hidden = ['payload'];
|
||||
|
||||
protected $casts = ['payload' => 'encrypted:array', 'valid_from' => 'date', 'valid_until' => 'date'];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Concerns\HasUuids;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ExistingBusinessObject extends Model
|
||||
{
|
||||
use HasUuids;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected $hidden = ['payload'];
|
||||
|
||||
protected $casts = ['payload' => 'encrypted:array'];
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class GeoLocation extends DomainRecord
|
||||
{
|
||||
protected $fillable = ['name', 'location_type', 'parent_id', 'code'];
|
||||
|
||||
/** @return BelongsTo<GeoLocation, $this> */
|
||||
public function parent(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'parent_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<GeoLocation, $this> */
|
||||
public function children(): HasMany
|
||||
{
|
||||
return $this->hasMany(self::class, 'parent_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<Opportunity, $this> */
|
||||
public function opportunities(): HasMany
|
||||
{
|
||||
return $this->hasMany(Opportunity::class, 'primary_territory_id');
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,8 @@ class InterestRequest extends Model
|
||||
'investor_type', 'country', 'sector_interest',
|
||||
'opportunity_reference', 'investment_range', 'message',
|
||||
'privacy_consent', 'consented_at', 'status', 'source_page',
|
||||
'ip_address', 'user_agent', 'metadata', 'reviewed_at', 'reviewed_by',
|
||||
'ip_address', 'user_agent', 'metadata', 'reviewed_at', 'reviewed_by', 'existing_business_id', 'investor_id',
|
||||
'modality', 'requested_percentage', 'ticket_min', 'ticket_max', 'ticket_currency', 'assigned_to', 'next_action', 'next_action_due_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
@@ -23,6 +24,10 @@ class InterestRequest extends Model
|
||||
'consented_at' => 'datetime',
|
||||
'metadata' => 'array',
|
||||
'reviewed_at' => 'datetime',
|
||||
'requested_percentage' => 'decimal:2',
|
||||
'ticket_min' => 'decimal:2',
|
||||
'ticket_max' => 'decimal:2',
|
||||
'next_action_due_at' => 'immutable_datetime',
|
||||
];
|
||||
|
||||
/** @return BelongsTo<Opportunity, $this> */
|
||||
@@ -30,4 +35,22 @@ class InterestRequest extends Model
|
||||
{
|
||||
return $this->belongsTo(Opportunity::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<ExistingBusiness, $this> */
|
||||
public function existingBusiness(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ExistingBusiness::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Investor, $this> */
|
||||
public function investor(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Investor::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<User, $this> */
|
||||
public function assignee(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'assigned_to');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,11 @@ class Investor extends Model
|
||||
'created_at' => 'immutable_datetime',
|
||||
'updated_at' => 'immutable_datetime',
|
||||
'deleted_at' => 'immutable_datetime',
|
||||
'investment_sectors' => 'array',
|
||||
'investment_geographies' => 'array',
|
||||
'investment_horizon_months' => 'integer',
|
||||
'ticket_min' => 'decimal:2',
|
||||
'ticket_max' => 'decimal:2',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
/**
|
||||
* @property string|null $primary_territory_id
|
||||
* @property int $territory_version
|
||||
*/
|
||||
class Opportunity extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
@@ -18,10 +22,12 @@ class Opportunity extends Model
|
||||
'estimated_investment_currency', 'financing_modality',
|
||||
'expected_impact', 'status', 'is_featured', 'published_at',
|
||||
'last_validated_at',
|
||||
'primary_territory_id', 'territory_version',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_featured' => 'boolean',
|
||||
'territory_version' => 'integer',
|
||||
'published_at' => 'datetime',
|
||||
'last_validated_at' => 'datetime',
|
||||
'estimated_investment_amount' => 'decimal:2',
|
||||
@@ -33,6 +39,12 @@ class Opportunity extends Model
|
||||
return $this->belongsTo(Sector::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<GeoLocation, $this> */
|
||||
public function primaryTerritory(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(GeoLocation::class, 'primary_territory_id');
|
||||
}
|
||||
|
||||
/** @param Builder<Opportunity> $query
|
||||
* @return Builder<Opportunity>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property int $version_no */
|
||||
class QuestionnaireVersion extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['schema_snapshot' => 'array', 'valid_from' => 'date', 'valid_to' => 'date'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
* @property int|null $owner_user_id
|
||||
* @property string|null $organization_id
|
||||
* @property string|null $anonymous_token_hash
|
||||
* @property string $status
|
||||
* @property int $version_no
|
||||
* @property array<string, mixed> $input_snapshot
|
||||
* @property array<string, mixed>|null $result_snapshot
|
||||
*/
|
||||
class Simulation extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['input_snapshot' => 'array', 'result_snapshot' => 'array', 'calculation_snapshot' => 'array'];
|
||||
|
||||
/** @return HasMany<SimulationScenario, $this> */
|
||||
public function scenarios(): HasMany
|
||||
{
|
||||
return $this->hasMany(SimulationScenario::class);
|
||||
}
|
||||
|
||||
/** @return HasMany<SimulationReport, $this> */
|
||||
public function reports(): HasMany
|
||||
{
|
||||
return $this->hasMany(SimulationReport::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
class SimulationFormDraft extends Model
|
||||
{
|
||||
protected $table = 'simulation_form_drafts';
|
||||
|
||||
protected $fillable = [
|
||||
'id', 'owner_user_id', 'anonymous_token_hash', 'version_no', 'create_key_hash', 'create_payload_hash', 'snapshot_sha256',
|
||||
'personal_snapshot', 'economic_snapshot', 'deleted_at',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['version_no' => 'integer', 'deleted_at' => 'immutable_datetime'];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $snapshot */
|
||||
public static function encryptSnapshot(array $snapshot): string
|
||||
{
|
||||
return Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public static function decryptSnapshot(string $snapshot): array
|
||||
{
|
||||
$decoded = json_decode(Crypt::decryptString($snapshot), true, 32, JSON_THROW_ON_ERROR);
|
||||
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationJob extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationObligation extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationReport extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['report_snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationResult extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['result_snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationResultSource extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['source_snapshot' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class SimulationScenario extends Model
|
||||
{
|
||||
public $incrementing = false;
|
||||
|
||||
protected $keyType = 'string';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = ['parameters' => 'array'];
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\User;
|
||||
|
||||
class ExistingBusinessPolicy
|
||||
{
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail();
|
||||
}
|
||||
|
||||
public function update(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $this->owns($user, $business) && in_array($business->status, ['draft', 'needs_information'], true);
|
||||
}
|
||||
|
||||
public function view(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
if ($this->owns($user, $business) || $this->review($user, $business) || $this->triage($user, $business)
|
||||
|| $this->approveLevelOne($user, $business) || $this->approveLevelTwo($user, $business) || $this->publish($user, $business)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['rejected', 'published', 'suspended', 'cancelled', 'archived'], true)
|
||||
&& $this->reviewQueue($user);
|
||||
}
|
||||
|
||||
public function delete(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $this->update($user, $business);
|
||||
}
|
||||
|
||||
public function owns(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail() && $business->owner_user_id === $user->id && ! $business->trashed();
|
||||
}
|
||||
|
||||
public function review(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['triage', 'in_review', 'needs_information'], true)
|
||||
&& $this->designated($user, 'reviewers');
|
||||
}
|
||||
|
||||
public function triage(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& in_array($business->status, ['submitted', 'triage'], true)
|
||||
&& $this->designated($user, 'triagers');
|
||||
}
|
||||
|
||||
public function approveLevelOne(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approval_l1'
|
||||
&& $this->designated($user, 'approvers_l1');
|
||||
}
|
||||
|
||||
public function approveLevelTwo(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approval_l2'
|
||||
&& $this->designated($user, 'approvers_l2');
|
||||
}
|
||||
|
||||
public function publish(User $user, ExistingBusiness $business): bool
|
||||
{
|
||||
return ! $business->trashed() && $business->owner_user_id !== $user->id
|
||||
&& $business->status === 'approved'
|
||||
&& $this->designated($user, 'publishers');
|
||||
}
|
||||
|
||||
public function reviewQueue(User $user): bool
|
||||
{
|
||||
foreach (['reviewers', 'triagers', 'approvers_l1', 'approvers_l2', 'publishers'] as $designation) {
|
||||
if ($this->designated($user, $designation)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function designated(User $user, string $designation): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail() && $user->can('manage-portal')
|
||||
&& (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
||||
&& in_array(strtolower($user->email), config('existing-business.'.$designation, []), true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\Simulation;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class SimulationPolicy
|
||||
{
|
||||
public function view(User $user, Simulation $simulation): bool
|
||||
{
|
||||
if ($simulation->organization_id === null && $simulation->owner_user_id === $user->id && $user->hasVerifiedEmail()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $simulation->organization_id !== null && $user->hasVerifiedEmail()
|
||||
&& DB::table('memberships')->where('user_id', $user->id)
|
||||
->where('organization_id', $simulation->organization_id)->whereNull('deleted_at')->exists();
|
||||
}
|
||||
|
||||
public function update(User $user, Simulation $simulation): bool
|
||||
{
|
||||
if (! $user->hasVerifiedEmail() || ! in_array($simulation->status, ['queued', 'completed', 'failed'], true)) {
|
||||
return false;
|
||||
}
|
||||
if ($simulation->organization_id === null) {
|
||||
return $simulation->owner_user_id === $user->id;
|
||||
}
|
||||
|
||||
return DB::table('memberships')->where('user_id', $user->id)->where('organization_id', $simulation->organization_id)
|
||||
->whereNull('deleted_at')->whereIn('role', ['admin', 'manager', 'officer'])->exists();
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ namespace App\Providers;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use App\Services\Mne\CompatibleBusinessRepository;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -23,7 +25,7 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
$this->app->bind(BusinessRepository::class, CompatibleBusinessRepository::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,7 +49,45 @@ class AppServiceProvider extends ServiceProvider
|
||||
$model::deleted($invalidate);
|
||||
}
|
||||
|
||||
RateLimiter::for('api', fn (Request $request) => Limit::perMinute(60)->by($request->ip()));
|
||||
$requestLimitKey = static function (Request $request): string {
|
||||
if ($user = $request->user()) {
|
||||
return 'user:'.$user->getAuthIdentifier();
|
||||
}
|
||||
|
||||
$token = $request->header('X-Simulation-Token');
|
||||
|
||||
return is_string($token) && $token !== ''
|
||||
? 'anonymous:'.hash('sha256', $token)
|
||||
: 'ip:'.$request->ip();
|
||||
};
|
||||
|
||||
RateLimiter::for('api', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(60)->by($requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Demasiadas solicitações. Aguarde um pouco e tente novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
|
||||
RateLimiter::for('simulation-draft-writes', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(30)->by('simulation-draft:'.$requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Foram guardadas demasiadas alterações em pouco tempo. Aguarde um minuto e tente novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
|
||||
RateLimiter::for('simulation-calculations', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(10)->by('simulation-calculation:'.$requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Foram solicitados demasiados cálculos em pouco tempo. Aguarde antes de tentar novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
|
||||
RateLimiter::for('simulation-scenario-updates', function (Request $request) use ($requestLimitKey) {
|
||||
return Limit::perMinute(10)->by('simulation-scenario-update:'.$requestLimitKey($request))
|
||||
->response(fn (Request $request, array $headers) => response()->json([
|
||||
'message' => 'Foram solicitadas demasiadas alterações de cenário em pouco tempo. Aguarde antes de tentar novamente.',
|
||||
], 429, $headers));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
final class BusinessFormSchema
|
||||
{
|
||||
/** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,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_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],
|
||||
'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],
|
||||
'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],
|
||||
'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']],
|
||||
'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_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],
|
||||
'document_reference' => ['step' => 7, 'pt' => 'Referências documentais (não são ficheiros validados)', 'en' => 'Document references (not validated files)', 'type' => 'textarea', 'max' => 2000],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, array<int,string>> */
|
||||
public static function rules(): array
|
||||
{
|
||||
$rules = [];
|
||||
foreach (self::fields() as $key => $field) {
|
||||
$rules['payload.'.$key] = ['nullable', 'string', 'max:'.$field['max']];
|
||||
if (isset($field['options'])) {
|
||||
$rules['payload.'.$key][] = 'in:'.implode(',', array_keys($field['options']));
|
||||
}
|
||||
}
|
||||
$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.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_step'] = ['nullable', 'integer', 'between:1,8'];
|
||||
$rules['payload.title'] = ['required', 'string', 'max:200'];
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload */
|
||||
public static function validateSubmission(array $payload): void
|
||||
{
|
||||
$rules = [];
|
||||
foreach (['proponent_type', 'proponent_name', 'tax_identifier', 'contact_email', 'country', 'acting_capacity', 'declared_holder', 'location_notes'] as $field) {
|
||||
$rules[$field] = ['required'];
|
||||
}
|
||||
$rules['legitimacy_declaration'] = ['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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use RuntimeException;
|
||||
use SimpleXMLElement;
|
||||
use ZipArchive;
|
||||
|
||||
/** Inspects an authorised local workbook without importing or transforming data. */
|
||||
final class CartographyWorkbookAudit
|
||||
{
|
||||
/** @param array<string, mixed> $manifest
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function inspect(string $path, array $manifest): array
|
||||
{
|
||||
if (! is_file($path) || filesize($path) > 20_000_000) {
|
||||
throw new RuntimeException('Workbook missing or larger than 20 MB.');
|
||||
}
|
||||
$checksum = hash_file('sha256', $path);
|
||||
if ($checksum === false) {
|
||||
throw new RuntimeException('Unable to read workbook checksum.');
|
||||
}
|
||||
if (! isset($manifest['sha256']) || ! hash_equals(strtolower((string) $manifest['sha256']), $checksum)) {
|
||||
throw new RuntimeException('Manifest checksum does not match the workbook.');
|
||||
}
|
||||
foreach (['inspection_authorization'] as $key) {
|
||||
if (! is_string($manifest[$key] ?? null) || trim($manifest[$key]) === '') {
|
||||
throw new RuntimeException('Missing manifest field: '.$key);
|
||||
}
|
||||
}
|
||||
if (isset($manifest['classification']) && ! in_array($manifest['classification'], ['public', 'internal', 'confidential', 'restricted'], true)) {
|
||||
throw new RuntimeException('Invalid classification.');
|
||||
}
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($path) !== true) {
|
||||
throw new RuntimeException('Invalid XLSX container.');
|
||||
}
|
||||
try {
|
||||
$bytes = 0;
|
||||
if ($zip->numFiles > 1000) {
|
||||
throw new RuntimeException('Too many archive entries.');
|
||||
}
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$entry = $zip->statIndex($i);
|
||||
if ($entry === false) {
|
||||
throw new RuntimeException('Unreadable archive entry.');
|
||||
}
|
||||
$bytes += $entry['size'];
|
||||
if ($bytes > 50_000_000 || str_contains($entry['name'], '../')) {
|
||||
throw new RuntimeException('Unsafe or oversized archive.');
|
||||
}
|
||||
}
|
||||
$strings = [];
|
||||
if ($zip->locateName('xl/sharedStrings.xml') !== false) {
|
||||
foreach ($this->xml($zip, 'xl/sharedStrings.xml')->xpath('//*[local-name()="si"]') ?: [] as $item) {
|
||||
$strings[] = implode('', array_map(fn ($t) => (string) $t, $item->xpath('.//*[local-name()="t"]') ?: []));
|
||||
}
|
||||
}
|
||||
$relationships = [];
|
||||
foreach ($this->xml($zip, 'xl/_rels/workbook.xml.rels')->children() as $rel) {
|
||||
$target = (string) $rel['Target'];
|
||||
if ((string) $rel['TargetMode'] !== 'External' && ! str_contains($target, '..')) {
|
||||
$relationships[(string) $rel['Id']] = str_starts_with($target, '/') ? ltrim($target, '/') : 'xl/'.$target;
|
||||
}
|
||||
}
|
||||
$sheets = [];
|
||||
$rowCount = 0;
|
||||
foreach ($this->xml($zip, 'xl/workbook.xml')->xpath('//*[local-name()="sheet"]') ?: [] as $sheet) {
|
||||
$id = (string) $sheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id'];
|
||||
if (! isset($relationships[$id])) {
|
||||
throw new RuntimeException('Unresolved worksheet relationship.');
|
||||
}
|
||||
$rows = [];
|
||||
$seen = [];
|
||||
foreach ($this->xml($zip, $relationships[$id])->xpath('//*[local-name()="sheetData"]/*[local-name()="row"]') ?: [] as $row) {
|
||||
if (++$rowCount > 50000) {
|
||||
throw new RuntimeException('Audit limit of 50000 rows exceeded.');
|
||||
}
|
||||
$values = [];
|
||||
$issues = [];
|
||||
foreach ($row->children() as $cell) {
|
||||
$address = (string) $cell['r'];
|
||||
$value = (string) $cell->v;
|
||||
if ((string) $cell['t'] === 's') {
|
||||
$value = $strings[(int) $value] ?? '';
|
||||
} elseif ((string) $cell['t'] === 'inlineStr') {
|
||||
$value = implode('', array_map(fn ($t) => (string) $t, $cell->xpath('.//*[local-name()="t"]') ?: []));
|
||||
}
|
||||
$values[preg_replace('/[0-9]+$/', '', $address)] = $value;
|
||||
if ($value === '') {
|
||||
$issues[] = ['field' => $address, 'code' => 'empty_cell'];
|
||||
}
|
||||
if (isset($cell->f)) {
|
||||
$issues[] = ['field' => $address, 'code' => 'formula_not_evaluated'];
|
||||
}
|
||||
if ((string) $cell['t'] === 'e') {
|
||||
$issues[] = ['field' => $address, 'code' => 'spreadsheet_error'];
|
||||
}
|
||||
}
|
||||
$hash = hash('sha256', json_encode($values, JSON_THROW_ON_ERROR));
|
||||
$duplicate = isset($seen[$hash]);
|
||||
$seen[$hash] = true;
|
||||
$issues[] = ['field' => '*', 'code' => 'semantic_mapping_and_institutional_validation_pending'];
|
||||
if (empty($manifest['original_crs'])) {
|
||||
$issues[] = ['field' => '*', 'code' => 'original_crs_unknown'];
|
||||
}
|
||||
$rows[] = ['row' => (int) $row['r'], 'status' => $duplicate ? 'duplicate' : 'pending', 'populated_columns' => array_keys($values), 'issues' => $issues];
|
||||
}
|
||||
$sheets[] = ['name' => (string) $sheet['name'], 'state' => (string) $sheet['state'] ?: 'visible', 'rows' => $rows];
|
||||
}
|
||||
|
||||
return ['sha256' => $checksum, 'version' => $manifest['version'] ?? null, 'classification' => $manifest['classification'] ?? null,
|
||||
'pending_metadata' => array_values(array_filter(['owner', 'version', 'received_at', 'classification', 'original_crs'], fn ($key) => empty($manifest[$key]))),
|
||||
'original_crs' => $manifest['original_crs'] ?? null, 'publication_allowed' => false, 'transformations' => [],
|
||||
'status' => 'quarantined', 'sheets' => $sheets, 'rows_inspected' => $rowCount,
|
||||
'limitations' => ['No semantic header mapping, omitted-cell inference, coordinate validation or external reference resolution.', 'No source values, coordinates or formulas copied to the report.']];
|
||||
} finally {
|
||||
$zip->close();
|
||||
}
|
||||
}
|
||||
|
||||
private function xml(ZipArchive $zip, string $name): SimpleXMLElement
|
||||
{
|
||||
$content = $zip->getFromName($name);
|
||||
if ($content === false || preg_match('/<!DOCTYPE|<!ENTITY/i', $content)) {
|
||||
throw new RuntimeException('Missing or unsafe workbook XML.');
|
||||
}
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
try {
|
||||
$xml = simplexml_load_string($content, SimpleXMLElement::class, LIBXML_NONET);
|
||||
if ($xml === false) {
|
||||
throw new RuntimeException('Malformed workbook XML.');
|
||||
}
|
||||
|
||||
return $xml;
|
||||
} finally {
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\User;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
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'];
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input, ?string $id = null): ExistingBusiness
|
||||
{
|
||||
$data = Validator::make($input, [
|
||||
'modality' => ['required', 'in:'.implode(',', self::MODALITIES)],
|
||||
'sector_id' => ['sometimes', 'nullable', 'integer', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
|
||||
'public_title' => ['sometimes', 'nullable', 'string', 'max:180'],
|
||||
'activity_code' => ['sometimes', 'nullable', 'string', 'max:60'],
|
||||
'stage' => ['sometimes', 'nullable', 'string', 'max:40'],
|
||||
'objective' => ['sometimes', 'nullable', 'string', 'max:5000'],
|
||||
'currency' => ['sometimes', 'nullable', 'regex:/^[A-Z]{3}$/', 'required_with:amount_min,amount_max'],
|
||||
'amount_min' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:999999999999999999.99'],
|
||||
'amount_max' => ['sometimes', 'nullable', 'numeric', 'min:0', 'gte:amount_min', 'max:999999999999999999.99'],
|
||||
'available_percentage' => ['sometimes', 'nullable', 'numeric', 'between:0,100'],
|
||||
'funds_use' => ['sometimes', 'nullable', 'string', 'max:10000'],
|
||||
'classification' => ['required', 'in:internal,confidential,restricted'],
|
||||
'version_no' => [$id ? 'required' : 'prohibited', 'integer', 'min:1'],
|
||||
'reason' => ['required', 'string', 'min:10', 'max:1000'],
|
||||
'payload' => ['required', 'array:'.implode(',', [...array_keys(BusinessFormSchema::fields()), 'wizard_version', 'wizard_step'])],
|
||||
'payload.title' => ['required', 'string', 'max:200'],
|
||||
'payload.description' => ['nullable', 'string', 'max:10000'],
|
||||
'payload.declared_reason' => ['nullable', 'string', 'max:2000'],
|
||||
'payload.source_reference' => ['nullable', 'string', 'max:2000'],
|
||||
'payload.valid_until' => ['nullable', 'date_format:Y-m-d'],
|
||||
...BusinessFormSchema::rules(),
|
||||
])->validate();
|
||||
|
||||
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++;
|
||||
} else {
|
||||
Gate::forUser($actor)->authorize('create', ExistingBusiness::class);
|
||||
if (! $actor->exists || $actor->id < 1) {
|
||||
abort(403, 'A conta deve estar registada.');
|
||||
}
|
||||
$business = new ExistingBusiness;
|
||||
$business->code = 'MNE-'.Str::uuid();
|
||||
$business->owner_user_id = $actor->id;
|
||||
$business->version_no = 1;
|
||||
$business->status = 'draft';
|
||||
}
|
||||
$business->fill(['modality' => $data['modality'], 'classification' => $data['classification'], 'payload' => $data['payload']]);
|
||||
foreach (['public_title', 'activity_code', 'stage', 'objective', 'currency', 'amount_min', 'amount_max', 'available_percentage', 'funds_use'] as $field) {
|
||||
if (array_key_exists($field, $data)) {
|
||||
$business->{$field} = $data[$field];
|
||||
}
|
||||
}
|
||||
if (array_key_exists('sector_id', $data)) {
|
||||
$business->sector_id = $data['sector_id'];
|
||||
}
|
||||
$business->save();
|
||||
$this->snapshot($business, $actor, $id ? 'updated' : 'created', $data['reason']);
|
||||
|
||||
return $business;
|
||||
});
|
||||
}
|
||||
|
||||
public function archive(User $actor, string $id, int $version, string $reason): void
|
||||
{
|
||||
Validator::make(['reason' => $reason], ['reason' => ['required', 'string', 'min:10', 'max:1000']])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $version, $reason) {
|
||||
$business = app(BusinessRepository::class)->find($id, true);
|
||||
Gate::forUser($actor)->authorize('delete', $business);
|
||||
abort_unless($business->version_no === $version, 409);
|
||||
$business->version_no++;
|
||||
$business->save();
|
||||
$business->delete();
|
||||
$this->snapshot($business, $actor, 'archived', $reason);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $context */
|
||||
public function snapshot(ExistingBusiness $business, User $actor, string $action, string $reason, array $context = []): void
|
||||
{
|
||||
$snapshot = json_encode(['context' => $context, 'record' => $business->attributesToArray(), 'payload' => $business->payload,
|
||||
'objects' => ExistingBusinessObject::where('business_id', $business->id)->orderBy('id')->get()
|
||||
->map(fn ($object) => [...$object->attributesToArray(), 'payload' => $object->payload])->all(),
|
||||
], JSON_THROW_ON_ERROR);
|
||||
DB::table('existing_business_revisions')->insert(['id' => (string) Str::uuid(), 'business_id' => $business->id,
|
||||
'version_no' => $business->version_no, 'actor_id' => $actor->id, 'action' => $action,
|
||||
'reason' => Crypt::encryptString($reason), 'snapshot' => Crypt::encryptString($snapshot), 'sha256' => hash('sha256', $snapshot)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Domain\Opportunities\Enums\OpportunityStatus;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\User;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class ExistingBusinessIntake
|
||||
{
|
||||
public function transition(User $actor, string $id, int $version, string $action, string $note, bool $consent = false, ?string $confirmationCode = null): ExistingBusiness
|
||||
{
|
||||
Validator::make(compact('action', 'note'), [
|
||||
'action' => ['required', Rule::in([
|
||||
OpportunityStatus::Submitted->value,
|
||||
OpportunityStatus::Triage->value,
|
||||
OpportunityStatus::InReview->value,
|
||||
OpportunityStatus::NeedsInformation->value,
|
||||
OpportunityStatus::ApprovalL1->value,
|
||||
OpportunityStatus::ApprovalL2->value,
|
||||
OpportunityStatus::Approved->value,
|
||||
OpportunityStatus::Published->value,
|
||||
OpportunityStatus::Rejected->value,
|
||||
OpportunityStatus::Withdrawn->value,
|
||||
])],
|
||||
'note' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $action, $note, $consent, $confirmationCode) {
|
||||
$business = app(BusinessRepository::class)->find($id, true);
|
||||
$ability = match ($action) {
|
||||
OpportunityStatus::Submitted->value, OpportunityStatus::Withdrawn->value => 'owns',
|
||||
OpportunityStatus::Triage->value => 'triage',
|
||||
OpportunityStatus::ApprovalL2->value => 'approveLevelOne',
|
||||
OpportunityStatus::Approved->value => 'approveLevelTwo',
|
||||
OpportunityStatus::Published->value => 'publish',
|
||||
OpportunityStatus::Rejected->value => in_array($business->status, ['approval_l1', 'approval_l2'], true)
|
||||
? ($business->status === 'approval_l1' ? 'approveLevelOne' : 'approveLevelTwo') : 'review',
|
||||
default => 'review',
|
||||
};
|
||||
Gate::forUser($actor)->authorize($ability, $business);
|
||||
abort_unless($business->version_no === $version, 409, 'Versão desactualizada.');
|
||||
$allowed = [
|
||||
OpportunityStatus::Submitted->value => [OpportunityStatus::Draft->value, OpportunityStatus::NeedsInformation->value],
|
||||
OpportunityStatus::Triage->value => [OpportunityStatus::Submitted->value],
|
||||
OpportunityStatus::InReview->value => [OpportunityStatus::Triage->value],
|
||||
OpportunityStatus::NeedsInformation->value => [OpportunityStatus::Triage->value, OpportunityStatus::InReview->value],
|
||||
OpportunityStatus::ApprovalL1->value => [OpportunityStatus::InReview->value],
|
||||
OpportunityStatus::ApprovalL2->value => [OpportunityStatus::ApprovalL1->value],
|
||||
OpportunityStatus::Approved->value => [OpportunityStatus::ApprovalL2->value],
|
||||
OpportunityStatus::Published->value => [OpportunityStatus::Approved->value],
|
||||
OpportunityStatus::Rejected->value => [OpportunityStatus::Triage->value, OpportunityStatus::InReview->value,
|
||||
OpportunityStatus::ApprovalL1->value, OpportunityStatus::ApprovalL2->value],
|
||||
OpportunityStatus::Withdrawn->value => [OpportunityStatus::Draft->value, OpportunityStatus::Submitted->value,
|
||||
OpportunityStatus::Triage->value, OpportunityStatus::InReview->value, OpportunityStatus::NeedsInformation->value],
|
||||
];
|
||||
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);
|
||||
$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 o elemento aplicável na etapa 6: '.$requiredKind]);
|
||||
}
|
||||
Validator::make(['confirmation_code' => $confirmationCode, 'sector_id' => $business->sector_id], [
|
||||
'confirmation_code' => ['required', Rule::in([$business->code])],
|
||||
'sector_id' => ['required', Rule::exists('sectors', 'id')->whereNull('deleted_at')->where('is_active', true)],
|
||||
])->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 ($action === OpportunityStatus::Approved->value) {
|
||||
$levelOneActor = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
||||
->where('to_status', OpportunityStatus::ApprovalL2->value)->orderByDesc('created_at')->value('actor_id');
|
||||
abort_unless($levelOneActor !== null && (int) $levelOneActor !== (int) $actor->id, 403,
|
||||
'A aprovação de nível 2 deve ser feita por uma pessoa diferente da aprovação de nível 1.');
|
||||
}
|
||||
if ($action === OpportunityStatus::Published->value) {
|
||||
abort_unless(is_string($business->public_title) && trim($business->public_title) !== '' && $business->sector_id,
|
||||
422, 'Preencha o título público e o sector antes de publicar.');
|
||||
$approvalActors = DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
||||
->whereIn('to_status', [OpportunityStatus::ApprovalL2->value, OpportunityStatus::Approved->value])
|
||||
->whereNotNull('actor_id')->pluck('actor_id')->map(fn ($id) => (int) $id)->all();
|
||||
abort_unless(! in_array((int) $actor->id, $approvalActors, true), 403,
|
||||
'A publicação deve ser executada por uma pessoa diferente dos aprovadores.');
|
||||
}
|
||||
$fromStatus = $business->status;
|
||||
$business->status = $action;
|
||||
if ($action === OpportunityStatus::Published->value) {
|
||||
$business->published_at = now();
|
||||
$business->public_slug ??= Str::slug($business->public_title).'-'.strtolower(substr(str_replace('-', '', $business->id), 0, 10));
|
||||
}
|
||||
$business->version_no++;
|
||||
$business->save();
|
||||
$correlationId = (string) Str::uuid();
|
||||
DB::table('business_workflow_transitions')->insert([
|
||||
'id' => (string) Str::uuid(),
|
||||
'existing_business_id' => $business->id,
|
||||
'from_status' => $fromStatus,
|
||||
'to_status' => $action,
|
||||
'actor_id' => $actor->id,
|
||||
'reason' => Crypt::encryptString($note),
|
||||
'correlation_id' => $correlationId,
|
||||
'metadata' => json_encode(['version_no' => $business->version_no, 'source' => 'portal-intake'], JSON_THROW_ON_ERROR),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
if ($action === OpportunityStatus::Submitted->value) {
|
||||
DB::table('tasks')->insertOrIgnore([
|
||||
'source_system' => 'portal-intake',
|
||||
'external_id' => 'BusinessListingTriage:'.$business->id.':'.$business->version_no,
|
||||
'version_no' => 1,
|
||||
'data_classification' => 'internal',
|
||||
'correlation_id' => $correlationId,
|
||||
'existing_business_id' => $business->id,
|
||||
'task_type' => 'triage',
|
||||
'title' => 'Triar oportunidade '.$business->code,
|
||||
'status' => 'open',
|
||||
'priority' => 3,
|
||||
'due_at' => now()->addWeekdays(3),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
DB::table('outbox_events')->insert([
|
||||
'source_system' => 'portal-intake',
|
||||
'external_id' => 'BusinessListingSubmitted:'.$business->id.':'.$business->version_no,
|
||||
'aggregate_type' => 'business_listing',
|
||||
'aggregate_id' => $business->id,
|
||||
'event_type' => 'BusinessListingSubmitted',
|
||||
'data_classification' => 'confidential',
|
||||
'correlation_id' => $correlationId,
|
||||
'status' => 'pending',
|
||||
'payload' => json_encode(['business_id' => $business->id, 'version_no' => $business->version_no], JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
}
|
||||
DB::table('existing_business_reviews')->insert(['id' => (string) Str::uuid(), 'business_id' => $id, 'actor_id' => $actor->id,
|
||||
'version_no' => $business->version_no, 'action' => $action,
|
||||
'note' => Crypt::encryptString(json_encode(['note' => $note, 'review_consent' => $action === 'submitted' ? $consent : null], JSON_THROW_ON_ERROR))]);
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $action, $note);
|
||||
|
||||
return $business;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\User;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
final class ExistingBusinessObjects
|
||||
{
|
||||
public const KINDS = ['company', 'participation', 'asset', 'property', 'unit', 'improvement', 'agricultural_investment', 'land_right', 'contract', 'license', 'authorization', 'encumbrance', 'valuation', 'capital_request'];
|
||||
|
||||
/** @return array<string,array<int,string>> */
|
||||
public static function fields(): array
|
||||
{
|
||||
return [
|
||||
'label' => ['required', 'string', 'max:200'],
|
||||
'declared_holder' => ['nullable', 'string', 'max:500'],
|
||||
'document_reference' => ['nullable', 'string', 'max:1000'],
|
||||
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'competent_entity' => ['nullable', 'string', 'max:500'],
|
||||
'purpose' => ['nullable', 'string', 'max:2000'],
|
||||
'location_description' => ['nullable', 'string', 'max:2000'],
|
||||
'boundaries_description' => ['nullable', 'string', 'max:2000'],
|
||||
'occupancy' => ['nullable', 'string', 'max:2000'],
|
||||
'condition' => ['nullable', 'string', 'max:2000'],
|
||||
'encumbrances' => ['nullable', 'string', 'max:4000'],
|
||||
'restrictions' => ['nullable', 'string', 'max:4000'],
|
||||
'required_authorizations' => ['nullable', 'string', 'max:4000'],
|
||||
'transfer_condition' => ['nullable', 'string', 'max:4000'],
|
||||
'contract_type' => ['nullable', 'in:purchase,sale,lease,operation,management,other'],
|
||||
'valid_from' => ['nullable', 'date_format:Y-m-d'],
|
||||
'valid_until' => ['nullable', 'date_format:Y-m-d'],
|
||||
'area' => ['nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,4})?$/', 'numeric', 'gt:0'],
|
||||
'area_unit' => ['nullable', 'required_with:area', 'in:m2,ha,km2'],
|
||||
'amount' => ['nullable', 'string', 'regex:/^\d{1,15}(\.\d{1,2})?$/', 'numeric', 'min:0'],
|
||||
'currency' => ['nullable', 'required_with:amount', 'regex:/^[A-Z]{3}$/'],
|
||||
'value_kind' => ['nullable', 'required_with:amount', 'in:asking,indicative,appraised,proposed,negotiated,confirmed'],
|
||||
'participation_percent' => ['nullable', 'numeric', 'between:0,100'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, string $businessId, array $input, ?string $objectId = null): ExistingBusinessObject
|
||||
{
|
||||
$rules = self::fields();
|
||||
if (! empty($input['payload']['valid_from'])) {
|
||||
$rules['valid_until'][] = 'after_or_equal:valid_from';
|
||||
}
|
||||
$data = Validator::make($input, ['version_no' => ['required', 'integer', 'min:1'],
|
||||
'kind' => ['required', 'in:'.implode(',', self::KINDS)], 'reason' => ['required', 'string', 'min:10', 'max:1000'],
|
||||
'payload' => ['required', 'array:'.implode(',', array_keys($rules))],
|
||||
])->validate();
|
||||
// Cross-field rules operate on the payload itself, rather than sibling root fields.
|
||||
Validator::make($data['payload'], $rules)->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $businessId, $objectId, $data) {
|
||||
$business = app(BusinessRepository::class)->find($businessId, true);
|
||||
Gate::forUser($actor)->authorize('update', $business);
|
||||
abort_unless($business->version_no === $data['version_no'], 409, 'Versão desactualizada.');
|
||||
abort_if(! $objectId && ExistingBusinessObject::where('business_id', $businessId)->count() >= 100, 422, 'Máximo de 100 elementos por negócio.');
|
||||
$object = $objectId ? ExistingBusinessObject::where('business_id', $businessId)->whereKey($objectId)->firstOrFail() : new ExistingBusinessObject;
|
||||
if ($objectId) {
|
||||
abort_unless($object->kind === $data['kind'], 422, 'Crie outro elemento para uma natureza diferente.');
|
||||
}
|
||||
$object->fill(['business_id' => $businessId, 'kind' => $data['kind'], 'classification' => 'restricted', 'verification_status' => 'pending', 'payload' => $data['payload']]);
|
||||
$object->save();
|
||||
$business->version_no++;
|
||||
$business->save();
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, $objectId ? 'object_updated' : 'object_added', $data['reason']);
|
||||
|
||||
return $object;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\ExistingBusinessObject;
|
||||
use App\Models\User;
|
||||
use App\Services\Mne\BusinessRepository;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
final class ExistingBusinessVerification
|
||||
{
|
||||
public const CHECKS = ['identity', 'representation', 'declared_ownership', 'documentary_ownership', 'document_received', 'document_validated', 'independent_valuation', 'land_right_documented', 'license_confirmed', 'validity', 'legal_transfer', 'prior_authorization'];
|
||||
|
||||
private function contentVersion(string $id): int
|
||||
{
|
||||
return (int) DB::table('existing_business_revisions')->where('business_id', $id)
|
||||
->whereIn('action', ['created', 'updated', 'object_added', 'object_updated'])->max('version_no');
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, string $id, array $input): ExistingBusiness
|
||||
{
|
||||
$data = Validator::make($input, [
|
||||
'version_no' => ['required', 'integer', 'min:1'],
|
||||
'object_id' => ['nullable', 'uuid'],
|
||||
'check' => ['required', 'in:'.implode(',', self::CHECKS)],
|
||||
'outcome' => ['required', 'in:confirmed,rejected,inconclusive,revoked'],
|
||||
'evidence_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'note' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'valid_until' => ['required_if:outcome,confirmed', 'nullable', 'date_format:Y-m-d', 'after_or_equal:today'],
|
||||
])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$business = app(BusinessRepository::class)->find($id, true);
|
||||
Gate::forUser($actor)->authorize('review', $business);
|
||||
abort_unless($business->status === 'in_review' && $business->version_no === $data['version_no'], 409, 'Reabra a versão actual em revisão.');
|
||||
if (! empty($data['object_id'])) {
|
||||
ExistingBusinessObject::where('business_id', $id)->whereKey($data['object_id'])->firstOrFail();
|
||||
}
|
||||
$data['content_version'] = $this->contentVersion($id);
|
||||
$business->version_no++;
|
||||
$business->save();
|
||||
app(ExistingBusinessDrafts::class)->snapshot($business, $actor, 'verification', $data['note'], $data);
|
||||
|
||||
return $business;
|
||||
});
|
||||
}
|
||||
|
||||
/** Latest finding for each check/subject; complete evidence remains in immutable revisions.
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function findings(ExistingBusiness $business): array
|
||||
{
|
||||
$contentVersion = $this->contentVersion($business->id);
|
||||
$findings = [];
|
||||
foreach (DB::table('existing_business_revisions')->where('business_id', $business->id)
|
||||
->where('action', 'verification')->orderByDesc('version_no')->cursor() as $revision) {
|
||||
$data = json_decode(Crypt::decryptString($revision->snapshot), true, 512, JSON_THROW_ON_ERROR)['context'];
|
||||
$key = ($data['object_id'] ?? 'business').':'.$data['check'];
|
||||
if (isset($findings[$key])) {
|
||||
continue;
|
||||
}
|
||||
$effective = $data['outcome'];
|
||||
if ($data['content_version'] !== $contentVersion) {
|
||||
$effective = 'stale';
|
||||
} elseif (! empty($data['valid_until']) && $data['valid_until'] < today()->toDateString()) {
|
||||
$effective = 'expired';
|
||||
}
|
||||
$findings[$key] = [...$data, 'effective_outcome' => $effective,
|
||||
'version_no' => $revision->version_no, 'created_at' => $revision->created_at];
|
||||
}
|
||||
|
||||
return array_values($findings);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@ final class InterestSubmission
|
||||
*/
|
||||
public function receive(#[SensitiveParameter] array $payload, #[SensitiveParameter] ?string $key, Closure $create): InterestRequest
|
||||
{
|
||||
$canonical = array_replace(['phone' => null, 'opportunityReference' => null, 'investmentRange' => null], $payload);
|
||||
$canonical = array_replace(['phone' => null, 'opportunityReference' => null, 'existingBusinessId' => null,
|
||||
'modality' => null, 'investmentRange' => null, 'shareWithProponent' => false], $payload);
|
||||
$canonical['email'] = strtolower(trim($canonical['email']));
|
||||
$canonical['fullName'] = trim($canonical['fullName']);
|
||||
$canonical['message'] = trim($canonical['message']);
|
||||
@@ -25,7 +26,7 @@ final class InterestSubmission
|
||||
$payloadHash = hash_hmac('sha256', json_encode($canonical, JSON_THROW_ON_ERROR), config()->string('app.key'));
|
||||
$keyHash = $key === null ? null : hash('sha256', strtolower($key));
|
||||
|
||||
return DB::transaction(function () use ($keyHash, $payloadHash, $create): InterestRequest {
|
||||
return DB::transaction(function () use ($keyHash, $payloadHash, $create, $canonical): InterestRequest {
|
||||
if ($keyHash !== null) {
|
||||
// Serialise concurrent submissions of this key across all web workers.
|
||||
DB::select('select pg_advisory_xact_lock(250925, hashtext(?))', [$keyHash]);
|
||||
@@ -41,6 +42,10 @@ final class InterestSubmission
|
||||
$interest = $create();
|
||||
$integrationId = (string) Str::uuid();
|
||||
$interest->forceFill(['integration_id' => $integrationId])->save();
|
||||
$this->recordConsent($interest, $integrationId, 'respond_to_interest', config('existing-business.consent_policy_version'));
|
||||
if ($canonical['shareWithProponent'] === true || $canonical['shareWithProponent'] === 1 || $canonical['shareWithProponent'] === '1') {
|
||||
$this->recordConsent($interest, $integrationId, 'share_contact_with_proponent', config('existing-business.sharing_policy_version'));
|
||||
}
|
||||
DB::table('outbox_events')->insert([
|
||||
'source_system' => 'portal-intake',
|
||||
'external_id' => 'ExpressionOfInterestSubmitted:'.$integrationId,
|
||||
@@ -59,4 +64,24 @@ final class InterestSubmission
|
||||
return $interest;
|
||||
});
|
||||
}
|
||||
|
||||
private function recordConsent(InterestRequest $interest, string $correlationId, string $purpose, string $policyVersion): void
|
||||
{
|
||||
DB::table('consents')->insert([
|
||||
'id' => (string) Str::uuid(),
|
||||
'source_system' => 'portal-intake',
|
||||
'external_id' => 'InterestConsent:'.$interest->integration_id.':'.$purpose,
|
||||
'version_no' => 1,
|
||||
'data_classification' => 'confidential',
|
||||
'correlation_id' => $correlationId,
|
||||
'subject_ref' => $interest->reference,
|
||||
'purpose' => $purpose,
|
||||
'status' => 'granted',
|
||||
'granted_at' => now(),
|
||||
'interest_request_id' => $interest->id,
|
||||
'policy_version' => $policyVersion,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Domain\Interests\Enums\InterestStatus;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class InterestWorkflow
|
||||
{
|
||||
/** @var array<string, list<string>> */
|
||||
private const TRANSITIONS = [
|
||||
'received' => ['in_review', 'qualification', 'contacted', 'closed', 'cancelled', 'refused'],
|
||||
'submitted' => ['in_review', 'qualification', 'contacted', 'closed', 'cancelled', 'refused'],
|
||||
'in_review' => ['qualification', 'qualified', 'contacted', 'referred', 'closed', 'cancelled', 'refused'],
|
||||
'reviewed' => ['qualification', 'qualified', 'contacted', 'referred', 'closed', 'cancelled', 'refused'],
|
||||
'qualification' => ['qualified', 'contacted', 'referred', 'closed', 'cancelled', 'refused'],
|
||||
'qualified' => ['contacted', 'contact_accepted', 'due_diligence', 'referred', 'closed', 'cancelled', 'refused'],
|
||||
'contacted' => ['contact_accepted', 'due_diligence', 'negotiation', 'referred', 'closed', 'cancelled', 'refused'],
|
||||
'contact_accepted' => ['due_diligence', 'negotiation', 'closed', 'cancelled', 'refused'],
|
||||
'referred' => ['in_review', 'contacted', 'closed', 'cancelled'],
|
||||
'due_diligence' => ['negotiation', 'closed', 'cancelled', 'refused'],
|
||||
'negotiation' => ['converted', 'closed', 'cancelled', 'refused'],
|
||||
'pending' => ['in_review', 'contacted', 'closed', 'cancelled', 'refused'],
|
||||
'closed' => ['in_review'],
|
||||
'cancelled' => [],
|
||||
'refused' => [],
|
||||
'converted' => [],
|
||||
];
|
||||
|
||||
public function transition(User $actor, InterestRequest $interest, string $status, ?string $note = null, ?string $nextAction = null, ?string $dueAt = null, ?int $assigneeId = null, bool $assignmentProvided = false, bool $actionProvided = false): InterestRequest
|
||||
{
|
||||
if (! in_array($status, array_column(InterestStatus::cases(), 'value'), true)) {
|
||||
throw ValidationException::withMessages(['status' => 'Estado inválido.']);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $interest, $status, $note, $nextAction, $dueAt, $assigneeId, $assignmentProvided, $actionProvided) {
|
||||
$locked = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id);
|
||||
$from = $locked->status;
|
||||
$actionDate = $dueAt ? Carbon::parse($dueAt)->toDateString() : null;
|
||||
$followUpChanged = ($actionProvided && ($locked->next_action !== $nextAction
|
||||
|| $locked->next_action_due_at?->toDateString() !== $actionDate))
|
||||
|| ($assignmentProvided && $locked->assigned_to !== $assigneeId);
|
||||
if ($from !== $status && ! in_array($status, self::TRANSITIONS[$from] ?? [], true)) {
|
||||
throw ValidationException::withMessages(['status' => 'Esta transição não é permitida a partir do estado actual.']);
|
||||
}
|
||||
|
||||
$locked->forceFill([
|
||||
'status' => $status,
|
||||
'reviewed_at' => now(),
|
||||
'reviewed_by' => $actor->id,
|
||||
...($actionProvided ? ['next_action' => $nextAction, 'next_action_due_at' => $dueAt] : []),
|
||||
...($assignmentProvided ? ['assigned_to' => $assigneeId] : []),
|
||||
])->save();
|
||||
|
||||
if ($followUpChanged) {
|
||||
DB::table('tasks')->where('interest_request_id', $locked->id)->where('task_type', 'interest_follow_up')
|
||||
->whereIn('status', ['open', 'in_progress'])->update([
|
||||
'status' => 'cancelled', 'completed_at' => now(), 'outcome' => 'superseded', 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($followUpChanged && $locked->next_action && $locked->next_action_due_at) {
|
||||
$correlationId = (string) Str::uuid();
|
||||
$assignee = $assignmentProvided ? $assigneeId : $locked->assigned_to;
|
||||
$externalId = 'InterestFollowUp:'.$locked->id.':'.hash('sha256', $locked->next_action.'|'.$locked->next_action_due_at.'|'.($assignee ?? ''));
|
||||
DB::table('tasks')->insertOrIgnore([
|
||||
'source_system' => 'portal-interest',
|
||||
'external_id' => $externalId,
|
||||
'version_no' => 1,
|
||||
'data_classification' => 'confidential',
|
||||
'correlation_id' => $correlationId,
|
||||
'assignee_user_id' => $assignee,
|
||||
'interest_request_id' => $locked->id,
|
||||
'task_type' => 'interest_follow_up',
|
||||
'title' => mb_substr($locked->next_action, 0, 200),
|
||||
'status' => 'open',
|
||||
'priority' => 3,
|
||||
'due_at' => Carbon::parse($locked->next_action_due_at)->endOfDay(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($from !== $status) {
|
||||
$correlationId = (string) Str::uuid();
|
||||
DB::table('business_workflow_transitions')->insert([
|
||||
'id' => (string) Str::uuid(),
|
||||
'interest_request_id' => $locked->id,
|
||||
'from_status' => $from,
|
||||
'to_status' => $status,
|
||||
'actor_id' => $actor->id,
|
||||
'reason' => $note ? Crypt::encryptString($note) : null,
|
||||
'correlation_id' => $correlationId,
|
||||
'metadata' => json_encode(['source' => 'management-interest'], JSON_THROW_ON_ERROR),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $locked->refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,9 @@ class InvestmentCatalogue
|
||||
/** @return array<string,mixed> */
|
||||
public function filters(Request $request): array
|
||||
{
|
||||
return $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
||||
$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'],
|
||||
'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'],
|
||||
@@ -28,6 +30,9 @@ class InvestmentCatalogue
|
||||
'currency' => ['nullable', 'required_with:min_amount,max_amount', 'in:MZN,USD,EUR,ZAR'],
|
||||
'before' => ['nullable', 'date_format:Y-m-d'], 'sort' => ['nullable', 'in:recent,title,amount_asc,amount_desc'],
|
||||
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
app(InvestmentGeography::class)->selection($filters);
|
||||
|
||||
return $filters;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,6 +42,14 @@ class InvestmentCatalogue
|
||||
public function query(array $filters): Builder
|
||||
{
|
||||
$query = Opportunity::published()->with('sector:id,name,slug');
|
||||
if (! empty($filters['opportunity_id'])) {
|
||||
$query->whereKey($filters['opportunity_id']);
|
||||
}
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->whereIn('primary_territory_id', $ids);
|
||||
}
|
||||
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')
|
||||
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('z.category', $filters['dimension'])->select('mapping.opportunity_id'));
|
||||
@@ -147,6 +160,7 @@ class InvestmentCatalogue
|
||||
$result['zones'] = app(InvestmentZones::class)->links()->join('investment_item_opportunities as m', 'm.item_id', '=', 'zl.item_id')
|
||||
->join('investment_zones as z', 'z.id', '=', 'zl.zone_id')->where('m.opportunity_id', $id)
|
||||
->get(['z.id', 'z.name', 'z.category', 'zl.association_type', 'zl.source_reference', 'zl.valid_from', 'zl.valid_until']);
|
||||
$result['primary_territory_path'] = app(InvestmentGeography::class)->path(DB::table('opportunities')->where('id', $id)->value('primary_territory_id'));
|
||||
|
||||
return $result;
|
||||
}
|
||||
@@ -157,14 +171,46 @@ class InvestmentCatalogue
|
||||
*/
|
||||
public function map(array $filters): array
|
||||
{
|
||||
$ids = $this->query($filters)->reorder()->select('opportunities.id');
|
||||
$points = DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')
|
||||
->join('geo_geometries as shape', 'shape.geo_location_id', '=', 'g.id')->join('opportunities as o', 'o.id', '=', 'l.opportunity_id')
|
||||
$records = $this->query($filters)->limit(1000)->get();
|
||||
$total = $this->query($filters)->reorder()->count();
|
||||
$ids = $records->pluck('id');
|
||||
$points = DB::table('opportunities as o')->join('geo_locations as g', function ($join) {
|
||||
$join->on('g.id', '=', 'o.primary_territory_id')->orWhereExists(fn ($q) => $q->selectRaw('1')->from('opportunity_locations as l')->whereColumn('l.opportunity_id', 'o.id')->whereColumn('l.geo_location_id', 'g.id'));
|
||||
})->join('geo_geometries as shape', 'shape.geo_location_id', '=', 'g.id')
|
||||
->whereIn('o.id', $ids)->where('g.data_classification', 'public')->where('shape.data_classification', 'public')
|
||||
->whereNull('g.deleted_at')->whereNull('shape.deleted_at')->where('shape.geometry_type', 'point')->limit(1000)
|
||||
->get(['o.id', 'o.title', 'o.slug', 'g.name', DB::raw('ST_AsGeoJSON(shape.geom) as geometry')]);
|
||||
->where('g.location_type', 'site')->whereNull('g.deleted_at')->whereNull('shape.deleted_at')->where('shape.geometry_type', 'point')
|
||||
->whereRaw("NOT EXISTS (WITH RECURSIVE parents AS (
|
||||
SELECT id,parent_id,deleted_at,data_classification,ARRAY[id] AS visited,false AS cycle FROM geo_locations WHERE id=g.id
|
||||
UNION ALL SELECT p.id,p.parent_id,p.deleted_at,p.data_classification,a.visited||p.id,p.id=ANY(a.visited)
|
||||
FROM geo_locations p JOIN parents a ON p.id=a.parent_id WHERE NOT a.cycle
|
||||
) SELECT 1 FROM parents WHERE deleted_at IS NOT NULL OR data_classification<>'public' OR cycle)")
|
||||
->whereRaw('ST_IsValid(shape.geom) AND NOT ST_IsEmpty(shape.geom) AND ST_SRID(shape.geom)=4326')
|
||||
->orderBy('o.id')->orderByRaw("CASE WHEN g.source_system='investment-site-editor' THEN 0 ELSE 1 END")->orderBy('g.id')->orderBy('shape.id')
|
||||
->get(['o.id', 'g.name', DB::raw('ST_AsGeoJSON(shape.geom) as geometry')])->unique('id')->keyBy('id');
|
||||
$relations = [];
|
||||
foreach (['clusters', 'corridors', 'projects'] as $relation) {
|
||||
[$foreign, $table] = self::RELATIONS[$relation];
|
||||
$relations[$relation] = DB::table('opportunity_'.$relation.' as l')->join($table.' as t', 't.id', '=', 'l.'.$foreign)
|
||||
->whereIn('l.opportunity_id', $ids)->whereNull('t.deleted_at')
|
||||
->whereIn('t.id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->select($foreign))
|
||||
->get(['l.opportunity_id', 't.name'])->groupBy('opportunity_id');
|
||||
}
|
||||
$features = $missing = [];
|
||||
foreach ($records as $record) {
|
||||
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
|
||||
'location' => trim($record->province.' '.$record->district), 'url' => '/oportunidades/'.$record->slug];
|
||||
foreach ($relations as $relation => $groups) {
|
||||
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
|
||||
}
|
||||
if ($point = $points->get($record->id)) {
|
||||
$features[] = ['type' => 'Feature', 'geometry' => json_decode($point->geometry, true), 'properties' => [...$properties, 'location' => trim($properties['location'].' — '.$point->name)]];
|
||||
} else {
|
||||
$missing[] = [...$properties, 'reason' => 'missing_public_site_coordinates'];
|
||||
}
|
||||
}
|
||||
|
||||
return ['type' => 'FeatureCollection', 'limit' => 1000, 'features' => $points->map(fn ($p) => ['type' => 'Feature',
|
||||
'geometry' => json_decode($p->geometry, true), 'properties' => ['id' => $p->id, 'title' => $p->title, 'location' => $p->name, 'url' => '/oportunidades/'.$p->slug]])->all()];
|
||||
return ['type' => 'FeatureCollection', 'limit' => 1000, 'matched_count' => $total, 'truncated' => $total > $records->count(),
|
||||
'georeferenced_count' => count($features), 'unlocated' => $missing, 'features' => $features,
|
||||
'complete' => $total === count($features)];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class InvestmentGeography
|
||||
{
|
||||
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
||||
|
||||
public function publicReferences(): Builder
|
||||
{
|
||||
return DB::table('geo_locations')->whereNull('deleted_at')->where('data_classification', 'public')
|
||||
->whereRaw("NOT EXISTS (WITH RECURSIVE ancestors AS (
|
||||
SELECT id,parent_id,deleted_at,data_classification,ARRAY[id] AS visited,false AS cycle FROM geo_locations a WHERE a.id=geo_locations.id
|
||||
UNION ALL SELECT a.id,a.parent_id,a.deleted_at,a.data_classification,p.visited||a.id,a.id=ANY(p.visited)
|
||||
FROM geo_locations a JOIN ancestors p ON a.id=p.parent_id WHERE NOT p.cycle
|
||||
) SELECT 1 FROM ancestors WHERE deleted_at IS NOT NULL OR data_classification<>'public' OR cycle)")
|
||||
->where(function ($query) {
|
||||
$query->where(function ($workbook) {
|
||||
$workbook->where('source_system', 'cartografia-workbook')
|
||||
->where('external_id', 'like', '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:%');
|
||||
})->orWhereIn('id', app(TerritorialRegistry::class)->published()->select('g.id'));
|
||||
});
|
||||
}
|
||||
|
||||
public function references(bool $management = false): Builder
|
||||
{
|
||||
return $management
|
||||
? DB::table('geo_locations')->whereNull('deleted_at')->whereIn('data_classification', ['public', 'internal'])
|
||||
: $this->publicReferences();
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return list<\stdClass>
|
||||
*/
|
||||
public function selection(array $input, bool $management = false): array
|
||||
{
|
||||
$path = [];
|
||||
$parent = null;
|
||||
$gap = false;
|
||||
foreach (self::FIELDS as $field => $type) {
|
||||
if (empty($input[$field])) {
|
||||
$gap = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
$node = $this->references($management)->where('id', $input[$field])->where('location_type', $type)->first(['id', 'name', 'parent_id', 'location_type']);
|
||||
if ($gap || ! $node || ($parent && $node->parent_id !== $parent)) {
|
||||
throw ValidationException::withMessages([$field => 'Seleccione a localização dentro da hierarquia indicada.']);
|
||||
}
|
||||
$path[] = $node;
|
||||
$parent = $node->id;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function descendants(string $id): array
|
||||
{
|
||||
$rows = DB::select('WITH RECURSIVE tree AS (
|
||||
SELECT id, ARRAY[id] AS visited FROM geo_locations WHERE id=? AND deleted_at IS NULL
|
||||
UNION ALL SELECT g.id, tree.visited||g.id FROM geo_locations g JOIN tree ON g.parent_id=tree.id
|
||||
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());
|
||||
}
|
||||
|
||||
/** @return list<\stdClass> */
|
||||
public function path(?string $id, bool $management = false): array
|
||||
{
|
||||
$path = [];
|
||||
for ($i = 0; $id && $i < 5; $i++) {
|
||||
$query = $management ? DB::table('geo_locations') : $this->publicReferences();
|
||||
$node = $query->where('id', $id)->first(['id', 'name', 'parent_id', 'location_type', 'deleted_at']);
|
||||
if (! $node) {
|
||||
return [];
|
||||
}
|
||||
if ($node->location_type !== 'country') {
|
||||
array_unshift($path, $node);
|
||||
}
|
||||
$id = $node->parent_id;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
interface BusinessRepository
|
||||
{
|
||||
/** @return Builder<ExistingBusiness> */
|
||||
public function query(): Builder;
|
||||
|
||||
public function find(string $id, bool $forUpdate = false): ExistingBusiness;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
final class CompatibilityBackfill
|
||||
{
|
||||
/** @return array<string, int> */
|
||||
public function run(int $batchSize = 100): array
|
||||
{
|
||||
$counts = [];
|
||||
foreach (['identity' => ['users', 'identity_links', 'user_id'], 'sector' => ['sectors', 'sector_links', 'sector_id'],
|
||||
'business' => ['existing_businesses', 'business_links', 'legacy_business_id']] as $domain => [$source, $target, $key]) {
|
||||
// Start again on each invocation to detect edits behind a previous checkpoint.
|
||||
$last = null;
|
||||
$processed = 0;
|
||||
do {
|
||||
$batch = DB::transaction(function () use ($domain, $source, $target, $key, $last, $processed, $batchSize) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(290926,170004)');
|
||||
$query = DB::table('public.'.$source)->orderBy('id')->limit($batchSize)->lockForUpdate();
|
||||
if ($last !== null) {
|
||||
$query->where('id', '>', $last);
|
||||
}
|
||||
$rows = $query->get();
|
||||
$checksums = [];
|
||||
foreach ($rows as $row) {
|
||||
$checksum = hash('sha256', json_encode((array) $row, JSON_THROW_ON_ERROR));
|
||||
$checksums[] = $checksum;
|
||||
$stableId = (string) Uuid::uuid5(Uuid::NAMESPACE_URL, 'investmoz:'.$domain.':'.$row->id);
|
||||
$data = ['id' => $stableId, $key => $row->id, 'source_system' => 'public.'.$source,
|
||||
'source_checksum' => $checksum, 'status' => 'pending'];
|
||||
if ($domain === 'sector') {
|
||||
$data['canonical_sector_id'] = $stableId;
|
||||
$data['source_code'] = $row->slug;
|
||||
$data['status'] = $row->is_active && $row->deleted_at === null ? 'active' : 'pending';
|
||||
}
|
||||
$existing = DB::table('mne.'.$target)->where($key, $row->id)->first();
|
||||
if (! $existing) {
|
||||
DB::table('mne.'.$target)->insert($data);
|
||||
} elseif ($existing->source_checksum !== $checksum) {
|
||||
// Changed sources invalidate previous reconciliation; never activate by inference.
|
||||
DB::table('mne.'.$target)->where($key, $row->id)->update(['source_checksum' => $checksum, 'status' => 'pending']);
|
||||
}
|
||||
if ($domain !== 'sector' && (! $existing || $existing->status !== 'active' || $existing->source_checksum !== $checksum)) {
|
||||
DB::table('mne.compatibility_rejections')->upsert([[
|
||||
'id' => $stableId, 'domain' => $domain, 'source_key' => (string) $row->id,
|
||||
'code' => 'CANONICAL_MAPPING_REQUIRED', 'cause' => 'Explicit canonical mapping and reconciliation required',
|
||||
'resolved_at' => null, 'resolution' => null,
|
||||
]], ['domain', 'source_key', 'code'], ['cause', 'resolved_at', 'resolution']);
|
||||
}
|
||||
}
|
||||
if ($rows->isNotEmpty() || $processed === 0) {
|
||||
DB::table('mne.compatibility_checkpoints')->updateOrInsert(['domain' => $domain], [
|
||||
'last_key' => $rows->isEmpty() ? $last : (string) $rows->last()->id,
|
||||
'processed' => $processed + $rows->count(), 'checksum' => hash('sha256', implode('', $checksums)), 'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $rows;
|
||||
});
|
||||
$processed += $batch->count();
|
||||
if ($batch->isNotEmpty()) {
|
||||
$last = $batch->last()->id;
|
||||
}
|
||||
} while ($batch->count() === $batchSize);
|
||||
$counts[$domain] = $processed;
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use App\Jobs\CompareMneBusiness;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
final class CompatibilityShadow
|
||||
{
|
||||
/** Invoke only after authorization; optional comparison must never affect the response. */
|
||||
public function schedule(string $businessId): void
|
||||
{
|
||||
if (! config('existing-business.compatibility_shadow', false)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
$control = DB::transaction(fn () => DB::table('mne.compatibility_controls')->where('capability', 'shadow')->first());
|
||||
if (! $control || ! $control->enabled || (hexdec(substr(hash('sha256', $businessId), 0, 6)) % 100) >= $control->percentage) {
|
||||
return;
|
||||
}
|
||||
$connection = (string) config('existing-business.shadow_queue', 'database');
|
||||
if (config('queue.connections.'.$connection.'.driver') !== 'database') {
|
||||
Log::info('mne.compatibility.shadow', ['outcome' => 'async_queue_required']);
|
||||
|
||||
return;
|
||||
}
|
||||
CompareMneBusiness::dispatch($businessId)->onConnection($connection)->onQueue('mne-shadow')->afterCommit();
|
||||
} catch (\Throwable) {
|
||||
Log::info('mne.compatibility.shadow', ['outcome' => 'dispatch_error']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
final class CompatibleBusinessRepository implements BusinessRepository
|
||||
{
|
||||
public function __construct(private LegacyBusinessRepository $legacy) {}
|
||||
|
||||
/** @return Builder<ExistingBusiness> */
|
||||
public function query(): Builder
|
||||
{
|
||||
return $this->legacy->query();
|
||||
}
|
||||
|
||||
public function find(string $id, bool $forUpdate = false): ExistingBusiness
|
||||
{
|
||||
// No configuration can transfer writes or bypass existing policies.
|
||||
return $this->legacy->find($id, $forUpdate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class IdentityResolver
|
||||
{
|
||||
public function resolve(int $userId): ?string
|
||||
{
|
||||
$id = DB::table('mne.identity_links as l')->join('mne.parties as p', 'p.id', '=', 'l.party_id')
|
||||
->join('public.users as u', 'u.id', '=', 'l.user_id')
|
||||
->where('l.user_id', $userId)->where('l.status', 'active')->where('p.party_type', 'person')
|
||||
->whereNull('p.deleted_at')->where('l.valid_from', '<=', now())
|
||||
->where(fn ($q) => $q->whereNull('l.valid_until')->orWhere('l.valid_until', '>', now()))
|
||||
->value('l.party_id');
|
||||
|
||||
return is_string($id) ? $id : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use App\Models\ExistingBusiness;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
final class LegacyBusinessRepository implements BusinessRepository
|
||||
{
|
||||
/** @return Builder<ExistingBusiness> */
|
||||
public function query(): Builder
|
||||
{
|
||||
return ExistingBusiness::query();
|
||||
}
|
||||
|
||||
public function find(string $id, bool $forUpdate = false): ExistingBusiness
|
||||
{
|
||||
$query = $this->query()->whereKey($id);
|
||||
if ($forUpdate) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
return $query->firstOrFail();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Read-only comparison adapter. Does not hydrate a legacy model or grant authority. */
|
||||
final class MneBusinessRepository
|
||||
{
|
||||
/** @return array<string, mixed>|null */
|
||||
public function comparison(string $legacyId): ?array
|
||||
{
|
||||
$row = DB::table('mne.business_links as l')
|
||||
->join('mne.existing_businesses as b', 'b.id', '=', 'l.canonical_business_id')
|
||||
->join('mne.business_modalities as m', 'm.id', '=', 'b.modality_id')
|
||||
->join('mne.workflow_states as s', 's.id', '=', 'b.status_id')
|
||||
->join('mne.data_classifications as c', 'c.id', '=', 'b.confidentiality_id')
|
||||
->where('l.legacy_business_id', $legacyId)->where('l.status', 'active')
|
||||
->where('l.valid_from', '<=', now())->where(fn ($q) => $q->whereNull('l.valid_until')->orWhere('l.valid_until', '>', now()))
|
||||
->whereNull('b.deleted_at')->first(['b.public_code as code', 'm.code as modality', 's.code as status',
|
||||
'c.code as classification', 'b.version as version_no']);
|
||||
|
||||
return $row ? (array) $row : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Mne;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class SectorResolver
|
||||
{
|
||||
public const VERSION = 1;
|
||||
|
||||
public function resolve(int $legacyId): ?string
|
||||
{
|
||||
$id = DB::table('mne.sector_links as l')->join('public.sectors as s', 's.id', '=', 'l.sector_id')
|
||||
->where('l.sector_id', $legacyId)->where('l.resolver_version', self::VERSION)
|
||||
->where('l.status', 'active')->where('s.is_active', true)->whereNull('s.deleted_at')
|
||||
->whereColumn('l.source_code', 's.slug')->where('l.valid_from', '<=', now())
|
||||
->where(fn ($q) => $q->whereNull('l.valid_until')->orWhere('l.valid_until', '>', now()))
|
||||
->value('l.canonical_sector_id');
|
||||
|
||||
return is_string($id) ? $id : null;
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ class PortalAudit
|
||||
$record->setRawAttributes($locked->getAttributes(), true);
|
||||
}
|
||||
// Exclude free text and personal data from the immutable event payload.
|
||||
$fields = ['version_no', 'status', 'is_active', 'is_featured', 'sort_order', 'sector_id', 'maturity_level',
|
||||
$fields = ['primary_territory_id', 'territory_version', 'version_no', 'status', 'is_active', 'is_featured', 'sort_order', 'sector_id', 'maturity_level',
|
||||
'estimated_investment_amount', 'estimated_investment_currency', 'owner_user_id', 'assignee_user_id', 'due_at',
|
||||
'cluster_id', 'project_id', 'corridor_id', 'dossier_id', 'interest_request_id', 'publication_status', 'editor_id', 'reviewer_id', 'role', 'stage', 'value_chain_id', 'from_value_chain_id', 'to_value_chain_id', 'link_type', 'deleted_at'];
|
||||
$before = array_intersect_key($record->getAttributes(), array_flip($fields));
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Jobs\RunSimulation;
|
||||
use App\Models\Simulation;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
final class SimulationExecution
|
||||
{
|
||||
/**
|
||||
* @param array{base: int|float|string, rate: int|float|string, reduction: int|float|string, organization_id?: string|null} $data
|
||||
* @return array{simulation: Simulation, token: string|null, replayed: bool}
|
||||
*/
|
||||
public function create(array $data, ?int $actorId, ?string $organizationId, ?string $token, string $key): array
|
||||
{
|
||||
$tokenHash = $actorId === null ? hash_hmac('sha256', (string) $token, (string) config('app.key')) : null;
|
||||
$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];
|
||||
ksort($payload);
|
||||
$payloadHash = hash('sha256', json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actorId, $organizationId, $token, $tokenHash, $scopeHash, $keyHash, $payloadHash, $payload): array {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
DB::select('select pg_advisory_xact_lock(261001, hashtext(?))', [$scopeHash.$keyHash]);
|
||||
$receipt = DB::table('simulation_idempotency')->where('scope_hash', $scopeHash)->where('key_hash', $keyHash)->first();
|
||||
if ($receipt) {
|
||||
if (! hash_equals($receipt->payload_hash, $payloadHash)) {
|
||||
throw new HttpException(409, 'Idempotency-Key já foi utilizada com outros parâmetros.');
|
||||
}
|
||||
|
||||
return ['simulation' => Simulation::with(['scenarios', 'reports'])->whereKey((string) $receipt->simulation_id)->firstOrFail(), 'token' => null, 'replayed' => true];
|
||||
}
|
||||
|
||||
$plainToken = $actorId === null ? $token : null;
|
||||
$tokenHash = $actorId === null ? hash_hmac('sha256', $plainToken, (string) config('app.key')) : null;
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$id = (string) Str::uuid();
|
||||
$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],
|
||||
]);
|
||||
$scenarioId = (string) Str::uuid();
|
||||
DB::table('simulation_scenarios')->insert([
|
||||
'id' => $scenarioId, 'simulation_id' => $id, 'code' => 'baseline', 'label' => 'Cenário base', 'version_no' => 1,
|
||||
'parameters' => json_encode($payload, JSON_THROW_ON_ERROR), 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
$jobId = (string) Str::uuid();
|
||||
DB::table('simulation_jobs')->insert(['id' => $jobId, 'simulation_id' => $id, 'job_type' => 'execute', 'status' => 'pending', 'created_at' => now(), 'updated_at' => now()]);
|
||||
DB::table('simulation_idempotency')->insert([
|
||||
'scope_hash' => $scopeHash, 'key_hash' => $keyHash, 'payload_hash' => $payloadHash,
|
||||
'simulation_id' => $id, 'response_snapshot' => json_encode(['simulation_id' => $id], JSON_THROW_ON_ERROR), 'created_at' => now(),
|
||||
]);
|
||||
DB::table('simulation_audit_events')->insert([
|
||||
'simulation_id' => $id, 'actor_user_id' => $actorId, 'action' => 'simulation.created',
|
||||
'correlation_id' => $id, 'data' => json_encode(['status' => 'queued', 'scenario_count' => 1], JSON_THROW_ON_ERROR), 'occurred_at' => now(),
|
||||
]);
|
||||
|
||||
$simulation->load(['scenarios', 'reports']);
|
||||
|
||||
RunSimulation::dispatch($id, $actorId, $tokenHash)->afterCommit();
|
||||
|
||||
return ['simulation' => $simulation, 'token' => $plainToken, 'replayed' => false];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function find(string $id, Request $request): Simulation
|
||||
{
|
||||
return DB::transaction(function () use ($id, $request): Simulation {
|
||||
$this->setContext($request->user()?->id, $this->tokenHash($request));
|
||||
|
||||
return Simulation::with(['scenarios', 'reports'])->whereNull('deleted_at')->findOrFail($id);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array{label: string, base: int|float|string, rate: int|float|string, reduction: int|float|string} $data */
|
||||
public function updateScenario(string $id, string $scenarioId, array $data, Request $request): Simulation
|
||||
{
|
||||
return DB::transaction(function () use ($id, $scenarioId, $data, $request): Simulation {
|
||||
$this->setContext($request->user()?->id, $this->tokenHash($request));
|
||||
$simulation = Simulation::whereNull('deleted_at')->lockForUpdate()->findOrFail($id);
|
||||
$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']];
|
||||
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(),
|
||||
]);
|
||||
$simulation->update(['version_no' => $simulation->version_no + 1, 'status' => 'queued', 'input_snapshot' => $parameters, 'result_snapshot' => null, 'error_code' => null]);
|
||||
DB::table('simulation_jobs')->where('simulation_id', $id)->where('job_type', 'execute')->update([
|
||||
'status' => 'pending', 'attempts' => 0, 'available_at' => now(), 'started_at' => null, 'finished_at' => null, 'error_code' => null, 'updated_at' => now(),
|
||||
]);
|
||||
DB::table('simulation_audit_events')->insert([
|
||||
'simulation_id' => $id, 'actor_user_id' => $request->user()?->id, 'action' => 'scenario.updated', 'correlation_id' => $id,
|
||||
'data' => json_encode(['scenario_id' => $scenarioId, 'version_no' => $scenario->version_no + 1], JSON_THROW_ON_ERROR), 'occurred_at' => now(),
|
||||
]);
|
||||
RunSimulation::dispatch($id, $simulation->owner_user_id, $simulation->anonymous_token_hash)->afterCommit();
|
||||
|
||||
return $simulation->refresh()->load(['scenarios', 'reports']);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function tokenHash(Request $request): ?string
|
||||
{
|
||||
$token = $request->header('X-Simulation-Token');
|
||||
|
||||
return is_string($token) && $token !== '' ? hash_hmac('sha256', $token, (string) config('app.key')) : null;
|
||||
}
|
||||
|
||||
public 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 ?? '')]);
|
||||
}
|
||||
|
||||
private function requireMatch(Request $request, Simulation $simulation): void
|
||||
{
|
||||
$provided = $request->header('If-Match');
|
||||
if (! $provided) {
|
||||
throw new HttpException(428, 'If-Match é obrigatório.');
|
||||
}
|
||||
if (! hash_equals($this->etag($simulation), trim($provided))) {
|
||||
throw new HttpException(412, 'A simulação foi alterada desde a última leitura.');
|
||||
}
|
||||
}
|
||||
|
||||
public function etag(Simulation $simulation): string
|
||||
{
|
||||
return '"sim-'.$simulation->id.'-v'.$simulation->version_no.'"';
|
||||
}
|
||||
|
||||
public function authorizeOrganization(?int $actorId, ?string $organizationId): void
|
||||
{
|
||||
if ($organizationId === null) {
|
||||
return;
|
||||
}
|
||||
abort_unless($actorId !== null && DB::table('memberships')->where('user_id', $actorId)->where('organization_id', $organizationId)
|
||||
->whereNull('deleted_at')->whereIn('role', ['admin', 'manager', 'officer'])->exists(), 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SimulationFormDraft;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
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 */
|
||||
public function create(array $data, Request $request, string $key): array
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
$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 {
|
||||
$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 ($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.');
|
||||
|
||||
return ['draft' => $draft, 'replayed' => true];
|
||||
}
|
||||
throw new HttpException(409, 'Já existe um rascunho activo. Carregue-o antes de guardar novas alterações.');
|
||||
}
|
||||
|
||||
$draft = SimulationFormDraft::query()->create([
|
||||
'id' => (string) Str::uuid(), 'owner_user_id' => $actorId, 'anonymous_token_hash' => $tokenHash,
|
||||
'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']),
|
||||
]);
|
||||
|
||||
return ['draft' => $draft, 'replayed' => false];
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @param array{personal_snapshot: array<string,mixed>, economic_snapshot: array<string,mixed>} $data */
|
||||
public function update(string $id, array $data, Request $request): SimulationFormDraft
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
|
||||
return DB::transaction(function () use ($id, $data, $request, $actorId, $tokenHash): SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
$draft = SimulationFormDraft::query()->whereNull('deleted_at')->lockForUpdate()->findOrFail($id);
|
||||
$this->requireMatch($request, $draft);
|
||||
$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,
|
||||
]);
|
||||
|
||||
return $draft->refresh();
|
||||
}, 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 ($actorId === null ? $query->where('anonymous_token_hash', $tokenHash) : $query->where('owner_user_id', $actorId))->first();
|
||||
});
|
||||
}
|
||||
|
||||
public function find(string $id, Request $request): SimulationFormDraft
|
||||
{
|
||||
[$actorId, $tokenHash] = $this->context($request);
|
||||
|
||||
return DB::transaction(function () use ($id, $actorId, $tokenHash): SimulationFormDraft {
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
|
||||
return SimulationFormDraft::query()->whereNull('deleted_at')->findOrFail($id);
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(string $id, Request $request): void
|
||||
{
|
||||
[$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);
|
||||
$this->requireMatch($request, $draft);
|
||||
$draft->update(['deleted_at' => now()]);
|
||||
}, 3);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function present(SimulationFormDraft $draft): array
|
||||
{
|
||||
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),
|
||||
'updated_at' => $draft->updated_at,
|
||||
];
|
||||
}
|
||||
|
||||
public function etag(SimulationFormDraft $draft): string
|
||||
{
|
||||
return '"sfd-'.$draft->id.'-v'.$draft->version_no.'"';
|
||||
}
|
||||
|
||||
/** @return array{0:int|null,1:string|null} */
|
||||
private function context(Request $request): array
|
||||
{
|
||||
$actorId = $request->user()?->id;
|
||||
$token = $request->header('X-Simulation-Token');
|
||||
abort_unless($actorId !== null || (is_string($token) && strlen($token) >= 32 && strlen($token) <= 256), 422,
|
||||
'X-Simulation-Token opaco é obrigatório para um rascunho anónimo.');
|
||||
|
||||
return [$actorId, $actorId === null ? hash_hmac('sha256', $token, (string) config('app.key')) : null];
|
||||
}
|
||||
|
||||
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 ?? '')]);
|
||||
}
|
||||
|
||||
private function requireMatch(Request $request, SimulationFormDraft $draft): void
|
||||
{
|
||||
$provided = $request->header('If-Match');
|
||||
if (! $provided) {
|
||||
throw new HttpException(428, 'If-Match é obrigatório.');
|
||||
}
|
||||
if (! hash_equals($this->etag($draft), trim($provided))) {
|
||||
throw new HttpException(412, 'O rascunho foi alterado desde a última leitura.');
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** Offline structural validation. This never approves a source or writes territories. */
|
||||
final class TerritorialCsvAudit
|
||||
{
|
||||
public const HEADERS = ['province_code', 'province_name', 'district_code', 'district_name', 'admin_post_code', 'admin_post_name', 'locality_code', 'locality_name', 'locality_type', 'latitude', 'longitude'];
|
||||
|
||||
/** @param list<string> $provinceCodes
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function inspect(string $path, array $provinceCodes): array
|
||||
{
|
||||
if (! is_file($path) || ! is_readable($path) || filesize($path) > 20 * 1024 * 1024) {
|
||||
throw new RuntimeException('CSV inacessível ou superior a 20 MiB.');
|
||||
}
|
||||
$bytes = file_get_contents($path);
|
||||
if ($bytes === false || ! mb_check_encoding($bytes, 'UTF-8') || str_contains($bytes, "\0")) {
|
||||
throw new RuntimeException('O CSV deve ser UTF-8 sem bytes nulos.');
|
||||
}
|
||||
// Parse the exact bytes hashed, avoiding a second read of a changing input.
|
||||
$stream = fopen('php://temp', 'w+');
|
||||
if ($stream === false) {
|
||||
throw new RuntimeException('Não foi possível preparar a leitura.');
|
||||
}
|
||||
fwrite($stream, preg_replace('/^\xEF\xBB\xBF/', '', $bytes) ?? $bytes);
|
||||
rewind($stream);
|
||||
try {
|
||||
if (fgetcsv($stream, null, ';', '"', '') !== self::HEADERS) {
|
||||
throw new RuntimeException('Cabeçalho inválido: usar o contrato INE com separador ponto e vírgula.');
|
||||
}
|
||||
$errors = $seen = $names = $totals = [];
|
||||
$duplicates = $count = 0;
|
||||
while (($values = fgetcsv($stream, null, ';', '"', '')) !== false) {
|
||||
$count++;
|
||||
if ($count > 50000) {
|
||||
throw new RuntimeException('O CSV excede 50.000 registos.');
|
||||
}
|
||||
$issues = [];
|
||||
if (count($values) !== count(self::HEADERS)) {
|
||||
$errors[] = ['record' => $count + 1, 'issues' => ['column_count']];
|
||||
|
||||
continue;
|
||||
}
|
||||
$row = array_combine(self::HEADERS, array_map(fn ($v) => trim((string) $v), $values));
|
||||
foreach ($row as $field => $value) {
|
||||
if (mb_strlen($value) > 255 || preg_match('/[\x00-\x1F\x7F]/', $value)) {
|
||||
$issues[] = 'invalid_field:'.$field;
|
||||
}
|
||||
}
|
||||
if (! preg_match('/^[0-9]{2}$/D', $row['province_code']) || ! in_array($row['province_code'], $provinceCodes, true)) {
|
||||
$issues[] = 'unknown_province';
|
||||
}
|
||||
foreach (['province', 'district', 'admin_post', 'locality'] as $kind) {
|
||||
$code = $row[$kind.'_code'];
|
||||
$name = $row[$kind.'_name'];
|
||||
if (($kind === 'province' || $kind === 'district' || $code !== '') && $name === '') {
|
||||
$issues[] = 'missing_name:'.$kind;
|
||||
}
|
||||
if (($kind === 'province' || $kind === 'district' || $name !== '') && $code === '') {
|
||||
$issues[] = 'missing_code:'.$kind;
|
||||
}
|
||||
if ($code === '') {
|
||||
continue;
|
||||
}
|
||||
if (! preg_match('/^[0-9]+$/D', $code)) {
|
||||
$issues[] = 'invalid_code:'.$kind;
|
||||
}
|
||||
$parent = match ($kind) {
|
||||
'province' => 'MZ', 'district' => $row['province_code'],
|
||||
'admin_post' => $row['district_code'], default => $row['admin_post_code'],
|
||||
};
|
||||
$identity = $kind.':'.$code;
|
||||
$definition = [$parent, $name];
|
||||
if ($kind === 'locality') {
|
||||
$definition = [...$definition, $row['locality_type'], $row['latitude'], $row['longitude']];
|
||||
}
|
||||
if (isset($seen[$identity]) && $seen[$identity] !== $definition) {
|
||||
$issues[] = 'conflicting_code:'.$kind;
|
||||
}
|
||||
$seen[$identity] ??= $definition;
|
||||
$nameKey = $kind.':'.$parent.':'.mb_strtolower($name);
|
||||
if (isset($names[$nameKey]) && $names[$nameKey] !== $code) {
|
||||
$issues[] = 'ambiguous_name:'.$kind;
|
||||
}
|
||||
$names[$nameKey] ??= $code;
|
||||
$totals[$row['province_code']][$kind][$code] = true;
|
||||
}
|
||||
if ($row['locality_code'] !== '' && $row['admin_post_code'] === '') {
|
||||
$issues[] = 'locality_requires_reviewed_parent_exception';
|
||||
}
|
||||
if (($row['latitude'] === '') !== ($row['longitude'] === '')) {
|
||||
$issues[] = 'incomplete_coordinates';
|
||||
}
|
||||
foreach (['latitude' => 90, 'longitude' => 180] as $field => $bound) {
|
||||
if ($row[$field] !== '' && (! preg_match('/^-?[0-9]+(?:\.[0-9]+)?$/D', $row[$field]) || abs((float) $row[$field]) > $bound)) {
|
||||
$issues[] = 'invalid_coordinate:'.$field;
|
||||
}
|
||||
}
|
||||
if ($row['locality_code'] === '' && ($row['latitude'] !== '' || $row['longitude'] !== '' || $row['locality_type'] !== '')) {
|
||||
$issues[] = 'locality_metadata_without_locality';
|
||||
}
|
||||
$fingerprint = hash('sha256', json_encode($row, JSON_THROW_ON_ERROR));
|
||||
if (isset($seen['row:'.$fingerprint])) {
|
||||
$duplicates++;
|
||||
}
|
||||
$seen['row:'.$fingerprint] = [];
|
||||
if ($issues !== []) {
|
||||
$errors[] = ['record' => $count + 1, 'issues' => array_values(array_unique($issues))];
|
||||
}
|
||||
}
|
||||
if ($count === 0) {
|
||||
$errors[] = ['record' => 1, 'issues' => ['empty_dataset']];
|
||||
}
|
||||
ksort($totals);
|
||||
$counts = [];
|
||||
foreach ($totals as $province => $kinds) {
|
||||
$counts[$province] = array_map('count', $kinds);
|
||||
}
|
||||
|
||||
return ['schema_version' => 1, 'sha256' => hash('sha256', $bytes), 'encoding' => 'UTF-8',
|
||||
'delimiter' => ';', 'coordinate_crs' => 'EPSG:4326', 'records' => $count,
|
||||
'duplicate_records' => $duplicates, 'rejected_records' => count($errors),
|
||||
'status' => $errors === [] ? 'structurally_valid_requires_review' : 'rejected',
|
||||
'candidate_counts_by_province' => $counts, 'errors' => $errors];
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
final class TerritorialRegistry
|
||||
{
|
||||
public const PARENTS = ['country' => null, 'province' => 'country', 'district' => 'province', 'admin_post' => 'district', 'locality' => 'admin_post'];
|
||||
|
||||
public function published(): Builder
|
||||
{
|
||||
// Every ancestor must remain public, in force and backed by an approved source.
|
||||
return DB::table('geo_locations as g')->join('geo_territory_profiles as p', 'p.geo_location_id', '=', 'g.id')
|
||||
->whereNull('g.deleted_at')->where('g.data_classification', 'public')->where('p.status', 'published')
|
||||
->whereRaw("NOT EXISTS (WITH RECURSIVE ancestry AS (
|
||||
SELECT l.id,l.parent_id,l.deleted_at,l.data_classification,ARRAY[l.id] AS path,false AS cycle FROM geo_locations l WHERE l.id=g.id
|
||||
UNION ALL SELECT l.id,l.parent_id,l.deleted_at,l.data_classification,a.path||l.id,l.id=ANY(a.path) FROM geo_locations l JOIN ancestry a ON l.id=a.parent_id WHERE NOT a.cycle
|
||||
) SELECT 1 FROM ancestry a LEFT JOIN geo_territory_profiles ap ON ap.geo_location_id=a.id LEFT JOIN geo_sources s ON s.id=ap.source_id
|
||||
WHERE a.cycle OR a.deleted_at IS NOT NULL OR a.data_classification<>'public' OR ap.status IS DISTINCT FROM 'published' OR s.status IS DISTINCT FROM 'approved'
|
||||
OR ap.valid_from>CURRENT_DATE OR ap.valid_to<CURRENT_DATE)");
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input, ?string $id = null): string
|
||||
{
|
||||
abort_unless($actor->can('manage-portal') && $actor->two_factor_confirmed_at && $actor->two_factor_secret, 403);
|
||||
abort_unless(in_array(strtolower($actor->email), config('territorial.editors', []), true), 403);
|
||||
$data = Validator::make($input, [
|
||||
'name' => ['required', 'string', 'max:255'], 'code' => ['required', 'string', 'max:100'],
|
||||
'location_type' => ['required', 'in:'.implode(',', array_keys(self::PARENTS))],
|
||||
'parent_id' => ['nullable', 'uuid', 'exists:geo_locations,id'], 'source_id' => ['required', 'uuid', 'exists:geo_sources,id'],
|
||||
'valid_from' => ['required', 'date_format:Y-m-d'], 'valid_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from'],
|
||||
'version_no' => [$id ? 'required' : 'prohibited', 'integer', 'min:1'], 'reason' => ['required', 'string', 'min:10', 'max:1000'],
|
||||
])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $id) {
|
||||
// Serialise hierarchy changes to prevent concurrent parent cycles and duplicate paths.
|
||||
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
|
||||
$current = $id ? DB::table('geo_locations')->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first() : null;
|
||||
if ($id) {
|
||||
abort_unless($current && DB::table('geo_territory_profiles')->where('geo_location_id', $id)->exists(), 404);
|
||||
abort_unless($current->version_no === $data['version_no'], 409);
|
||||
abort_unless($current->location_type === $data['location_type'], 422, 'O tipo territorial é imutável.');
|
||||
}
|
||||
$parentType = self::PARENTS[$data['location_type']];
|
||||
$parent = empty($data['parent_id']) ? null : DB::table('geo_locations')->where('id', $data['parent_id'])->whereNull('deleted_at')->first();
|
||||
abort_unless($parentType ? $parent && $parent->location_type === $parentType : ! $parent, 422, 'Hierarquia territorial incoerente.');
|
||||
$duplicate = DB::table('geo_locations')->where('location_type', $data['location_type'])->whereNull('deleted_at')->when($id, fn ($q) => $q->where('id', '<>', $id))
|
||||
->where(fn ($q) => $q->where('code', $data['code'])->orWhere(fn ($q) => $q->where('parent_id', $data['parent_id'] ?? null)->whereRaw('lower(trim(name))=lower(trim(?))', [$data['name']])))->exists();
|
||||
abort_if($duplicate, 422, 'Código ou nome no mesmo pai já existente.');
|
||||
$id ??= (string) Str::uuid();
|
||||
$version = $current ? $current->version_no + 1 : 1;
|
||||
DB::table('geo_locations')->updateOrInsert(['id' => $id], ['name' => $data['name'], 'code' => $data['code'],
|
||||
'location_type' => $data['location_type'], 'parent_id' => $data['parent_id'] ?? null,
|
||||
'version_no' => $version, 'data_classification' => 'internal', 'updated_at' => now()]);
|
||||
DB::table('geo_territory_profiles')->updateOrInsert(['geo_location_id' => $id], ['source_id' => $data['source_id'],
|
||||
'valid_from' => $data['valid_from'], 'valid_to' => $data['valid_to'] ?? null, 'status' => 'draft',
|
||||
'editor_id' => $actor->id, 'reviewer_id' => null, 'publisher_id' => null, 'updated_at' => now()]);
|
||||
$this->snapshot($id, $version, $actor, $data['reason']);
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
public function snapshot(string $id, int $version, User $actor, string $reason): void
|
||||
{
|
||||
$snapshot = json_encode(['location' => DB::table('geo_locations')->find($id),
|
||||
'profile' => DB::table('geo_territory_profiles')->where('geo_location_id', $id)->first()], JSON_THROW_ON_ERROR);
|
||||
DB::table('geo_territory_revisions')->insert(['id' => (string) Str::uuid(), 'geo_location_id' => $id,
|
||||
'version_no' => $version, 'actor_id' => $actor->id, 'reason' => Crypt::encryptString($reason),
|
||||
'snapshot' => Crypt::encryptString($snapshot), 'checksum' => hash('sha256', $snapshot)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
abstract class SkillsEducationMigration extends Migration
|
||||
{
|
||||
protected int $block;
|
||||
|
||||
/** @var list<string> */
|
||||
protected array $tables;
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if (DB::getDriverName() !== 'pgsql') {
|
||||
throw new \RuntimeException('PostgreSQL 17 with existing PostGIS/pgcrypto required.');
|
||||
}
|
||||
DB::select("SELECT pg_advisory_xact_lock(hashtextextended('skills_edu:migrations',0))");
|
||||
DB::statement("SET LOCAL TIME ZONE 'UTC'");
|
||||
$version = (int) DB::selectOne("SELECT current_setting('server_version_num') AS n")->n;
|
||||
if ($version < 170000 || $version >= 180000 || DB::table('pg_extension')->whereIn('extname', ['pgcrypto', 'postgis'])->count() !== 2) {
|
||||
throw new \RuntimeException('Expected PostgreSQL 17 and extensions managed by existing migrations.');
|
||||
}
|
||||
foreach (['users' => 'bigint', 'sectors' => 'bigint', 'skills' => 'uuid', 'occupations' => 'uuid', 'courses' => 'uuid', 'training_providers' => 'uuid',
|
||||
'organizations' => 'uuid', 'projects' => 'uuid', 'economic_clusters' => 'uuid', 'development_corridors' => 'uuid', 'investment_zones' => 'uuid',
|
||||
'geo_locations' => 'uuid', 'labour_demands' => 'uuid', 'education_investment_proposals' => 'uuid', 'documents' => 'uuid', 'consents' => 'uuid'] as $table => $type) {
|
||||
$actual = DB::selectOne("SELECT format_type(atttypid,atttypmod) AS type FROM pg_attribute WHERE attrelid=to_regclass(?) AND attname='id' AND NOT attisdropped", ['public.'.$table]);
|
||||
if (! $actual || $actual->type !== $type) {
|
||||
throw new \RuntimeException('Unexpected master identifier: public.'.$table);
|
||||
}
|
||||
}
|
||||
if ($this->block === 1) {
|
||||
if (DB::selectOne("SELECT to_regnamespace('skills_edu') AS id")->id !== null) {
|
||||
throw new \RuntimeException('Unregistered skills_edu schema exists; reconcile before migration.');
|
||||
}
|
||||
DB::statement('CREATE SCHEMA skills_edu');
|
||||
DB::unprepared('CREATE FUNCTION skills_edu.set_updated_at() RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog AS $$ BEGIN NEW.updated_at := now(); RETURN NEW; END $$');
|
||||
} else {
|
||||
$predecessor = match ($this->block) {
|
||||
2 => 'occupation_skills', 3 => 'institutional_candidate_registrations', 4 => 'institutional_authorisations',
|
||||
5 => 'human_resource_need_certifications', 6 => 'profile_need_matches',
|
||||
default => throw new \RuntimeException('Unknown skills education migration block'),
|
||||
};
|
||||
if (DB::selectOne('SELECT to_regclass(?) AS id', ['skills_edu.'.$predecessor])->id === null) {
|
||||
throw new \RuntimeException('Missing previous skills_edu block: '.$predecessor);
|
||||
}
|
||||
}
|
||||
$sql = file_get_contents(database_path('sql/skills-education/'.sprintf('%02d', $this->block).'.sql'));
|
||||
if ($sql === false) {
|
||||
throw new \RuntimeException('Versioned SQL block missing');
|
||||
}
|
||||
if (DB::connection()->getPdo()->exec($sql) === false) {
|
||||
throw new \RuntimeException('Versioned SQL block failed');
|
||||
}
|
||||
DB::unprepared(<<<'SQL'
|
||||
DO $indexes$
|
||||
DECLARE fk record;
|
||||
BEGIN
|
||||
FOR fk IN SELECT c.conrelid,c.conkey,c.conname,t.relname,
|
||||
(SELECT string_agg(quote_ident(a.attname),', ' ORDER BY k.p) FROM unnest(c.conkey) WITH ORDINALITY k(n,p)
|
||||
JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=k.n) AS cols
|
||||
FROM pg_constraint c JOIN pg_class t ON t.oid=c.conrelid JOIN pg_namespace ns ON ns.oid=t.relnamespace
|
||||
WHERE ns.nspname='skills_edu' AND c.contype='f'
|
||||
LOOP
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_index i JOIN pg_class x ON x.oid=i.indexrelid JOIN pg_am am ON am.oid=x.relam
|
||||
WHERE i.indrelid=fk.conrelid AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND am.amname='btree'
|
||||
AND i.indnkeyatts>=cardinality(fk.conkey)
|
||||
AND ARRAY(SELECT n FROM unnest(i.indkey::smallint[]) WITH ORDINALITY k(n,p) WHERE p<=cardinality(fk.conkey) ORDER BY p)=fk.conkey)
|
||||
THEN EXECUTE format('CREATE INDEX %I ON skills_edu.%I (%s)','se_fk_'||md5(fk.relname||fk.conname),fk.relname,fk.cols);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $indexes$;
|
||||
SQL);
|
||||
if ($this->block === 6) {
|
||||
DB::unprepared(<<<'SQL'
|
||||
CREATE FUNCTION skills_edu.reject_audit_mutation() RETURNS trigger LANGUAGE plpgsql SET search_path=pg_catalog AS $$
|
||||
BEGIN RAISE EXCEPTION 'Skills education audit is append-only' USING ERRCODE='23514'; END $$;
|
||||
CREATE TRIGGER immutable_skills_education_audit BEFORE UPDATE OR DELETE OR TRUNCATE ON skills_edu.audit_events
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION skills_edu.reject_audit_mutation();
|
||||
SQL);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::select("SELECT pg_advisory_xact_lock(hashtextextended('skills_edu:migrations',0))");
|
||||
foreach ($this->tables as $table) {
|
||||
if (DB::table('skills_edu.'.$table)->exists()) {
|
||||
throw new \RuntimeException('Skills education data exists; destructive rollback refused: '.$table);
|
||||
}
|
||||
}
|
||||
foreach (array_reverse($this->tables) as $table) {
|
||||
DB::statement('DROP TABLE skills_edu.'.$table.' RESTRICT');
|
||||
}
|
||||
if ($this->block === 6) {
|
||||
DB::statement('DROP FUNCTION skills_edu.reject_audit_mutation() RESTRICT');
|
||||
}
|
||||
if ($this->block === 3) {
|
||||
DB::statement('DROP FUNCTION skills_edu.validate_consent_dates() RESTRICT');
|
||||
}
|
||||
if ($this->block === 1) {
|
||||
DB::statement('DROP FUNCTION skills_edu.set_updated_at() RESTRICT');
|
||||
DB::statement('DROP SCHEMA skills_edu RESTRICT');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,15 @@
|
||||
|
||||
use App\Http\Middleware\HandleAppearance;
|
||||
use App\Http\Middleware\HandleInertiaRequests;
|
||||
use App\Http\Middleware\PreserveFormFeedback;
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
use Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Throwable;
|
||||
|
||||
return Application::configure(basePath: dirname(__DIR__))
|
||||
->withRouting(
|
||||
@@ -21,6 +25,7 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
$middleware->web(append: [
|
||||
HandleAppearance::class,
|
||||
HandleInertiaRequests::class,
|
||||
PreserveFormFeedback::class,
|
||||
AddLinkHeadersForPreloadedAssets::class,
|
||||
]);
|
||||
})
|
||||
@@ -28,4 +33,15 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
$exceptions->shouldRenderJsonWhen(
|
||||
fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
|
||||
);
|
||||
$exceptions->respond(function (Response $response, Throwable $exception, Request $request): Response {
|
||||
if ($request->is('api/*')) {
|
||||
$response->headers->set(
|
||||
'X-Correlation-ID',
|
||||
(string) ($request->attributes->get('correlation_id')
|
||||
?? (Str::isUuid($request->header('X-Correlation-ID')) ? $request->header('X-Correlation-ID') : Str::uuid())),
|
||||
);
|
||||
}
|
||||
|
||||
return $response;
|
||||
});
|
||||
})->create();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'compatibility_shadow' => (bool) env('INVESTMOZ_MNE_COMPATIBILITY_SHADOW', false),
|
||||
'shadow_queue' => 'database',
|
||||
'enabled' => (bool) env('INVESTMOZ_MNE_ENABLED', false),
|
||||
'consent_policy_version' => env('INVESTMOZ_CONSENT_POLICY_VERSION', '2026-09-30'),
|
||||
'sharing_policy_version' => env('INVESTMOZ_SHARING_POLICY_VERSION', '2026-09-30'),
|
||||
'sla_escalation_enabled' => (bool) env('INVESTMOZ_SLA_ESCALATION_ENABLED', false),
|
||||
// Designations do not establish legal competence or an institutional mandate.
|
||||
'reviewers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_MNE_REVIEWERS', '')))))),
|
||||
// These lists control application workflow access; they do not replace institutional delegation.
|
||||
'triagers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_MNE_TRIAGERS', '')))))),
|
||||
'approvers_l1' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_MNE_APPROVERS_L1', '')))))),
|
||||
'approvers_l2' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_MNE_APPROVERS_L2', '')))))),
|
||||
'publishers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_MNE_PUBLISHERS', '')))))),
|
||||
];
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'enabled' => (bool) env('INVESTMOZ_TERRITORIAL_ENABLED', false),
|
||||
'editors' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TERRITORIAL_EDITORS', '')))))),
|
||||
'reviewers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TERRITORIAL_REVIEWERS', '')))))),
|
||||
'publishers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TERRITORIAL_PUBLISHERS', '')))))),
|
||||
];
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (DB::connection()->getDriverName() !== 'pgsql') {
|
||||
throw new RuntimeException('PostgreSQL required.');
|
||||
}
|
||||
Schema::create('existing_businesses', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->string('code')->unique();
|
||||
$t->string('source_system')->nullable();
|
||||
$t->string('legacy_id')->nullable();
|
||||
$t->unique(['source_system', 'legacy_id']);
|
||||
$t->foreignId('owner_user_id')->constrained('users')->restrictOnDelete();
|
||||
$t->foreignUuid('organization_id')->nullable()->constrained('organizations')->restrictOnDelete();
|
||||
$t->foreignUuid('investment_item_id')->nullable()->unique()->constrained('investment_items')->restrictOnDelete();
|
||||
$t->string('modality');
|
||||
$t->string('status')->default('draft');
|
||||
$t->string('classification')->default('confidential');
|
||||
$t->unsignedInteger('version_no')->default(1);
|
||||
$t->text('payload');
|
||||
$t->timestampsTz();
|
||||
$t->softDeletesTz();
|
||||
});
|
||||
// Phase 1 deliberately cannot publish. Future workflow must replace this constraint explicitly.
|
||||
DB::statement("ALTER TABLE existing_businesses ADD CHECK(status='draft'), ADD CHECK(version_no>0), ADD CHECK(classification IN ('internal','confidential','restricted')), ADD CHECK((source_system IS NULL)=(legacy_id IS NULL)), ADD CHECK(modality IN ('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'))");
|
||||
Schema::create('existing_business_objects', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
|
||||
$t->string('kind');
|
||||
$t->string('classification')->default('restricted');
|
||||
$t->string('verification_status')->default('pending');
|
||||
$t->text('payload');
|
||||
$t->timestampsTz();
|
||||
});
|
||||
DB::statement("ALTER TABLE existing_business_objects ADD CHECK(kind IN ('company','participation','asset','property','unit','improvement','agricultural_investment','land_right','contract','license','authorization','encumbrance','valuation','capital_request')), ADD CHECK(classification IN ('confidential','restricted')), ADD CHECK(verification_status='pending')");
|
||||
Schema::create('existing_business_mandates', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
|
||||
$t->foreignId('representative_user_id')->constrained('users')->restrictOnDelete();
|
||||
$t->foreignUuid('document_id')->constrained('documents')->restrictOnDelete();
|
||||
$t->date('valid_from');
|
||||
$t->date('valid_until');
|
||||
$t->string('verification_status')->default('pending');
|
||||
$t->text('payload');
|
||||
$t->timestampsTz();
|
||||
});
|
||||
DB::statement("ALTER TABLE existing_business_mandates ADD CHECK(valid_until>=valid_from), ADD CHECK(verification_status='pending')");
|
||||
Schema::create('existing_business_revisions', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
|
||||
$t->unsignedInteger('version_no');
|
||||
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
|
||||
$t->string('action');
|
||||
$t->text('reason');
|
||||
$t->text('snapshot');
|
||||
$t->char('sha256', 64);
|
||||
$t->timestampTz('created_at')->useCurrent();
|
||||
$t->unique(['business_id', 'version_no']);
|
||||
});
|
||||
DB::unprepared("CREATE OR REPLACE FUNCTION reject_business_revision_change() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Business revisions are immutable'; END $$; CREATE TRIGGER immutable_business_revision BEFORE UPDATE OR DELETE ON existing_business_revisions FOR EACH ROW EXECUTE FUNCTION reject_business_revision_change()");
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$tables = ['existing_business_revisions', 'existing_business_mandates', 'existing_business_objects', 'existing_businesses'];
|
||||
foreach ($tables as $table) {
|
||||
if (DB::table($table)->exists()) {
|
||||
throw new RuntimeException('Business data exists; destructive rollback refused.');
|
||||
}
|
||||
}
|
||||
foreach ($tables as $table) {
|
||||
Schema::drop($table);
|
||||
}
|
||||
DB::statement('DROP FUNCTION reject_business_revision_change()');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::statement('ALTER TABLE existing_businesses DROP CONSTRAINT existing_businesses_status_check');
|
||||
DB::statement("ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_status_check CHECK(status IN ('draft','submitted','in_review','needs_information','withdrawn'))");
|
||||
Schema::create('existing_business_reviews', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignUuid('business_id')->constrained('existing_businesses')->restrictOnDelete();
|
||||
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
|
||||
$t->unsignedInteger('version_no');
|
||||
$t->string('action');
|
||||
$t->text('note');
|
||||
$t->timestampTz('created_at')->useCurrent();
|
||||
$t->unique(['business_id', 'version_no']);
|
||||
});
|
||||
DB::statement("ALTER TABLE existing_business_reviews ADD CHECK(action IN ('submitted','in_review','needs_information','withdrawn'))");
|
||||
DB::unprepared('CREATE TRIGGER immutable_business_review BEFORE UPDATE OR DELETE ON existing_business_reviews FOR EACH ROW EXECUTE FUNCTION reject_business_revision_change()');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::table('existing_business_reviews')->exists() || DB::table('existing_businesses')->where('status', '<>', 'draft')->exists()) {
|
||||
throw new RuntimeException('Intake evidence exists; destructive rollback refused.');
|
||||
}
|
||||
Schema::drop('existing_business_reviews');
|
||||
DB::statement('ALTER TABLE existing_businesses DROP CONSTRAINT existing_businesses_status_check');
|
||||
DB::statement("ALTER TABLE existing_businesses ADD CONSTRAINT existing_businesses_status_check CHECK(status='draft')");
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::statement('ALTER TABLE geo_locations DROP CONSTRAINT imz_geo_locations_check_03');
|
||||
DB::statement("ALTER TABLE geo_locations ADD CONSTRAINT imz_geo_locations_check_03 CHECK(location_type IN ('country','province','district','admin_post','locality','municipality','site'))");
|
||||
Schema::create('geo_sources', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->string('name');
|
||||
$t->string('responsible_entity')->nullable();
|
||||
$t->text('reference');
|
||||
$t->text('license')->nullable();
|
||||
$t->char('checksum', 64);
|
||||
$t->string('source_version');
|
||||
$t->date('collected_at');
|
||||
$t->string('original_crs')->nullable();
|
||||
$t->string('status')->default('pending');
|
||||
$t->foreignId('editor_id')->constrained('users')->restrictOnDelete();
|
||||
$t->foreignId('reviewer_id')->nullable()->constrained('users')->restrictOnDelete();
|
||||
$t->text('approval_reference')->nullable();
|
||||
$t->timestampsTz();
|
||||
$t->unique(['checksum', 'source_version']);
|
||||
});
|
||||
DB::statement("ALTER TABLE geo_sources ADD CHECK(status IN ('pending','approved','revoked')), ADD CHECK(checksum ~ '^[0-9a-f]{64}$'), ADD CHECK(status<>'approved' OR (responsible_entity IS NOT NULL AND license IS NOT NULL))");
|
||||
Schema::create('geo_territory_profiles', function (Blueprint $t) {
|
||||
$t->foreignUuid('geo_location_id')->primary()->constrained('geo_locations')->restrictOnDelete();
|
||||
$t->foreignUuid('source_id')->constrained('geo_sources')->restrictOnDelete();
|
||||
$t->char('iso2', 2)->nullable()->unique();
|
||||
$t->char('iso3', 3)->nullable()->unique();
|
||||
$t->foreignUuid('capital_territory_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
|
||||
$t->date('valid_from');
|
||||
$t->date('valid_to')->nullable();
|
||||
$t->string('status')->default('draft');
|
||||
$t->foreignId('editor_id')->constrained('users')->restrictOnDelete();
|
||||
$t->foreignId('reviewer_id')->nullable()->constrained('users')->restrictOnDelete();
|
||||
$t->foreignId('publisher_id')->nullable()->constrained('users')->restrictOnDelete();
|
||||
$t->timestampsTz();
|
||||
});
|
||||
DB::statement("ALTER TABLE geo_territory_profiles ADD CHECK(valid_to IS NULL OR valid_to>=valid_from), ADD CHECK(status IN ('draft','pending_review','approved','published','rejected','archived')), ADD CHECK(iso2 IS NULL OR iso2 ~ '^[A-Z]{2}$'), ADD CHECK(iso3 IS NULL OR iso3 ~ '^[A-Z]{3}$'), ADD CHECK(status NOT IN ('approved','published') OR (reviewer_id IS NOT NULL AND reviewer_id<>editor_id)), ADD CHECK(status<>'published' OR (publisher_id IS NOT NULL AND publisher_id<>editor_id AND publisher_id<>reviewer_id))");
|
||||
Schema::create('geo_names', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignUuid('geo_location_id')->constrained('geo_locations')->restrictOnDelete();
|
||||
$t->string('language', 10);
|
||||
$t->string('name');
|
||||
$t->string('normalized_name');
|
||||
$t->boolean('official')->default(false);
|
||||
$t->timestampsTz();
|
||||
$t->unique(['geo_location_id', 'language', 'normalized_name']);
|
||||
});
|
||||
DB::statement('CREATE UNIQUE INDEX geo_names_official_language_uq ON geo_names(geo_location_id,language) WHERE official');
|
||||
Schema::create('geo_territory_revisions', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignUuid('geo_location_id')->constrained('geo_locations')->restrictOnDelete();
|
||||
$t->unsignedInteger('version_no');
|
||||
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
|
||||
$t->text('reason');
|
||||
$t->text('snapshot');
|
||||
$t->char('checksum', 64);
|
||||
$t->timestampTz('created_at')->useCurrent();
|
||||
$t->unique(['geo_location_id', 'version_no']);
|
||||
});
|
||||
DB::unprepared("CREATE OR REPLACE FUNCTION reject_territory_revision_change() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Territory revisions are immutable'; END $$; CREATE TRIGGER immutable_territory_revision BEFORE UPDATE OR DELETE ON geo_territory_revisions FOR EACH ROW EXECUTE FUNCTION reject_territory_revision_change()");
|
||||
Schema::create('geo_write_receipts', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
|
||||
$t->uuid('idempotency_key');
|
||||
$t->string('scope');
|
||||
$t->char('request_hash', 64);
|
||||
$t->text('response');
|
||||
$t->integer('http_status');
|
||||
$t->timestampTz('created_at')->useCurrent();
|
||||
$t->unique(['actor_id', 'idempotency_key', 'scope']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$tables = ['geo_write_receipts', 'geo_territory_revisions', 'geo_names', 'geo_territory_profiles', 'geo_sources'];
|
||||
foreach ($tables as $table) {
|
||||
if (DB::table($table)->exists()) {
|
||||
throw new RuntimeException('Territory evidence exists; destructive rollback refused.');
|
||||
}
|
||||
}
|
||||
if (DB::table('geo_locations')->whereIn('location_type', ['admin_post', 'locality'])->exists()) {
|
||||
throw new RuntimeException('New territory types exist; rollback refused.');
|
||||
}
|
||||
foreach ($tables as $table) {
|
||||
Schema::drop($table);
|
||||
}
|
||||
DB::statement('DROP FUNCTION reject_territory_revision_change()');
|
||||
DB::statement('ALTER TABLE geo_locations DROP CONSTRAINT imz_geo_locations_check_03');
|
||||
DB::statement("ALTER TABLE geo_locations ADD CONSTRAINT imz_geo_locations_check_03 CHECK(location_type IN ('country','province','district','municipality','site'))");
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
foreach (['opportunities', 'projects', 'economic_clusters', 'development_corridors', 'investment_zones'] as $table) {
|
||||
Schema::table($table, function (Blueprint $t) {
|
||||
$t->foreignUuid('primary_territory_id')->nullable()->constrained('geo_locations')->restrictOnDelete();
|
||||
$t->unsignedInteger('territory_version')->default(0);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$tables = ['opportunities', 'projects', 'economic_clusters', 'development_corridors', 'investment_zones'];
|
||||
foreach ($tables as $table) {
|
||||
if (Schema::hasColumn($table, 'primary_territory_id') && DB::table($table)->whereNotNull('primary_territory_id')->exists()) {
|
||||
throw new RuntimeException('Preserve territorial assignments before rollback.');
|
||||
}
|
||||
}
|
||||
foreach ($tables as $table) {
|
||||
if (Schema::hasColumn($table, 'primary_territory_id')) {
|
||||
Schema::table($table, function (Blueprint $t) {
|
||||
$t->dropConstrainedForeignId('primary_territory_id');
|
||||
$t->dropColumn('territory_version');
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::statement('ALTER TABLE geo_locations ADD COLUMN source_code text');
|
||||
DB::statement('CREATE UNIQUE INDEX geo_source_parent_code_uq ON geo_locations(source_system, parent_id, location_type, source_code) NULLS NOT DISTINCT WHERE deleted_at IS NULL AND source_code IS NOT NULL');
|
||||
DB::statement('CREATE INDEX geo_parent_type_name_idx ON geo_locations(parent_id, location_type, name) WHERE deleted_at IS NULL');
|
||||
DB::unprepared(<<<'SQL'
|
||||
CREATE OR REPLACE FUNCTION enforce_geo_hierarchy() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent_type text; expected_type text;
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(280926,150000);
|
||||
IF NEW.deleted_at IS NOT NULL THEN RETURN NEW; END IF;
|
||||
IF NEW.location_type='country' AND NEW.parent_id IS NOT NULL THEN
|
||||
RAISE EXCEPTION 'Country cannot have a parent';
|
||||
END IF;
|
||||
expected_type := CASE NEW.location_type WHEN 'province' THEN 'country' WHEN 'district' THEN 'province' WHEN 'admin_post' THEN 'district' WHEN 'locality' THEN 'admin_post' END;
|
||||
IF NEW.parent_id IS NOT NULL THEN
|
||||
SELECT location_type INTO parent_type FROM geo_locations WHERE id=NEW.parent_id AND deleted_at IS NULL;
|
||||
IF parent_type IS NULL OR (expected_type IS NOT NULL AND parent_type<>expected_type) THEN
|
||||
RAISE EXCEPTION 'Invalid geographic parent';
|
||||
END IF;
|
||||
IF EXISTS(WITH RECURSIVE ancestors AS (
|
||||
SELECT id,parent_id,ARRAY[id] as visited FROM geo_locations WHERE id=NEW.parent_id
|
||||
UNION ALL SELECT g.id,g.parent_id,a.visited||g.id FROM geo_locations g JOIN ancestors a ON g.id=a.parent_id WHERE NOT g.id=ANY(a.visited)
|
||||
) SELECT 1 FROM ancestors WHERE id=NEW.id) THEN RAISE EXCEPTION 'Geographic cycle'; END IF;
|
||||
ELSIF expected_type IS NOT NULL AND NEW.source_system='cartografia-workbook' THEN
|
||||
RAISE EXCEPTION 'Workbook administrative node requires a parent';
|
||||
END IF;
|
||||
IF EXISTS(SELECT 1 FROM geo_locations c WHERE c.parent_id=NEW.id AND c.deleted_at IS NULL AND
|
||||
CASE c.location_type WHEN 'province' THEN 'country' WHEN 'district' THEN 'province' WHEN 'admin_post' THEN 'district' WHEN 'locality' THEN 'admin_post' END <> NEW.location_type) THEN
|
||||
RAISE EXCEPTION 'Geographic children incompatible with new level';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER geo_hierarchy_guard BEFORE INSERT OR UPDATE OF parent_id,location_type,deleted_at,source_system ON geo_locations FOR EACH ROW EXECUTE FUNCTION enforce_geo_hierarchy();
|
||||
SQL);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::table('geo_locations')->whereNotNull('source_code')->exists()) {
|
||||
throw new RuntimeException('Preserve imported source codes before rollback.');
|
||||
}
|
||||
DB::statement('DROP TRIGGER geo_hierarchy_guard ON geo_locations');
|
||||
DB::statement('DROP FUNCTION enforce_geo_hierarchy()');
|
||||
DB::statement('DROP INDEX geo_source_parent_code_uq');
|
||||
DB::statement('DROP INDEX geo_parent_type_name_idx');
|
||||
DB::statement('ALTER TABLE geo_locations DROP COLUMN source_code');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('existing_businesses', function (Blueprint $table) {
|
||||
$table->foreignId('sector_id')->nullable()->constrained('sectors')->restrictOnDelete();
|
||||
$table->index('sector_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::table('existing_businesses')->whereNotNull('sector_id')->exists()) {
|
||||
throw new RuntimeException('Sector associations exist; destructive rollback refused.');
|
||||
}
|
||||
Schema::table('existing_businesses', function (Blueprint $table) {
|
||||
$table->dropForeign(['sector_id']);
|
||||
$table->dropIndex(['sector_id']);
|
||||
$table->dropColumn('sector_id');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Support\SkillsEducationMigration;
|
||||
|
||||
return new class extends SkillsEducationMigration
|
||||
{
|
||||
protected int $block = 1;
|
||||
|
||||
protected array $tables = ['skill_details', 'occupation_details', 'occupation_skills'];
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Support\SkillsEducationMigration;
|
||||
|
||||
return new class extends SkillsEducationMigration
|
||||
{
|
||||
protected int $block = 2;
|
||||
|
||||
protected array $tables = ['professional_profiles', 'profile_contacts', 'profile_skills', 'profile_experiences', 'profile_languages', 'institutional_candidate_registrations'];
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Support\SkillsEducationMigration;
|
||||
|
||||
return new class extends SkillsEducationMigration
|
||||
{
|
||||
protected int $block = 3;
|
||||
|
||||
protected array $tables = ['profile_qualifications', 'qualification_document_details', 'consent_details', 'institutional_authorisations'];
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Support\SkillsEducationMigration;
|
||||
|
||||
return new class extends SkillsEducationMigration
|
||||
{
|
||||
protected int $block = 4;
|
||||
|
||||
protected array $tables = ['human_resource_need_details', 'human_resource_need_skills', 'human_resource_need_languages', 'human_resource_need_certifications'];
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Support\SkillsEducationMigration;
|
||||
|
||||
return new class extends SkillsEducationMigration
|
||||
{
|
||||
protected int $block = 5;
|
||||
|
||||
protected array $tables = ['program_details', 'education_program_skills', 'skill_gaps', 'educational_opportunity_details', 'educational_opportunity_skills', 'profile_need_matches'];
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
use App\Support\SkillsEducationMigration;
|
||||
|
||||
return new class extends SkillsEducationMigration
|
||||
{
|
||||
protected int $block = 6;
|
||||
|
||||
protected array $tables = ['audit_events'];
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::unprepared(<<<'SQL'
|
||||
CREATE FUNCTION public.lock_project_dependency_graph() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF current_setting('transaction_isolation') <> 'read committed' THEN
|
||||
RAISE EXCEPTION 'Dependency writes require READ COMMITTED isolation' USING ERRCODE='25000';
|
||||
END IF;
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended('investmoz:project-dependency-graph', 0));
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
CREATE FUNCTION public.check_project_dependency_graph() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
WITH RECURSIVE edges AS (
|
||||
SELECT anchor_project_id AS origin, complementary_project_id AS destination
|
||||
FROM public.complementary_project_links
|
||||
WHERE relation_type='dependency' AND deleted_at IS NULL
|
||||
), paths(origin,destination) AS (
|
||||
SELECT origin,destination FROM edges
|
||||
UNION
|
||||
SELECT p.origin,e.destination FROM paths p JOIN edges e ON e.origin=p.destination
|
||||
) SELECT 1 FROM paths WHERE origin=destination
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Project dependency cycle is not permitted' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NULL;
|
||||
END $$;
|
||||
CREATE TRIGGER project_dependency_lock BEFORE INSERT OR UPDATE ON public.complementary_project_links
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION public.lock_project_dependency_graph();
|
||||
CREATE TRIGGER project_dependency_check AFTER INSERT OR UPDATE ON public.complementary_project_links
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION public.check_project_dependency_graph();
|
||||
-- Validate the complete existing graph, without modifying a row.
|
||||
UPDATE public.complementary_project_links SET relation_type=relation_type WHERE false;
|
||||
SQL);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::unprepared(<<<'SQL'
|
||||
DROP TRIGGER project_dependency_check ON public.complementary_project_links;
|
||||
DROP TRIGGER project_dependency_lock ON public.complementary_project_links;
|
||||
DROP FUNCTION public.check_project_dependency_graph() RESTRICT;
|
||||
DROP FUNCTION public.lock_project_dependency_graph() RESTRICT;
|
||||
SQL);
|
||||
}
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user