Compare commits
470
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
979f3f850e | ||
|
|
b81f477bf2 | ||
|
|
568a488ae7 | ||
|
|
d96f9c6bf5 | ||
|
|
4875c4beb9 | ||
|
|
3f7082a3e6 | ||
|
|
23ecccfaad | ||
|
|
332c16ebb5 | ||
|
|
17444aaaa5 | ||
|
|
789fffd098 | ||
|
|
502e3ec4d5 | ||
|
|
54d1b2a543 | ||
|
|
6520d303f7 | ||
|
|
47dae1b77e | ||
|
|
2c8eb95e10 | ||
|
|
1b2ede41e2 | ||
|
|
d7a9284d5f | ||
|
|
6e8de43ae7 | ||
|
|
77d133ef0e | ||
|
|
930013f920 | ||
|
|
6d14769369 | ||
|
|
a022ed9848 | ||
|
|
2f58b7d438 | ||
|
|
150bef4b89 | ||
|
|
569a1cd750 | ||
|
|
aae67c169d | ||
|
|
6ededb597a | ||
|
|
d134a92d16 | ||
|
|
cf4e0638c1 | ||
|
|
838ad941a2 | ||
|
|
814fe0a9b7 | ||
|
|
e182d1d79d | ||
|
|
9a093046e5 | ||
|
|
4ee427bad4 | ||
|
|
669cb8979b | ||
|
|
7fdb6b424b | ||
|
|
dc14f01e14 | ||
|
|
1ee0c6d21d | ||
|
|
9fda6d6e12 | ||
|
|
56c0c6a7ca | ||
|
|
74f7f93a75 | ||
|
|
0ff402a11d | ||
|
|
51d536b7ba | ||
|
|
403c444a3e | ||
|
|
a78abf06d0 | ||
|
|
52f54655d2 | ||
|
|
4f9450a71d | ||
|
|
1afab4a2a7 | ||
|
|
3439f35038 | ||
|
|
c85e772d2f | ||
|
|
1436074819 | ||
|
|
11a6cee981 | ||
|
|
d5f11462e9 | ||
|
|
f8d57bddf9 | ||
|
|
ea2bceb5ce | ||
|
|
245549f9e8 | ||
|
|
a7434cd27c | ||
|
|
71551deb73 | ||
|
|
f33d99b4d5 | ||
|
|
632dc06930 | ||
|
|
ff84ab648f | ||
|
|
992c97ad4e | ||
|
|
ae0d74bb3a | ||
|
|
894ca4ec69 | ||
|
|
ba83afe7d8 | ||
|
|
4da7a16a50 | ||
|
|
eccd95f9e7 | ||
|
|
0bd5d49550 | ||
|
|
aed020d19e | ||
|
|
1649710cf7 | ||
|
|
e07f89da3d | ||
|
|
ab2ff2fdbc | ||
|
|
a2122dc34c | ||
|
|
d37fffb2d2 | ||
|
|
45fd591c7f | ||
|
|
17d633c99c | ||
|
|
5aaf1a56f9 | ||
|
|
2116f66b2b | ||
|
|
8f1ab24b22 | ||
|
|
56475acb2f | ||
|
|
0effdc9fcb | ||
|
|
e9fe102259 | ||
|
|
44d0858cee | ||
|
|
043dd35d8e | ||
|
|
f400e56a5b | ||
|
|
a2de725901 | ||
|
|
82d0d05887 | ||
|
|
2f684e5984 | ||
|
|
b8d45796dd | ||
|
|
5e02c23af8 | ||
|
|
664c88c8f7 | ||
|
|
7a11c4ef8f | ||
|
|
acf8ec3cb5 | ||
|
|
5fa64bc0f4 | ||
|
|
85e3cd5c7b | ||
|
|
ce746d889d | ||
|
|
2b33a1c343 | ||
|
|
4d6f828230 | ||
|
|
da0d8abb47 | ||
|
|
5c0cb25cea | ||
|
|
3dda7130ee | ||
|
|
6af7092e83 | ||
|
|
49b448eb47 | ||
|
|
fa32a2b9e1 | ||
|
|
0f4df8a4d1 | ||
|
|
b189d0fa43 | ||
|
|
dbeaf886ee | ||
|
|
7ad187f9f0 | ||
|
|
4708662532 | ||
|
|
46944402da | ||
|
|
de36f02880 | ||
|
|
9e2d90c880 | ||
|
|
b7a745e64f | ||
|
|
3aa851a467 | ||
|
|
109cb0fe9e | ||
|
|
f7b778cdce | ||
|
|
508aeb5205 | ||
|
|
acbd1f3315 | ||
|
|
7a380b7690 | ||
|
|
dde20c3348 | ||
|
|
2c2a2f2010 | ||
|
|
855ab066c4 | ||
|
|
819ae791e9 | ||
|
|
fc7e590d4e | ||
|
|
56c948ec45 | ||
|
|
940d69b82a | ||
|
|
7febb6f7be | ||
|
|
ada9629bb6 | ||
|
|
6e1dc4104c | ||
|
|
4f28fac5d0 | ||
|
|
9019f766f2 | ||
|
|
e38aa74920 | ||
|
|
fab72d2e0c | ||
|
|
7b6a95a718 | ||
|
|
9536eb710b | ||
|
|
8b3ec2b04d | ||
|
|
a665ee9c97 | ||
|
|
2b130a66ec | ||
|
|
4e550c3892 | ||
|
|
34bbcfa7e4 | ||
|
|
0807201517 | ||
|
|
f059622562 | ||
|
|
a48e974979 | ||
|
|
1a5f72209e | ||
|
|
c309215d0f | ||
|
|
7986d02405 | ||
|
|
91c4063338 | ||
|
|
df43aeb1e5 | ||
|
|
de4b25bbd7 | ||
|
|
5f088e3411 | ||
|
|
e4c490b323 | ||
|
|
86970cd507 | ||
|
|
2de67bebf9 | ||
|
|
e8b5ae43ad | ||
|
|
0052cd42d2 | ||
|
|
7e6e462e12 | ||
|
|
7a3ac43224 | ||
|
|
92eaa93570 | ||
|
|
d84883b801 | ||
|
|
5999e35fcb | ||
|
|
4cacef23dd | ||
|
|
ce9d649fbf | ||
|
|
a5b1ae6657 | ||
|
|
f640e19370 | ||
|
|
4ef7be3d6f | ||
|
|
019bcbad6c | ||
|
|
0ebb20c86a | ||
|
|
b0818c0163 | ||
|
|
ec786f4ae2 | ||
|
|
6c12aabb3a | ||
|
|
cd259623ae | ||
|
|
9b95e5e7a8 | ||
|
|
1b67fa85ff | ||
|
|
63cc336787 | ||
|
|
af7d250320 | ||
|
|
2b592ded66 | ||
|
|
5837f34a2c | ||
|
|
2fdca86367 | ||
|
|
833b4e5cef | ||
|
|
67a96085c8 | ||
|
|
b0e01ef737 | ||
|
|
2a7254406d | ||
|
|
4601bf64a0 | ||
|
|
6cffa1188f | ||
|
|
4853bc7284 | ||
|
|
03c26d6613 | ||
|
|
3f4e71c3f3 | ||
|
|
ec33fb5be2 | ||
|
|
aac3f46306 | ||
|
|
8f14f5dde2 | ||
|
|
fb7248661d | ||
|
|
0682ef74e2 | ||
|
|
21ce03f65c | ||
|
|
6f1cf7b7a0 | ||
|
|
a4329bb4bf | ||
|
|
90b31c677f | ||
|
|
33cc971a12 | ||
|
|
cd530b248b | ||
|
|
2087134143 | ||
|
|
67b8b58149 | ||
|
|
adb849d4fc | ||
|
|
5d5f3b4148 | ||
|
|
9c2b2c6560 | ||
|
|
acc633bf08 | ||
|
|
a89f9eca8c | ||
|
|
7e5710ebbd | ||
|
|
6f90fcb9d4 | ||
|
|
e3caf55361 | ||
|
|
0bef805ede | ||
|
|
70b4a640ee | ||
|
|
0460c85330 | ||
|
|
9f053ac9d3 | ||
|
|
6234d34392 | ||
|
|
92a7418cb6 | ||
|
|
76be72c38c | ||
|
|
3bcd98e78e | ||
|
|
9600880169 | ||
|
|
df7cb7fa47 | ||
|
|
287f2f8321 | ||
|
|
4672789f2b | ||
|
|
15894f4b04 | ||
|
|
e62b7dfdc2 | ||
|
|
9bd2e062f4 | ||
|
|
948621a65c | ||
|
|
50463ca716 | ||
|
|
4193056bdd | ||
|
|
20bfeb4f71 | ||
|
|
1dda6ea258 | ||
|
|
0a80f1c457 | ||
|
|
eb9294ef42 | ||
|
|
2359a88dba | ||
|
|
69b6c49a60 | ||
|
|
163e090ea5 | ||
|
|
9b26217dec | ||
|
|
ebf5e53c3c | ||
|
|
9783c54b2c | ||
|
|
0f9f7e3409 | ||
|
|
78c9f4a356 | ||
|
|
7996c35933 | ||
|
|
29e708ba2d | ||
|
|
f9fb04f947 | ||
|
|
77d1290258 | ||
|
|
946fc08906 | ||
|
|
7ecf9ec79a | ||
|
|
536559d651 | ||
|
|
c1314cdf90 | ||
|
|
ff8848d32d | ||
|
|
1565aa4ffb | ||
|
|
4e4bf6b859 | ||
|
|
5ec2f198a3 | ||
|
|
e32690799f | ||
|
|
2d889a211b | ||
|
|
50fdd97916 | ||
|
|
9842dcbb0e | ||
|
|
e384418ecc | ||
|
|
0eb37ef59b | ||
|
|
2ed62165b7 | ||
|
|
d46b794ab2 | ||
|
|
d65d3f5c4e | ||
|
|
8e5565d5e0 | ||
|
|
72e56f7ae5 | ||
|
|
4cebd61765 | ||
|
|
1efb32c244 | ||
|
|
f75f36f0e3 | ||
|
|
a23f1dcb6e | ||
|
|
e3601c124d | ||
|
|
615f78e79f | ||
|
|
965da26426 | ||
|
|
e99ea1d013 | ||
|
|
6f056359df | ||
|
|
0cd7e9fb62 | ||
|
|
689a4c93c3 | ||
|
|
d3e9f3732c | ||
|
|
69f2e365bf | ||
|
|
4e97cd05ea | ||
|
|
1f7fc13872 | ||
|
|
0eb2c485cc | ||
|
|
2e21ca4500 | ||
|
|
fae8162c58 | ||
|
|
d03101bb69 | ||
|
|
38faeac685 | ||
|
|
3be371c823 | ||
|
|
686328a085 | ||
|
|
40a4ddcbde | ||
|
|
e50733ba1d | ||
|
|
8df721ac51 | ||
|
|
25cae1d98b | ||
|
|
679203d4b1 | ||
|
|
2fccbc8ee8 | ||
|
|
19b31d51c5 | ||
|
|
b1c8e0e343 | ||
|
|
117f2a70a8 | ||
|
|
a153d0782f | ||
|
|
0b0e002d15 | ||
|
|
b641887274 | ||
|
|
f946364baa | ||
|
|
3846be8fc6 | ||
|
|
b898955603 | ||
|
|
7b54efb0fc | ||
|
|
7a58fa2435 | ||
|
|
0f0d2e566f | ||
|
|
82e010c44f | ||
|
|
6eefe4b332 | ||
|
|
0dc2d64b20 | ||
|
|
bda6d1e3a0 | ||
|
|
ac948bd8b7 | ||
|
|
908c8afc54 | ||
|
|
643ba6ed72 | ||
|
|
ccdecbd8d7 | ||
|
|
da798dd1d8 | ||
|
|
0304612093 | ||
|
|
d76078a81f | ||
|
|
c4cc7d83e7 | ||
|
|
744682835a | ||
|
|
1fe742561f | ||
|
|
8882dc54d0 | ||
|
|
eb9e0dbc60 | ||
|
|
e45a1394fa | ||
|
|
72f4187d3b | ||
|
|
a5ac8ca1c9 | ||
|
|
fe69a16eea | ||
|
|
7696af6814 | ||
|
|
d4eae917ee | ||
|
|
b297058d11 | ||
|
|
48146089cd | ||
|
|
2440cb448a | ||
|
|
9dbfdd67ad | ||
|
|
b1928b61e5 | ||
|
|
541ea70484 | ||
|
|
9a56d98242 | ||
|
|
38b49bd5fa | ||
|
|
9b0f437073 | ||
|
|
8171c7992e | ||
|
|
30760cab9b | ||
|
|
33d18b9efc | ||
|
|
0aac0d1555 | ||
|
|
3b788ec009 | ||
|
|
db4ff64e87 | ||
|
|
c28e290b42 | ||
|
|
8d127799cd | ||
|
|
d32ad1e0a6 | ||
|
|
122f4f04b9 | ||
|
|
dacda11c07 | ||
|
|
490527b92c | ||
|
|
4a35d63cd3 | ||
|
|
0e644b5524 | ||
|
|
675cf38f67 | ||
|
|
89ab288334 | ||
|
|
5030116ee5 | ||
|
|
8719e916ea | ||
|
|
689e7cbe8b | ||
|
|
d89912e579 | ||
|
|
544068e8cc | ||
|
|
e8c39a1b54 | ||
|
|
1655f57e69 | ||
|
|
d18ff0f049 | ||
|
|
355656b5c8 | ||
|
|
cd10cccbf4 | ||
|
|
d044ef1efc | ||
|
|
65b87819a0 | ||
|
|
be62783b98 | ||
|
|
98fc16a3fb | ||
|
|
276d833a4b | ||
|
|
5d45541a11 | ||
|
|
066707ece6 | ||
|
|
c1f4a71963 | ||
|
|
cf2ddf21a1 | ||
|
|
3fd5128c62 | ||
|
|
cdf8fcfba4 | ||
|
|
8036b9b071 | ||
|
|
6985f82e9c | ||
|
|
2856240cf4 | ||
|
|
32144aa2f3 | ||
|
|
1afdfee8c0 | ||
|
|
bc84fbdb3e | ||
|
|
b6a626c92d | ||
|
|
55136b446d | ||
|
|
4a01e9e2b7 | ||
|
|
ad4160f040 | ||
|
|
af9261809c | ||
|
|
d8224ba84b | ||
|
|
088f2c2cf4 | ||
|
|
603a88e1d3 | ||
|
|
43cd0be7cb | ||
|
|
89a9c3d994 | ||
|
|
4098192a05 | ||
|
|
d242482042 | ||
|
|
6b544548d3 | ||
|
|
c3f7c3ad10 | ||
|
|
445aa7e69d | ||
|
|
7c1f532134 | ||
|
|
115c773162 | ||
|
|
ec4b2f2af2 | ||
|
|
3d877ec745 | ||
|
|
6948ed62fc | ||
|
|
7d798579a6 | ||
|
|
5bda74aedc | ||
|
|
f2150b1912 | ||
|
|
7ca94967f3 | ||
|
|
e1f010f941 | ||
|
|
0025309b98 | ||
|
|
a0e80db4ec | ||
|
|
7226287526 | ||
|
|
f1ac82ae4d | ||
|
|
98474777f6 | ||
|
|
3848f29bea | ||
|
|
203492997e | ||
|
|
165c2f6171 | ||
|
|
4ad1bf402b | ||
|
|
e12ef6ad42 | ||
|
|
c641b267ac | ||
|
|
e2b0fb4b2d | ||
|
|
7d08c2c664 | ||
|
|
761035aefb | ||
|
|
20a4099d10 | ||
|
|
e03de682ca | ||
|
|
37a8eb015a | ||
|
|
65eddf6bc7 | ||
|
|
fb4e7d8970 | ||
|
|
bc93ccdb9e | ||
|
|
7ccf62adec | ||
|
|
f4d0970917 | ||
|
|
e46f973159 | ||
|
|
1bcf34c0c0 | ||
|
|
ef0c2acd36 | ||
|
|
30aed7cd12 | ||
|
|
95d4cf44d7 | ||
|
|
73c046e104 | ||
|
|
15d82611b6 | ||
|
|
8286d7504d | ||
|
|
aa2b3d05b0 | ||
|
|
97d51db60a | ||
|
|
a1b553372e | ||
|
|
f80d30f478 | ||
|
|
916819eb35 | ||
|
|
1d921c9d03 | ||
|
|
7b1c35793c | ||
|
|
1ec318561c | ||
|
|
9ac623a433 | ||
|
|
5f4eb5cfaa | ||
|
|
042ffbde44 | ||
|
|
064296e1fb | ||
|
|
a1fbda06ad | ||
|
|
52fbb1468a | ||
|
|
a76369eb86 | ||
|
|
57fc914821 | ||
|
|
0b0cf76137 | ||
|
|
3f5430c3ce | ||
|
|
0d7b70459d | ||
|
|
f3ec686f8c | ||
|
|
bd5166bd11 | ||
|
|
d3fe8a02ec | ||
|
|
f5b1d67ee5 | ||
|
|
90179149c7 | ||
|
|
364be835fe | ||
|
|
4a4d121275 | ||
|
|
480effa5fc | ||
|
|
226fd308dd | ||
|
|
2ced7b790c | ||
|
|
d186f94206 | ||
|
|
83d2f97d82 | ||
|
|
37085b40c1 | ||
|
|
325d58b694 | ||
|
|
0fafd348e7 | ||
|
|
13f68f1bd8 | ||
|
|
c22003a3da | ||
|
|
a690c665fb | ||
|
|
59ab4fe956 | ||
|
|
e69ab1499f | ||
|
|
3258a25f76 |
@@ -0,0 +1,16 @@
|
||||
.git
|
||||
.idea
|
||||
.agents
|
||||
.codex
|
||||
node_modules
|
||||
vendor
|
||||
public/build
|
||||
storage/logs
|
||||
storage/framework/cache
|
||||
storage/framework/sessions
|
||||
storage/framework/views
|
||||
tests
|
||||
Doc
|
||||
docs
|
||||
*.zip
|
||||
.phpunit.result.cache
|
||||
@@ -4,6 +4,11 @@ APP_KEY=
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://localhost:8000
|
||||
|
||||
# Separate from publication. Bind only an explicitly authorised published rule version.
|
||||
INVESTMOZ_IVA_CONSUMER_ENABLED=false
|
||||
INVESTMOZ_IVA_CONSUMER_RULE_ID=
|
||||
INVESTMOZ_IVA_CONSUMER_RULE_VERSION=0
|
||||
|
||||
APP_LOCALE=en
|
||||
APP_FALLBACK_LOCALE=en
|
||||
APP_FAKER_LOCALE=en_US
|
||||
|
||||
@@ -12,3 +12,6 @@ database/data/economic-references-lot-01.json text eol=crlf
|
||||
CHANGELOG.md export-ignore
|
||||
README.md export-ignore
|
||||
.github/workflows/browser-tests.yml export-ignore
|
||||
|
||||
# Preserve the original archived BM HTML bytes and whitespace.
|
||||
docs/investmoz/simulations/source-archive/BM-Mercado-Monetario-MAIBOR-20261025.html -text -diff
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Instruções permanentes do projeto InvesteMoz
|
||||
|
||||
## Percurso adaptativo — decisão expressa da Tempo, 23/10/2026
|
||||
|
||||
Carteira/projectos âncora e percurso adaptativo têm diagnósticos distintos, mas fazem parte da mesma experiência e responsabilidade de correcção. Separar o diagnóstico não autoriza adiamento, desligamento do percurso ou perda de contexto entre corredor/localização, oportunidades, associações documentadas a âncoras/clusters, dossier e simulador. A reposição prioritária só se considera demonstrada com causa delimitada e disponibilidade recuperada, reutilizando o inventário e os recibos existentes; melhorias noutro ponto não a comprovam. Consultar os registos de reposição antes de voltar a declarar causa desconhecida ou registos desaparecidos.
|
||||
|
||||
Apresentar apenas o necessário ao investimento em preparação, com entrada por ideia, oportunidade, sector ou localização, reutilizando informação válida e autorizada da oportunidade, perfil, organização, dossier e fontes anteriores. As etapas são adaptáveis, não seis formulários obrigatórios. Não sobrescrever edições deliberadas; explicar divergências e impactos antes da confirmação. Conservar escolhas ao avançar, regressar, actualizar e autenticar-se. Seleccionar opções únicas e pedir apenas dados em falta ou desactualizados.
|
||||
|
||||
Ocultar campos e acções sem aplicação, conservando explicação breve e histórico; desconhecido não significa não aplicável. Na selecção múltipla, partilhar dados comuns sem perder os requisitos específicos de cada oportunidade. Consulta pública livre; autenticação no momento de manifestar interesse ou iniciar operação privada. Relatórios e exportações devem reflectir o contexto e as etapas efectivamente aplicáveis. O utilizador deve perceber onde está, o que falta e a próxima acção. Aperfeiçoar os componentes existentes por incrementos e registar cobertura na matriz existente; esta instrução não declara concluída a sua implementação transversal.
|
||||
|
||||
## Regras permanentes do InvesteMoz — decisão da Tempo, 12/10/2026
|
||||
|
||||
1. O portal InvesteMoz é propriedade da Tempo, Lda.
|
||||
@@ -39,3 +47,20 @@ Referenciar estas orientações nos requisitos correspondentes da matriz existen
|
||||
- Preservar o ficheiro original, a proveniência, o identificador exacto, a edição/data, o hash e o histórico. Não marcar autenticidade, vigência, direitos ou scan como confirmados sem evidência.
|
||||
- Para fontes fiscais, inventariar também as fontes não analisadas e os diplomas/artigos sem correspondência documental. Parâmetros ausentes ou ambiguidades permanecem indeterminados; não usar zero nem a taxa mais recente como substituto.
|
||||
- Antes de aplicar mudanças em dados activos, confirmar backup/restauro e a acção autenticada que continua necessária. Testes e migrações devem usar exclusivamente uma base QA isolada com guarda contra a base activa.
|
||||
|
||||
|
||||
## Execução das fontes e decisões — orientação permanente da Tempo, 22/10/2026
|
||||
|
||||
A legislação, os formulários e os procedimentos oficiais disponibilizados são fontes válidas para implementar os requisitos. As decisões e procedimentos da Tempo orientam a sua utilização no portal. Traduzir essas fontes em campos, regras, documentos, cálculos e percursos executáveis com rastreabilidade, sem exigir nova validação jurídica genérica ou criar aprovadores, restrições ou condições por interpretação do Codex.
|
||||
|
||||
Uma divergência concreta deve identificar os trechos, períodos e comportamento afectados; prosseguir com os restantes requisitos. Uma decisão de implementação em falta deve ser apresentada especificamente à Tempo, sem a substituir por regra inventada. Rever e remover bloqueios anteriores sem fundamento numa fonte aplicável ou decisão expressa da Tempo, preservando dados e histórico. A rastreabilidade explica a execução e não constitui uma autoridade adicional. Mantêm-se os limites autorizados de QA e das alterações no activo.
|
||||
|
||||
## Preservação do concluído — pedido expresso da Tempo, 23/10/2026
|
||||
|
||||
Antes de avançar com novas rondas de testes/validações, inventariar na matriz e no manual existentes as funcionalidades concluídas e as funcionalidades desaparecidas, e repor as perdas confirmadas. Preservar as aprovações, dados, originais, relações, versões, histórico e acessos já concluídos. Não transformar uma entrega anterior em funcionalidade nova nem exigir novamente a decisão organizacional já registada.
|
||||
|
||||
Comparar código, schema, dados, configuração e permissões entre o último estado demonstrado e o destino. Distinguir eliminação, perda de visibilidade, diferença de ambiente, pendência real e estado documental desactualizado; uma página vazia ou a falta de nova prova não apagam a aceitação anterior. Reutilizar as provas aceites e conferir apenas o delta da reposição. Cada entrega seguinte deve explicar qualquer redução do âmbito previamente disponível, em vez de a aceitar como consequência normal da implementação.
|
||||
|
||||
Transporte privado não equivale à revogação de uma divulgação anterior aprovada. Reconciliar a decisão anterior de forma delimitada e auditada, sem publicar automaticamente conteúdos novos, reviver exemplares arquivados ou sobrescrever edições posteriores. Mantêm-se backup/restauro, autenticação e os limites concretos de cada tarefa.
|
||||
|
||||
Escolha técnica de verificação: comparar dados protegidos por segurança por linha (RLS) com identidades e contexto de acesso equivalentes. Uma leitura da aplicação sem actor pode ocultar registos que o utilizador do backup consegue ler; confirmar essa diferença antes de declarar perda ou propor reposição. Esta orientação não altera permissões do portal nem autoriza contornar RLS numa operação da equipa.
|
||||
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
+342
File diff suppressed because one or more lines are too long
Binary file not shown.
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\User;
|
||||
use App\Services\SimulationTaxParameterResolver;
|
||||
use App\Services\SimulationTaxRuleExpression;
|
||||
use App\Services\SimulationTaxRuleGovernance;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/** Explicit registration: never run during migration, deployment or document import. */
|
||||
class RegisterFiscalQaDraft extends Command
|
||||
{
|
||||
protected $signature = 'fiscal:qa-register-iva {actor : Existing QA editor ID} {source : Existing accepted legal source UUID}';
|
||||
|
||||
protected $description = 'Cadastrar apenas o rascunho IVA do primeiro lote numa base QA isolada, sem publicação';
|
||||
|
||||
public function handle(SimulationTaxRuleGovernance $governance): int
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 403, 'O cadastro deste lote só é permitido na base QA isolada.');
|
||||
$actor = User::findOrFail($this->argument('actor'));
|
||||
$source = InvestmentLegalSource::findOrFail($this->argument('source'));
|
||||
abort_unless($source->validation_status === 'validated' && $source->diploma === 'Lei 22/2022'
|
||||
&& $source->article === 'Artigo 17(1)', 422, 'Seleccione a referência aceite da taxa geral, Lei 22/2022, artigo 17(1).');
|
||||
$payload = json_decode(file_get_contents(database_path('qa/iva-general-net-v1.json')), true, flags: JSON_THROW_ON_ERROR);
|
||||
$actualHash = hash_file('sha256', base_path('docs/investmoz/simulations/source-archive/Lei-22-2022-IVA-republicada-BR-250-2-suplemento.pdf'));
|
||||
abort_unless(hash_equals($payload['source_sha256'], $actualHash), 422, 'O exemplar não corresponde ao hash da ficha.');
|
||||
$payload['legal_source_id'] = (string) $source->id;
|
||||
app(SimulationTaxRuleExpression::class)->validate($payload['rule_definition']);
|
||||
app(SimulationTaxParameterResolver::class)->validateParameters($payload['parameters']);
|
||||
$existing = $governance->listing($actor, ['rule_code' => $payload['rule_code']])->getCollection()
|
||||
->firstWhere('rule_version', 1);
|
||||
if ($existing) {
|
||||
foreach ($payload as $field => $value) {
|
||||
$stored = $existing->attributesToArray()[$field] ?? null;
|
||||
abort_unless($stored == $value, 409, 'O cadastro existente difere desta ficha; não será sobrescrito.');
|
||||
}
|
||||
abort_unless($existing->status === 'draft', 409, 'A versão existente já não é um rascunho.');
|
||||
$this->line(json_encode(['id' => $existing->id, 'status' => 'draft', 'reused' => true], JSON_THROW_ON_ERROR));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
$rule = $governance->create($actor, $payload);
|
||||
$this->line(json_encode(['id' => $rule->id, 'status' => $rule->status, 'reused' => false], JSON_THROW_ON_ERROR));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -37,11 +37,17 @@ class SimulationController extends Controller
|
||||
$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;
|
||||
$organizationId = $validated['organization_id'] ?? null;
|
||||
$execution->authorizeOrganization($actorId, $organizationId);
|
||||
$result = $execution->create($data, $actorId, $organizationId, $token, $key);
|
||||
if (($validated['scenario_kind'] ?? null) === 'fiscal_rule_published') {
|
||||
$input = array_intersect_key($validated, array_flip(['base', 'currency', 'reference_date', 'operation', 'scope_declared', 'monthly_sales', 'sales_vat_basis']));
|
||||
$input['scope_declared'] = (bool) $input['scope_declared'];
|
||||
$result = $execution->createPublishedFiscal($input, $actorId, $organizationId, $token, $key);
|
||||
} else {
|
||||
$data = ['base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
|
||||
'reduction' => (string) ($validated['reduction'] ?? '0')];
|
||||
$result = $execution->create($data, $actorId, $organizationId, $token, $key);
|
||||
}
|
||||
$simulation = $result['simulation'];
|
||||
$body = ['data' => $simulation, 'replayed' => $result['replayed']];
|
||||
if ($actorId === null) {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Services\SimulationFormDrafts;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SimulationOfferDocumentController extends Controller
|
||||
{
|
||||
public function store(Request $request, string $id, SimulationFormDrafts $drafts)
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$drafts->find($id, $request);
|
||||
// Same private document infrastructure and technical file limit as investment attachments.
|
||||
$request->validate(['file' => ['required', 'file', 'mimetypes:application/pdf,text/plain,image/png,image/jpeg', 'max:10240']]);
|
||||
$file = $request->file('file');
|
||||
$hash = hash_file('sha256', $file->getRealPath());
|
||||
$existing = DB::table('documents')->where('source_system', 'simulation-fiscal-offer')->where('external_id', $id)->where('sha256', $hash)->whereNull('deleted_at')->first();
|
||||
if ($existing) {
|
||||
return response()->json(['data' => $this->metadata($id, $existing)], 200)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
$documentId = (string) Str::uuid();
|
||||
$key = $file->storeAs('simulation-offers/'.$id, $documentId, 'local');
|
||||
abort_unless(is_string($key), 500);
|
||||
try {
|
||||
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'simulation-fiscal-offer', 'external_id' => $id,
|
||||
'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $key,
|
||||
'sha256' => $hash, 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id,
|
||||
'status' => 'quarantined', 'data_classification' => 'confidential']);
|
||||
} catch (\Throwable $e) {
|
||||
Storage::disk('local')->delete($key);
|
||||
throw $e;
|
||||
}
|
||||
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
|
||||
return response()->json(['data' => $this->metadata($id, DB::table('documents')->where('id', $documentId)->first())], 201)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function index(Request $request, string $id, SimulationFormDrafts $drafts)
|
||||
{
|
||||
abort_unless(Str::isUuid($id), 404);
|
||||
$drafts->find($id, $request);
|
||||
$documents = DB::table('documents')->where('source_system', 'simulation-fiscal-offer')->where('external_id', $id)->whereNull('deleted_at')->get();
|
||||
return response()->json(['data' => $documents->map(fn ($doc) => $this->metadata($id, $doc))])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function download(Request $request, string $id, string $document, SimulationFormDrafts $drafts)
|
||||
{
|
||||
abort_unless(Str::isUuid($id) && Str::isUuid($document), 404);
|
||||
$drafts->find($id, $request);
|
||||
$doc = DB::table('documents')->where('id', $document)->where('source_system', 'simulation-fiscal-offer')->where('external_id', $id)->whereNull('deleted_at')->first();
|
||||
abort_unless($doc, 404);
|
||||
abort_unless($doc->status === 'active' && $doc->malware_scan_status === 'clean' && hash_equals(trim($doc->sha256), (string) $doc->malware_scanned_sha256), 409, 'Anexo conservado; descarga disponível após análise antimalware concluída.');
|
||||
$root = realpath(Storage::disk('local')->path('simulation-offers/'.$id));
|
||||
$path = realpath(Storage::disk('local')->path($doc->storage_key));
|
||||
abort_unless($root && $path && str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR)) && is_file($path), 404);
|
||||
abort_unless(hash_equals(trim($doc->sha256), hash_file('sha256', $path)), 409, 'Conteúdo do anexo diverge do hash registado.');
|
||||
return response()->download($path, basename($doc->file_name), ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
private function metadata(string $id, object $doc): array
|
||||
{
|
||||
return ['id' => $doc->id, 'draftId' => $id, 'name' => $doc->file_name, 'sha256' => trim($doc->sha256),
|
||||
'scan' => $doc->malware_scan_status, 'url' => '/api/v1/simulation-drafts/'.$id.'/offer-documents/'.$doc->id];
|
||||
}
|
||||
}
|
||||
@@ -19,13 +19,15 @@ class SimulationTaxParameterController extends Controller
|
||||
$input['period_start'],
|
||||
$input['period_end'],
|
||||
$input['context'] ?? [],
|
||||
$input['component'] === 'IVA',
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'component' => $input['component'],
|
||||
'period' => ['start' => $input['period_start'], 'end' => $input['period_end']],
|
||||
'assumptions' => $input['context'] ?? [],
|
||||
'parameters' => $data,
|
||||
'parameters' => $input['component'] === 'IVA' ? $data['parameters'] : $data,
|
||||
'diagnostics' => $input['component'] === 'IVA' ? $data['diagnostics'] : [],
|
||||
])->header('Cache-Control', 'no-store');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Services\ClusterCompetitiveness;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class ClusterCompetitivenessController extends Controller
|
||||
{
|
||||
public function show(EconomicCluster $cluster, ClusterCompetitiveness $service): JsonResponse
|
||||
{
|
||||
return response()->json($service->management($cluster->id))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function change(Request $request, EconomicCluster $cluster, string $action, ClusterCompetitiveness $service): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['expected_version' => 'required|integer|min:0',
|
||||
'draft' => $action === 'saved' ? 'required|array:version,clusterId,sector,region,forces' : 'prohibited',
|
||||
'revision' => $action === 'restored' ? 'required|integer|min:1' : 'prohibited',
|
||||
'reason' => in_array($action, ['approved', 'withdrawn'], true) ? 'required|string|min:10|max:3000' : 'nullable|string|max:3000']);
|
||||
|
||||
return response()->json($service->change($cluster, $request->user()->id, (int) $data['expected_version'], $action, $data))
|
||||
->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\CorridorAgribusinessOpportunities;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityPromotion;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Inertia;
|
||||
|
||||
final class CorridorAgribusinessController extends Controller
|
||||
{
|
||||
private function manifest(CorridorAgribusinessOpportunities $service): string
|
||||
{
|
||||
return hash('sha256', json_encode($service->entries(), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function show(Request $request, CorridorAgribusinessOpportunities $service)
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_unless($access->internalAssignment($request->user(), 'investment_project') || $access->has($request->user(), 'publisher'), 403);
|
||||
$records = Opportunity::withTrashed()->whereIn('management_creation_key', array_column($service->entries(), 'key'))->get()->keyBy('management_creation_key');
|
||||
foreach ($records as $record) abort_unless($access->canView($request->user(), $record), 403);
|
||||
return Inertia::render('management/corridor-agribusiness', ['manifestHash' => $this->manifest($service),
|
||||
'canRegister' => (bool) $access->internalAssignment($request->user(), 'investment_project'),
|
||||
'entries' => array_map(function ($entry) use ($records) {
|
||||
$r = $records->get($entry['key']);
|
||||
return [...$entry, 'id' => $r?->id, 'status' => $r?->status, 'href' => $r ? '/oportunidades/'.$r->slug : null];
|
||||
}, $service->entries())]);
|
||||
}
|
||||
|
||||
public function register(Request $request, CorridorAgribusinessOpportunities $service)
|
||||
{
|
||||
$data = $request->validate(['manifest_hash' => 'required|string|size:64', 'confirm' => 'required|accepted']);
|
||||
abort_unless(hash_equals($this->manifest($service), $data['manifest_hash']), 409, 'A fonte mudou; recupere a prévia.');
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$grant = $access->internalAssignment($request->user(), 'investment_project');
|
||||
abort_unless($grant && $access->mfa($request->user()), 403, 'Use a designação existente e MFA recente.');
|
||||
return response()->json(['records' => $service->register($request->user(), $grant->organization_id)]);
|
||||
}
|
||||
|
||||
public function preview(Request $request, CorridorAgribusinessOpportunities $service)
|
||||
{
|
||||
$previews = [];
|
||||
foreach ($service->entries() as $entry) {
|
||||
$record = Opportunity::where('management_creation_key', $entry['key'])->firstOrFail();
|
||||
$input = data_get($record->workflow_context, 'promotional_summary.input');
|
||||
abort_unless(is_array($input), 409, 'Complete a selecção pública na divulgação individual.');
|
||||
$previews[] = ['id' => $record->id, ...app(OpportunityPromotion::class)->preview($request->user(), $record,
|
||||
[...$input, 'source_date' => $input['source_date'] ?: null, 'action' => 'disclose', 'etag' => app(OpportunityManagement::class)->etag($record)])];
|
||||
}
|
||||
return response()->json(['previews' => $previews]);
|
||||
}
|
||||
|
||||
public function disclose(Request $request, CorridorAgribusinessOpportunities $service)
|
||||
{
|
||||
$data = $request->validate(['confirm' => 'required|accepted', 'reason' => 'required|string|min:20|max:1000',
|
||||
'previews' => 'required|array|size:34', 'previews.*.id' => 'required|integer|distinct',
|
||||
'previews.*.token' => 'required|string|max:300000', 'previews.*.operation_key' => 'required|uuid|distinct']);
|
||||
$expected = Opportunity::whereIn('management_creation_key', array_column($service->entries(), 'key'))->pluck('id')->sort()->values()->all();
|
||||
$supplied = array_column($data['previews'], 'id'); sort($supplied);
|
||||
abort_unless($expected === $supplied && count($expected) === 34, 409, 'A prévia deve identificar exactamente as 34 fichas deste lote.');
|
||||
return response()->json(DB::transaction(function () use ($request, $data) {
|
||||
$result = [];
|
||||
foreach ($data['previews'] as $preview) $result[] = app(OpportunityPromotion::class)->confirm($request->user(), $preview['id'],
|
||||
[...$preview, 'confirm' => true, 'reason' => $data['reason']]);
|
||||
return ['records' => $result];
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -81,31 +81,18 @@ class EditorialArticleController extends Controller
|
||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource(request()->user(), $id);
|
||||
$r = DB::table('portal_resources')->find($id);
|
||||
abort_unless($r, 404);
|
||||
$content = $r->editorial_content ? json_decode($r->editorial_content, true) : null;
|
||||
if ($content === null) {
|
||||
$document = DB::table('documents')->find($r->document_id);
|
||||
if ($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
|
||||
&& in_array($document->media_type, ['text/plain', 'application/json'], true)) {
|
||||
$binary = app(VerifiedDocumentBinary::class)->respond($document);
|
||||
$bytes = $binary instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse
|
||||
? file_get_contents($binary->getFile()->getPathname()) : $binary->getContent();
|
||||
$original = json_decode($bytes, true);
|
||||
if (is_array($original) && ($original['format'] ?? '') === 'investmoz-legacy-article-v1') {
|
||||
$html = preg_replace('~</(?:p|div|li|h[1-6])>|<br\s*/?>~i', "\n\n", $original['content_html'] ?? '');
|
||||
$content = ['body' => trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')), 'image_resource_id' => null];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Inertia::render('portal/article-editor', ['resource' => ['id' => $r->id, 'title' => $r->title, 'metadata_version' => $r->metadata_version],
|
||||
'content' => $content, 'images' => $this->publicResources()->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->get(['r.id', 'r.title']),
|
||||
'revisions' => DB::table('portal_resource_revisions')->where('resource_id', $id)->orderByDesc('revision_no')->get(['revision_no', 'change_type', 'created_at'])]);
|
||||
$reading = app(\App\Services\EditorialReading::class);
|
||||
$original = $reading->original($r);
|
||||
$content = $reading->content($r, $original);
|
||||
return Inertia::render('portal/article-editor', ['resource' => ['id' => $r->id, 'title' => $r->title, 'metadata_version' => $r->metadata_version, 'published' => (bool) $r->published],
|
||||
'content' => $content, 'source' => $original ? array_intersect_key($original, array_flip(['source_url', 'published_at', 'modified_at', 'legacy_id', 'image_source_url'])) : null, 'images' => $this->publicResources()->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->get(['r.id', 'r.title']),
|
||||
'revisions' => DB::table('portal_resource_revisions')->where('resource_id', $id)->orderByDesc('revision_no')->get(['revision_no', 'change_type', 'created_at'])])->toResponse(request())->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function save(Request $request, int $id)
|
||||
{
|
||||
$this->installed();
|
||||
$data = $request->validate(['body' => ['required', 'string', 'max:100000'], 'image_resource_id' => ['nullable', 'integer'], 'metadata_version' => ['required', 'integer', 'min:1']]);
|
||||
$data = $this->validateContent($request);
|
||||
DB::transaction(function () use ($request, $id, $data) {
|
||||
$r = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
|
||||
abort_unless($r, 404);
|
||||
@@ -118,7 +105,7 @@ class EditorialArticleController extends Controller
|
||||
if ($body === '') {
|
||||
throw ValidationException::withMessages(['body' => 'Escreva o corpo do artigo.']);
|
||||
}
|
||||
$content = ['format' => 1, 'body' => $body, 'image_resource_id' => $data['image_resource_id'] ?? null];
|
||||
$content = $this->edition($r, $data);
|
||||
$revision = (int) $r->metadata_version + 1;
|
||||
DB::table('portal_resources')->where('id', $id)->update(['editorial_content' => json_encode($content, JSON_THROW_ON_ERROR), 'published' => false, 'approved_by' => null, 'metadata_version' => $revision, 'last_reviewed_by' => $request->user()->id, 'last_reviewed_at' => now(), 'updated_at' => now()]);
|
||||
$resource = DB::table('portal_resources')->find($id);
|
||||
@@ -130,16 +117,46 @@ class EditorialArticleController extends Controller
|
||||
return redirect('/management/portal-services/resources/'.$id.'/article')->with('success', 'Artigo guardado como rascunho. Publique expressamente no acervo quando estiver pronto.');
|
||||
}
|
||||
|
||||
public function show(int $id)
|
||||
private function validateContent(Request $request): array
|
||||
{
|
||||
return $request->validate(['body' => ['required', 'string', 'max:100000'], 'image_resource_id' => ['nullable', 'integer'], 'image_mode' => ['nullable', 'in:original,selected,none'], 'metadata_version' => ['required', 'integer', 'min:1']]);
|
||||
}
|
||||
|
||||
private function edition(object $resource, array $data): array
|
||||
{
|
||||
$reading = app(\App\Services\EditorialReading::class);
|
||||
$original = $reading->original($resource);
|
||||
$mode = $data['image_mode'] ?? (!empty($data['image_resource_id']) ? 'selected' : 'none');
|
||||
if ($mode === 'selected') abort_unless(!empty($data['image_resource_id']) && $reading->publicResources()->where('r.id', $data['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->exists(), 422, 'Escolha uma imagem pública disponível na biblioteca.');
|
||||
return ['format' => 1, 'body' => trim($data['body']), 'image_mode' => $mode, 'image_resource_id' => $mode === 'selected' ? (int)$data['image_resource_id'] : null,
|
||||
'preserve_original_html' => $original && trim($data['body']) === $reading->plain($original['content_html'])];
|
||||
}
|
||||
|
||||
public function preview(Request $request, int $id)
|
||||
{
|
||||
$this->installed();
|
||||
$r = $this->publicResources()->where('r.id', $id)->first(['r.id', 'r.title', 'r.description', 'r.editorial_content', 'r.document_id', 'd.issuer']);
|
||||
abort_unless($r && $r->editorial_content, 404);
|
||||
$content = json_decode($r->editorial_content, true);
|
||||
// Recheck the original bytes using the same binary gate as the library.
|
||||
$binary = app(VerifiedDocumentBinary::class)->respond($this->publicResources()->where('r.id', $id)->first(['r.*', 'd.*']));
|
||||
$image = ! empty($content['image_resource_id']) ? $this->publicResources()->where('r.id', $content['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->value('r.id') : null;
|
||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||
$resource = DB::table('portal_resources')->find($id); abort_unless($resource, 404);
|
||||
return Inertia::render('portal/article', ['article' => app(\App\Services\EditorialReading::class)->reading($resource, null, true)])
|
||||
->toResponse($request)->header('Cache-Control', 'private, no-store')->header('X-Robots-Tag', 'noindex, nofollow');
|
||||
}
|
||||
|
||||
return Inertia::render('portal/article', ['article' => ['id' => $id, 'title' => $r->title, 'description' => $r->description, 'author' => $r->issuer, 'body' => $content['body'], 'image_url' => $image ? '/documentos/'.$image.'/view' : null, 'original_url' => '/documentos/'.$id]]);
|
||||
public function previewContent(Request $request, int $id)
|
||||
{
|
||||
$this->installed();
|
||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||
$resource = DB::table('portal_resources')->find($id); abort_unless($resource, 404);
|
||||
$data = $this->validateContent($request);
|
||||
abort_unless((int)$resource->metadata_version === (int)$data['metadata_version'], 409, 'A revisão mudou; recupere antes de rever a prévia.');
|
||||
return response()->json(['article' => app(\App\Services\EditorialReading::class)->reading($resource, $this->edition($resource, $data), true)])
|
||||
->header('Cache-Control', 'private, no-store')->header('X-Robots-Tag', 'noindex, nofollow');
|
||||
}
|
||||
|
||||
public function show(Request $request, int $id)
|
||||
{
|
||||
$this->installed();
|
||||
$resource = app(\App\Services\EditorialReading::class)->publicResources()->where('r.id', $id)->first(['r.*']);
|
||||
abort_unless($resource, 404);
|
||||
return Inertia::render('portal/article', ['article' => app(\App\Services\EditorialReading::class)->reading($resource)])->toResponse($request)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\InvestmentComplements;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
final class InvestmentComplementController extends Controller
|
||||
{
|
||||
public function index(Request $request, InvestmentComplements $service)
|
||||
{
|
||||
$data = $request->validate(['origin' => [\Illuminate\Validation\Rule::requiredIf(!$request->has('contexts')), 'nullable', 'string', 'max:100'], 'territory_id' => 'nullable|uuid',
|
||||
'contexts' => 'sometimes|array|max:100', 'contexts.*' => 'array:origin,territory_id', 'contexts.*.origin' => 'required|string|max:100', 'contexts.*.territory_id' => 'nullable|uuid']);
|
||||
$items = [];
|
||||
$issues = [];
|
||||
foreach ($data['contexts'] ?? [['origin' => $data['origin'], 'territory_id' => $data['territory_id'] ?? null]] as $context) {
|
||||
try {
|
||||
$items = [...$items, ...$service->options($context['origin'], $context['territory_id'] ?? null)];
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException|\Symfony\Component\HttpKernel\Exception\HttpException $e) {
|
||||
$status = $e instanceof \Symfony\Component\HttpKernel\Exception\HttpException ? $e->getStatusCode() : 404;
|
||||
if (!isset($data['contexts']) || $status !== 404) throw $e;
|
||||
$issues[] = ['origin' => $context['origin'], 'message' => 'Uma referência escolhida deixou de estar disponível para consulta pública. A relação guardada conserva-se no dossier; os outros complementos continuam disponíveis.'];
|
||||
}
|
||||
}
|
||||
return response()->json(isset($data['contexts']) ? ['items' => $items, 'issues' => $issues] : $items)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,10 @@ class InvestmentDiscoveryController extends Controller
|
||||
}
|
||||
|
||||
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(false, $filters),
|
||||
'corridorGroups' => ($filters['view'] ?? '') === 'corridors' ? app(\App\Services\OpportunityCorridorExplorer::class)->groups($filters) : [],
|
||||
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
|
||||
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
|
||||
'guides' => app(\App\Services\SectorInvestment::class)->guides(\App\Models\Sector::where('slug', $filters['sector'] ?? '')->where('is_active', true)->whereNotNull('published_at')->first()),
|
||||
'results' => $catalogue->query($filters)->paginate(12)->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record)),
|
||||
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
|
||||
'territorial' => $this->territorial($filters)]);
|
||||
}
|
||||
@@ -72,7 +74,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
|
||||
public function search(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
{
|
||||
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString());
|
||||
return response()->json($catalogue->query($catalogue->filters($request))->paginate($request->integer('per_page', 12))->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record)));
|
||||
}
|
||||
|
||||
public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||
@@ -87,7 +89,7 @@ class InvestmentDiscoveryController extends Controller
|
||||
$data = $request->validate(['zone_id' => ['nullable', 'uuid'], 'from_dossier' => ['nullable', 'uuid']]);
|
||||
$dossierOrigin = isset($data['from_dossier']) ? InvestmentPortfolioController::visible()->whereKey($data['from_dossier'])->firstOrFail() : null;
|
||||
if ($dossierOrigin) {
|
||||
$linked = false;
|
||||
$linked = in_array($record->id, app(\App\Services\CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($dossierOrigin), true);
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
|
||||
if ($dossierOrigin->$foreign && DB::table('opportunity_'.$relation)->where('opportunity_id', $record->id)->where($foreign, $dossierOrigin->$foreign)->exists()) {
|
||||
$linked = true;
|
||||
@@ -105,7 +107,8 @@ class InvestmentDiscoveryController extends Controller
|
||||
$returnFilters = $request->query();
|
||||
unset($returnFilters['zone_id'], $returnFilters['from_dossier']);
|
||||
|
||||
return Inertia::render('investment/detail', ['record' => $record, 'context' => $catalogue->context($record->id), 'zone_origin' => $origin,
|
||||
return Inertia::render('investment/detail', ['complements' => app(\App\Services\InvestmentComplements::class)->options('opportunity:'.$record->id), 'record' => $record, 'context' => $catalogue->context($record->id), 'zone_origin' => $origin,
|
||||
'guides' => app(\App\Services\SectorInvestment::class)->guides($record->sector),
|
||||
'dossierOrigin' => $dossierOrigin ? ['id' => $dossierOrigin->id, 'title' => $dossierOrigin->title] : null,
|
||||
'returnUrl' => $returnFilters === [] ? '/oportunidades' : '/oportunidades?'.http_build_query($returnFilters)]);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ class InvestmentLegalSourceController extends Controller
|
||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
|
||||
|
||||
return DB::transaction(function () use ($request, $id, $action, $data) {
|
||||
DB::select('select pg_advisory_xact_lock(261022, hashtext(?))', [$id]);
|
||||
$source = InvestmentLegalSource::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_if((int) $source->version_no !== (int) $data['version_no'], 409, 'Versão alterada.');
|
||||
if ($action === 'validate') {
|
||||
|
||||
@@ -61,8 +61,15 @@ class InvestmentPortfolioController extends Controller
|
||||
{
|
||||
$management = $request->routeIs('management.portfolio*');
|
||||
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'kind' => ['nullable', 'in:corridor,cluster,project'],
|
||||
'sector' => ['nullable', 'string', 'max:500'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
|
||||
$query = $management ? InvestmentDossier::query() : self::visible();
|
||||
$sectorOptions = ($management ? InvestmentDossier::query() : self::visible())
|
||||
->whereNotNull('content->sector')->get()->pluck('content.sector')
|
||||
->filter(fn ($sector) => is_string($sector) && trim($sector) !== '')->unique()->sort()->values();
|
||||
if (! empty($filters['sector'])) {
|
||||
$query->where('content->sector', $filters['sector']);
|
||||
}
|
||||
if (! empty($filters['kind'])) {
|
||||
$query->whereNotNull($filters['kind'].'_id');
|
||||
}
|
||||
@@ -76,7 +83,7 @@ class InvestmentPortfolioController extends Controller
|
||||
}
|
||||
|
||||
return Inertia::render('portfolio/index', ['records' => $query->orderBy('title')->paginate(30)->withQueryString(),
|
||||
'management' => $management, 'filters' => $filters, 'territorySelection' => $territorySelection]);
|
||||
'management' => $management, 'filters' => $filters, 'sectors' => $sectorOptions, 'territorySelection' => $territorySelection]);
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id): Response
|
||||
@@ -105,6 +112,7 @@ class InvestmentPortfolioController extends Controller
|
||||
|
||||
$opportunities = Opportunity::published()->where(function ($query) use ($record) {
|
||||
$query->whereRaw('false');
|
||||
$query->orWhereIn('id', app(\App\Services\CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($record));
|
||||
foreach (['clusters' => 'cluster_id', 'corridors' => 'corridor_id', 'projects' => 'project_id'] as $relation => $foreign) {
|
||||
if ($record->$foreign) {
|
||||
$query->orWhereIn('id', DB::table('opportunity_'.$relation)->where($foreign, $record->$foreign)->select('opportunity_id'));
|
||||
@@ -130,12 +138,20 @@ class InvestmentPortfolioController extends Controller
|
||||
->orderByDesc('updated_at')->limit(10)->get(['id', 'version', 'updated_at'])
|
||||
: collect();
|
||||
|
||||
return Inertia::render('portfolio/show', ['record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones,
|
||||
return Inertia::render('portfolio/show', ['complements' => $management ? [] : app(\App\Services\InvestmentComplements::class)->options('portfolio:'.$record->id), 'record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones,
|
||||
'anchorProject' => $anchorProject, 'existingSubmissions' => $existingSubmissions,
|
||||
'competitiveness' => $record->cluster_id ? app(\App\Services\ClusterCompetitiveness::class)->publicData($record->cluster_id) : null,
|
||||
'geography' => app(InvestmentRelations::class)->dossier($record, $management),
|
||||
'origin' => $origin ? ['id' => $origin->id, 'title' => $origin->title] : null, 'opportunities' => $opportunities, 'chains' => $chains]);
|
||||
}
|
||||
|
||||
public function resumeInterest(Request $request, string $id): RedirectResponse
|
||||
{
|
||||
self::visible()->findOrFail($id);
|
||||
$data = $request->validate(['catalogue_query' => ['nullable', 'string', 'max:4000']]);
|
||||
return redirect('/carteira/'.$id.'?'.http_build_query([...$data, 'prepare_interest' => '1']));
|
||||
}
|
||||
|
||||
public function save(Request $request, InvestmentDossier $dossier): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'title' => ['required', 'string', 'max:255'], 'source' => ['required', 'string', 'max:2000'],
|
||||
|
||||
@@ -50,6 +50,7 @@ class InvestmentStructureController extends Controller
|
||||
->whereNull('origins.deleted_at')->whereNull('destinations.deleted_at')->whereNull('value_chain_links.deleted_at')
|
||||
->orderBy('origins.code')->orderBy('destinations.code')
|
||||
->get(['value_chain_links.id', 'origins.name as origin', 'destinations.name as destination', 'link_type']) : [],
|
||||
'competitiveness' => $structure === 'clusters' && $id ? app(\App\Services\ClusterCompetitiveness::class)->management($id) : null,
|
||||
'viewerId' => $request->user()->id,
|
||||
'memberships' => $structure === 'clusters' && $id ? DB::table('cluster_projects')
|
||||
->join('projects', 'projects.id', '=', 'cluster_projects.project_id')
|
||||
|
||||
@@ -170,8 +170,10 @@ class InvestmentSubmissionController extends Controller
|
||||
// Binding does not save form edits or assert that the context has been reviewed.
|
||||
$this->event($row, $request, 'context_bound');
|
||||
$desk->event($desk->case($request->user(), $case->id), $request->user(), 'manifestation_context_bound', ['submission_id' => $id, 'previous_case_version' => (int) $case->version]);
|
||||
|
||||
return ['case_id' => $case->id, 'version' => $row->version, 'case_version' => (int) $case->version + 1, 'replayed' => false];
|
||||
}, 3);
|
||||
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
@@ -190,11 +192,14 @@ class InvestmentSubmissionController extends Controller
|
||||
{
|
||||
$required = $submitting ? 'required' : 'nullable';
|
||||
$data = $request->validate(['version' => ['required', 'integer', 'min:1'],
|
||||
'payload' => ['required', 'array:full_name,email,phone,country,residence_country_code,incorporation_country_code,organization_country_snapshot,declared_origin_country_code,organisation,representative_role,experience,investment_capacity,profile_id,sector,objective,participation_id,partnership_id,estimated_amount,currency,horizon,location,cluster_ids,corridor_ids,project_ids,contact_consent,other_details'],
|
||||
'payload' => ['required', 'array:context_opportunity,context_opportunity_snapshot,context_reuse,full_name,email,phone,country,residence_country_code,incorporation_country_code,organization_country_snapshot,declared_origin_country_code,organisation,representative_role,experience,investment_capacity,profile_id,sector,objective,participation_id,partnership_id,estimated_amount,currency,horizon,location,cluster_ids,corridor_ids,project_ids,contact_consent,other_details'],
|
||||
'payload.organization_country_snapshot' => ['sometimes', 'array', 'max:10'],
|
||||
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
|
||||
'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
|
||||
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
|
||||
'payload.context_opportunity' => ['nullable', 'string', 'max:100'],
|
||||
'payload.context_opportunity_snapshot' => ['nullable', 'string', 'max:200000'],
|
||||
'payload.context_reuse' => ['nullable', 'string', 'max:10000'],
|
||||
'payload.other_details' => ['nullable', 'string', 'max:5000'],
|
||||
'payload.full_name' => [$required, 'string', ...($submitting ? ['min:3'] : []), 'max:150'], 'payload.email' => [$required, $submitting ? 'email:rfc' : 'string', 'max:150'],
|
||||
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => [$submitting ? 'required_without:payload.declared_origin_country_code' : 'nullable', 'nullable', 'string', 'max:100'],
|
||||
@@ -244,6 +249,9 @@ class InvestmentSubmissionController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
$bound = DB::table('desk_cases')->where('submission_id', $request->route('id'))->where('user_id', $request->user()->id)->whereNotNull('journey_id')->first();
|
||||
if ($bound) $data['payload'] = app(\App\Services\InvestmentConsumerScope::class)->bind($request->user(), $bound->id, $data['payload'], $submitting);
|
||||
else unset($data['payload']['context_opportunity'], $data['payload']['context_opportunity_snapshot']);
|
||||
return $data;
|
||||
}
|
||||
|
||||
@@ -263,7 +271,7 @@ class InvestmentSubmissionController extends Controller
|
||||
$version = DB::transaction(function () use ($request, $id, $data) {
|
||||
$row = $this->owned($request, $id, true, true);
|
||||
abort_unless($row->status === 'draft' && $row->version === (int) $data['version'], 409, 'Rascunho alterado. Recarregue antes de guardar.');
|
||||
$row->update(['payload' => $this->preserveCountrySource($row, $data['payload']), 'version' => $row->version + 1]);
|
||||
$row->update([...(isset($data['payload']['context_opportunity']) ? ['opportunity_id'=>(int)substr($data['payload']['context_opportunity'],12)] : []), 'payload' => $this->preserveCountrySource($row, $data['payload']), 'version' => $row->version + 1]);
|
||||
InvestmentSpecificNeed::where('submission_id', $id)->delete();
|
||||
foreach ($data['needs'] ?? [] as $need) {
|
||||
InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]);
|
||||
@@ -307,7 +315,8 @@ class InvestmentSubmissionController extends Controller
|
||||
return InterestRequest::findOrFail($row->interest_request_id)->reference;
|
||||
}
|
||||
abort_unless($row->version === (int) $data['version'], 409, 'Rascunho alterado. Recarregue.');
|
||||
$opportunity = $row->opportunity_id ? Opportunity::published()->findOrFail($row->opportunity_id) : null;
|
||||
$scopeKey = $data['payload']['context_opportunity'] ?? null;
|
||||
$opportunity = $scopeKey ? Opportunity::published()->findOrFail(substr($scopeKey,12)) : ($row->opportunity_id ? Opportunity::published()->findOrFail($row->opportunity_id) : null);
|
||||
if ($row->dossier_id) {
|
||||
InvestmentPortfolioController::visible()->findOrFail($row->dossier_id);
|
||||
}
|
||||
@@ -328,12 +337,14 @@ class InvestmentSubmissionController extends Controller
|
||||
'sector_interest' => $p['sector'], 'message' => $p['objective'], 'privacy_consent' => true, 'consented_at' => now(),
|
||||
'status' => 'received', 'source_page' => '/investidor/manifestacoes/'.$id,
|
||||
'metadata' => ['submission_id' => $id, 'portal_user_id' => $request->user()->id, 'dossier_id' => $row->dossier_id,
|
||||
'context_opportunity' => $p['context_opportunity'] ?? null,
|
||||
'context_opportunity_snapshot' => $p['context_opportunity_snapshot'] ?? null,
|
||||
'declared_origin_country_code' => $p['declared_origin_country_code'] ?? null,
|
||||
'residence_country_code' => $p['residence_country_code'] ?? null,
|
||||
'incorporation_country_code' => $p['incorporation_country_code'] ?? null,
|
||||
...(isset($p['organization_country_snapshot']) ? ['organization_country_snapshot' => $p['organization_country_snapshot']] : []),
|
||||
...($zoneOrigin ? ['zone_origin' => (array) $zoneOrigin] : [])]]));
|
||||
$row->update(['payload' => $p, 'version' => $row->version + 1, 'interest_request_id' => $interest->id, 'status' => 'submitted']);
|
||||
$row->update(['opportunity_id'=>$opportunity?->id, 'payload' => $p, 'version' => $row->version + 1, 'interest_request_id' => $interest->id, 'status' => 'submitted']);
|
||||
InvestmentSpecificNeed::where('submission_id', $id)->delete();
|
||||
foreach ($data['needs'] ?? [] as $need) {
|
||||
InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]);
|
||||
|
||||
@@ -19,12 +19,21 @@ class InvestmentTerritoryController extends Controller
|
||||
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
|
||||
$profile = $request->is('minhas-oportunidades/*');
|
||||
$management = $request->is('management/*') || $profile;
|
||||
$actor = $request->user();
|
||||
$access = app(PortalProfileAccess::class);
|
||||
// The general consumers use this same endpoint while authenticated.
|
||||
// Reuse the read access already granted by the private cadastral routes.
|
||||
$profileAccess = $actor && $actor->hasVerifiedEmail()
|
||||
&& ($access->grants($actor) !== [] || $access->superuser($actor));
|
||||
$internal = $profileAccess || ($actor?->hasVerifiedEmail() && $actor->can('manage-portal'));
|
||||
if ($management) {
|
||||
$access = app(PortalProfileAccess::class);
|
||||
abort_unless($profile ? ($access->grants($request->user()) !== [] || $access->superuser($request->user())) : $request->user()?->can('manage-portal'), 403);
|
||||
abort_unless($profile ? $profileAccess : $internal, 403);
|
||||
}
|
||||
|
||||
return response()->json(app(TerritoryGeometry::class)->context($data['territory_id'], $management));
|
||||
return response()->json([
|
||||
...app(TerritoryGeometry::class)->context($data['territory_id'], $internal),
|
||||
'geometry_scope' => $internal ? 'authorized_internal' : 'public',
|
||||
])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones'];
|
||||
|
||||
@@ -11,6 +11,36 @@ use Inertia\Inertia;
|
||||
|
||||
final class InvestorContextController extends Controller
|
||||
{
|
||||
private function entryComplements(Request $request): array
|
||||
{
|
||||
$data = $request->validate(['complement_origin' => 'nullable|string|max:100', 'complement_code' => 'required_with:complement_origin|string|max:40',
|
||||
'complement_target' => 'nullable|string|max:100', 'complement_territory' => 'nullable|uuid']);
|
||||
if (empty($data['complement_origin'])) return [];
|
||||
return app(\App\Services\InvestmentComplements::class)->resolve([['origin' => $data['complement_origin'], 'code' => $data['complement_code'],
|
||||
'target' => $data['complement_target'] ?? null, 'territory_id' => $data['complement_territory'] ?? null]]);
|
||||
}
|
||||
|
||||
private function entryChoices(Request $r, InvestorContext $context): array
|
||||
{
|
||||
$data = $r->validate(['source' => 'nullable|string|max:100', 'from_dossier' => 'nullable|uuid', 'opportunities' => 'sometimes|array|max:100', 'opportunities.*' => 'integer|distinct|min:1',
|
||||
'province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid']);
|
||||
$source = !empty($data['source']) ? $context->reference($data['source']) : null;
|
||||
$ids = $data['opportunities'] ?? (($source['kind'] ?? '') === 'opportunity' ? [$source['id']] : []);
|
||||
abort_if(!empty($data['from_dossier']) && !$ids, 422, 'Escolha a oportunidade associada à ficha da carteira.');
|
||||
$path = app(InvestmentGeography::class)->selection($data);
|
||||
$input = array_map(fn($id) => ['source' => 'opportunity:'.$id, ...($path ? ['territory' => 'territory:'.$path[array_key_last($path)]->id] : [])], $ids);
|
||||
if (!empty($data['from_dossier'])) $input[0]['portfolio_origins'] = [$data['from_dossier']];
|
||||
foreach ($this->entryComplements($r) as $complement) {
|
||||
$keys = array_filter([$complement['origin']['key'], $complement['target']['key'] ?? null], fn($key) => str_starts_with($key, 'opportunity:'));
|
||||
foreach ($keys as $key) {
|
||||
if (in_array($key, array_column($input, 'source'), true)) continue;
|
||||
$input[] = ['source' => $key, ...($complement['territory_id'] ? ['territory' => 'territory:'.$complement['territory_id']] : []),
|
||||
...(str_starts_with($complement['origin']['key'], 'portfolio:') ? ['portfolio_origins' => [substr($complement['origin']['key'], 10)]] : [])];
|
||||
}
|
||||
}
|
||||
return app(\App\Services\InvestmentOpportunityChoices::class)->resolve($input, [], true);
|
||||
}
|
||||
|
||||
public function current(Request $r, InvestorContext $context)
|
||||
{
|
||||
return response()->json($context->current($r->user()));
|
||||
@@ -23,7 +53,8 @@ final class InvestorContextController extends Controller
|
||||
|
||||
public function show(Request $r, string $id, InvestorContext $context)
|
||||
{
|
||||
return response()->json($context->view($r->user(), $id));
|
||||
$data = $r->validate(['opportunity' => 'nullable|string|max:100']);
|
||||
return response()->json($context->view($r->user(), $id, $data['opportunity'] ?? null));
|
||||
}
|
||||
|
||||
public function options(Request $r, InvestorContext $context)
|
||||
@@ -33,12 +64,56 @@ final class InvestorContextController extends Controller
|
||||
return response()->json($context->options($d['q'] ?? ''));
|
||||
}
|
||||
|
||||
public function corridorOptions(Request $r)
|
||||
{
|
||||
$data = $r->validate(['corridor' => ['nullable', \Illuminate\Validation\Rule::in(array_keys(config('investment_corridors')))], 'territory' => 'nullable|uuid']);
|
||||
$service = app(\App\Services\InvestmentCorridorContext::class);
|
||||
return response()->json(['corridors' => collect(config('investment_corridors'))->map(fn($entry,$key)=>['key'=>$key,'name'=>$entry['name'],'provinces'=>$service->provinces($key)])->values(),
|
||||
'parks' => $service->parks($data['corridor'] ?? null, $data['territory'] ?? null)]);
|
||||
}
|
||||
|
||||
public function saveDraft(Request $r, string $id, InvestorContext $context)
|
||||
{
|
||||
return response()->json($context->saveDraft($r->user(), $id, $r->all()));
|
||||
}
|
||||
|
||||
public function edit(Request $r, string $id, InvestorContext $context)
|
||||
{
|
||||
$data = $context->view($r->user(), $id);
|
||||
abort_unless($data['can_write'], 403);
|
||||
|
||||
return Inertia::render('investor-path/context', ['initial' => $data, 'options' => $context->options(), 'source' => $r->query('source') ? $context->reference($r->validate(['source' => 'required|string|max:100'])['source']) : null, 'territorySelection' => isset($data['context']['selection']['territory']) ? app(InvestmentGeography::class)->path($data['context']['selection']['territory']['id']) : []]);
|
||||
$entries = $this->entryChoices($r, $context);
|
||||
$choices = $entries ?: null;
|
||||
$source = $r->query('source') ? $context->reference($r->validate(['source' => 'required|string|max:100'])['source']) : null;
|
||||
if ($choices === null && ($source['kind'] ?? '') === 'opportunity') $choices = app(\App\Services\InvestmentOpportunityChoices::class)->resolve([['source' => $source['key']]]);
|
||||
$explicitChoices=$choices;
|
||||
$selectionKey=$r->validate(['selection_key'=>'nullable|uuid'])['selection_key']??null;
|
||||
$entryKey=fn($c)=>$c['opportunity']['key'].($selectionKey?'@'.$selectionKey:'');
|
||||
$entrySources=array_map($entryKey,$explicitChoices??[]);
|
||||
if ($choices !== null) $choices = app(\App\Services\InvestmentOpportunityChoices::class)->mergeEntries($data['context']['opportunity_choices'] ?? [], $choices);
|
||||
$draft = $context->draft($r->user(), $id);
|
||||
if ($draft && isset($draft['opportunity_choices'])) {
|
||||
$recovered = app(\App\Services\InvestmentOpportunityChoices::class)->resolve($draft['opportunity_choices'], $data['context']['opportunity_choices'] ?? [], true);
|
||||
$new=array_filter($explicitChoices??[],fn($c)=>!in_array($entryKey($c),$draft['entry_sources']??[],true));
|
||||
$choices = app(\App\Services\InvestmentOpportunityChoices::class)->mergeEntries($recovered, array_values($new));
|
||||
}
|
||||
$differences = [];
|
||||
foreach ($explicitChoices ?? [] as $entry) {
|
||||
$kept = collect($choices ?? [])->firstWhere('opportunity.key', $entry['opportunity']['key']);
|
||||
if ($kept && ($kept['territory']['key'] ?? null) !== ($entry['territory']['key'] ?? null)) $differences[] = ['title'=>$entry['opportunity']['title'],'saved'=>$kept['territory']['title']??'Por definir','requested'=>$entry['territory']['title']??'Por definir'];
|
||||
}
|
||||
$complements = isset($draft['complements']) ? app(\App\Services\InvestmentComplements::class)->resolve($draft['complements'], $data['context']['complements'] ?? []) : ($data['context']['complements'] ?? []);
|
||||
$entryTerritory = null;
|
||||
if (($source['kind'] ?? null) === 'portfolio') {
|
||||
$path = app(InvestmentGeography::class)->selection($r->validate(['province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid']));
|
||||
if ($path) $entryTerritory = $context->reference('territory:'.$path[array_key_last($path)]->id);
|
||||
}
|
||||
foreach ($this->entryComplements($r) as $entry) {
|
||||
$tag = 'complement:'.hash('sha256', $entry['key'].'@'.($selectionKey ?? ''));
|
||||
$entrySources[] = $tag;
|
||||
if (!in_array($tag, $draft['entry_sources'] ?? [], true)) $complements = collect([...$complements, $entry])->unique('key')->values()->all();
|
||||
}
|
||||
return Inertia::render('investor-path/context', ['entryTerritory' => $entryTerritory, 'entryComplements' => $complements, 'entryLocationDifferences'=>$differences,'entrySources'=>$entrySources,'draft' => $draft, 'requestedChoices' => $choices, 'initial' => $data, 'options' => $context->options(), 'source' => $source, 'territorySelection' => isset($data['context']['selection']['territory']) ? app(InvestmentGeography::class)->path($data['context']['selection']['territory']['id']) : ($entryTerritory ? app(InvestmentGeography::class)->path($entryTerritory['id']) : [])]);
|
||||
}
|
||||
|
||||
public function preview(Request $r, string $id, InvestorContext $context)
|
||||
@@ -55,8 +130,16 @@ final class InvestorContextController extends Controller
|
||||
{
|
||||
$d = $r->validate(['source' => 'nullable|string|max:100', 'step' => ['nullable', 'regex:/^S(0[1-9]|1[0-9])$/']]);
|
||||
$ref = isset($d['source']) ? $context->reference($d['source']) : null;
|
||||
$submissionId = $r->validate(['submission' => 'nullable|uuid'])['submission'] ?? null;
|
||||
$entrySubmission = null;
|
||||
if ($submissionId) {
|
||||
$submission = \App\Models\InvestmentSubmission::where('id', $submissionId)->where('user_id', $r->user()->id)->where('status', 'draft')->firstOrFail();
|
||||
abort_unless(($ref['kind'] ?? null) === 'portfolio' && $submission->dossier_id === $ref['id'], 422, 'Conserve a ficha de origem da manifestação.');
|
||||
$entrySubmission = ['id' => $submission->id, 'version' => $submission->version];
|
||||
}
|
||||
|
||||
return Inertia::render('investor-path/context-start', ['contexts' => $path->contexts($r->user()), 'source' => $ref, 'step' => $d['step'] ?? null]);
|
||||
$choices = $this->entryChoices($r, $context);
|
||||
return Inertia::render('investor-path/context-start', ['entrySubmission' => $entrySubmission, 'entryComplements' => $this->entryComplements($r), 'entryQuery' => $r->only(['complement_origin', 'complement_code', 'complement_target', 'complement_territory', 'from_dossier', 'province_id', 'district_id', 'admin_post_id', 'locality_id']), 'opportunityChoices' => $choices, 'contexts' => $path->contexts($r->user()), 'source' => $ref, 'step' => $d['step'] ?? null]);
|
||||
}
|
||||
|
||||
public function installation(Request $r, InvestorContextInstallation $install)
|
||||
|
||||
@@ -88,7 +88,8 @@ class InvestorPathController extends Controller
|
||||
|
||||
public function show(Request $request, string $id, InvestorPath $path): JsonResponse|Response
|
||||
{
|
||||
$data = $path->view($request->user(), $id);
|
||||
$choice = $request->validate(['opportunity' => 'nullable|string|max:100'])['opportunity'] ?? null;
|
||||
$data = $path->view($request->user(), $id, $choice);
|
||||
|
||||
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/show', $data);
|
||||
}
|
||||
|
||||
@@ -103,6 +103,7 @@ class OpportunityManagementController extends Controller
|
||||
$records = $query->orderByDesc('id')->paginate(20)->withQueryString();
|
||||
$records->getCollection()->each(function (Opportunity $r) use ($access, $service, $request) {
|
||||
$r->setAttribute('can_edit', $access->canEdit($request->user(), $r));
|
||||
$r->setAttribute('can_promote', app(\App\Services\OpportunityPromotion::class)->allowed($request->user(), $r));
|
||||
$r->setAttribute('working_status', $access->state($r));
|
||||
$r->setAttribute('publication', $r->publicationPresentation());
|
||||
$r->setAttribute('draft_title', $service->values($r)['canonical']['official_title'] ?? $r->title);
|
||||
@@ -130,6 +131,7 @@ class OpportunityManagementController extends Controller
|
||||
'profileReauthenticationRequired' => $record && $record->owner_user_id !== null
|
||||
? app(OpportunityProfileWorkflow::class)->reauthenticationRequired($request->user(), $record) : false,
|
||||
'publicationState' => $record?->publicationPresentation(),
|
||||
'promotionHref' => $record && app(\App\Services\OpportunityPromotion::class)->allowed($request->user(), $record) ? '/minhas-oportunidades/'.$record->id.'/divulgacao' : null,
|
||||
'canonicalResponse' => $record?->owner_user_id !== null ? app(OpportunityCanonicalResponse::class)->read($request->user(), $record) : null,
|
||||
'canEditDraft' => $record ? $access->canEdit($request->user(), $record) : false,
|
||||
'workflowParticipants' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->participants($request->user(), $record) : ['validators' => [], 'publishers' => []],
|
||||
@@ -145,7 +147,7 @@ class OpportunityManagementController extends Controller
|
||||
Inertia::share('publicationPreview', app(OpportunityCanonicalContract::class)->publicProjection($values['canonical'] ?? []));
|
||||
$classification = $id ? DB::table('audit_events')->where('source_system', 'opportunity-origin-review')->where('after_data->opportunity_id', $id)->orderByDesc('occurred_at')->orderByDesc('id')->value('after_data') : null;
|
||||
|
||||
return Inertia::render('management/opportunity-draft', ['resourcesInstalled' => app(OpportunityResources::class)->installed(), 'record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view') || ($record && ! $access->canEdit($request->user(), $record)), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'categories' => OpportunityManagement::CATEGORIES,
|
||||
return Inertia::render('management/opportunity-draft', ['proactiveHistory' => app(\App\Services\ProactiveInvestment::class)->history($record), 'proactiveOptions' => app(\App\Services\ProactiveInvestment::class)->options($record), 'resourcesInstalled' => app(OpportunityResources::class)->installed(), 'record' => $record, 'values' => $values, 'etag' => $record ? $service->etag($record) : null, 'readOnly' => str_ends_with($request->path(), '/view') || ($record && ! $access->canEdit($request->user(), $record)), 'closedVersion' => $record ? $service->closed($record) : false, 'classification' => $classification ? json_decode($classification, true)['classification'] : 'undetermined', 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'categories' => OpportunityManagement::CATEGORIES,
|
||||
'maturityCatalogue' => ['version' => OpportunityMaturity::VERSION, 'stages' => OpportunityMaturity::STAGES, 'legacyVersion' => OpportunityMaturity::LEGACY, 'legacyLabels' => OpportunityMaturity::LEGACY_LABELS],
|
||||
'territoryPath' => app(InvestmentGeography::class)->path($values['primary_territory_id'] ?? null, true),
|
||||
'history' => $id ? DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at']) : []]);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\OpportunityPromotion;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
|
||||
final class OpportunityPromotionController extends Controller
|
||||
{
|
||||
public function show(Request $request, int $id, OpportunityPromotion $service): \Inertia\Response
|
||||
{
|
||||
return Inertia::render('management/opportunity-promotion', $service->editor($request->user(), Opportunity::findOrFail($id)));
|
||||
}
|
||||
|
||||
public function preview(Request $request, int $id, OpportunityPromotion $service): \Illuminate\Http\JsonResponse
|
||||
{
|
||||
return response()->json($service->preview($request->user(), Opportunity::findOrFail($id), $request->all()));
|
||||
}
|
||||
|
||||
public function confirm(Request $request, int $id, OpportunityPromotion $service): \Illuminate\Http\JsonResponse
|
||||
{
|
||||
return response()->json($service->confirm($request->user(), $id, $request->all()));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use App\Services\CountryCatalogue;
|
||||
use App\Services\IdempotencyConflict;
|
||||
use App\Services\InterestSubmission;
|
||||
use App\Services\LegacyContent;
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use App\Services\VerifiedDocumentBinary;
|
||||
use App\Services\VirtualDesk;
|
||||
@@ -274,7 +275,7 @@ class PortalServicesController extends Controller
|
||||
'resource' => $resource,
|
||||
'backUrl' => $backUrl,
|
||||
'downloadUrl' => route('services.download', ['id' => $id]),
|
||||
'articleUrl' => Schema::hasColumn('portal_resources','editorial_content') && DB::table('portal_resources')->where('id',$id)->whereNotNull('editorial_content')->exists() ? '/artigos/'.$id : null,
|
||||
'articleUrl' => $this->articleUrl($id),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -297,6 +298,7 @@ class PortalServicesController extends Controller
|
||||
|
||||
public function manage(Request $request, MalwareScanner $scanner): Response
|
||||
{
|
||||
$managementFilters = $request->validate(['q' => 'nullable|string|max:150', 'state' => 'nullable|in:draft,published,withdrawn', 'intent' => 'nullable|in:document,legislation']);
|
||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
||||
if (! $access->full($request->user())) {
|
||||
$documents = $access->documents($request->user())->where('status', '!=', 'deleted');
|
||||
@@ -304,7 +306,7 @@ class PortalServicesController extends Controller
|
||||
$health['signatures_at'] = $health['signatures_at']?->format(DATE_ATOM);
|
||||
|
||||
$editorial = $access->editorial($request->user());
|
||||
$resources = $editorial ? $access->editorialResources($request->user())->orderByDesc('r.updated_at')
|
||||
$resources = $editorial ? $this->filterManagedResources($access->editorialResources($request->user()), $managementFilters)->orderByDesc('r.updated_at')
|
||||
->get(['r.*', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.status as file_status', 'd.data_classification', 'd.version_no as file_version', 'd.rights_status as file_rights_status', 'd.malware_scan_status', 'd.malware_failure_reason']) : collect();
|
||||
$links = DB::table('portal_resource_links')->whereIn('resource_id', $resources->pluck('id'))->orderBy('id')->get()->groupBy('resource_id');
|
||||
$revisions = DB::table('portal_resource_revisions')->whereIn('resource_id', $resources->pluck('id'))->orderByDesc('revision_no')->get(['resource_id', 'revision_no', 'change_type', 'actor_user_id', 'created_at'])->groupBy('resource_id');
|
||||
@@ -313,6 +315,7 @@ class PortalServicesController extends Controller
|
||||
$resource->revisions = $revisions->get($resource->id, collect())->values();
|
||||
});
|
||||
return Inertia::render('portal/manage', [
|
||||
'managementFilters' => $managementFilters, 'associationOptions' => $this->contentAssociations($request),
|
||||
'documentAccessOnly' => ! $editorial, 'editorialScopeOnly' => $editorial, 'resources' => $resources, 'partnerships' => [], 'territories' => [],
|
||||
'requirementCatalogue' => [], 'requirementAssociationsEnabled' => false,
|
||||
'disclosureAuthorization' => null, 'incompleteCount' => $resources->filter(fn ($r) => ! $r->description || ! $r->issuer || ! $r->source_url || $r->source_confirmation === 'unconfirmed' || $r->legal_status === 'unknown' || $r->rights_status === 'unconfirmed')->count(), 'possibleDuplicates' => $resources->whereNotNull('duplicate_of_resource_id')->count(),
|
||||
@@ -331,7 +334,7 @@ class PortalServicesController extends Controller
|
||||
->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1')
|
||||
->where('action', 'public_disclosure_authorized')->first(['external_id', 'occurred_at', 'after_data']);
|
||||
$disclosureAuthorizationData = $disclosureAuthorization ? json_decode($disclosureAuthorization->after_data, true) : null;
|
||||
$resources = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->orderByDesc('r.updated_at')->limit(200)
|
||||
$resources = $this->filterManagedResources(DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->whereNull('d.deleted_at'), $managementFilters)->orderByDesc('r.updated_at')->limit(200)
|
||||
->get(['r.*', 'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.status as file_status', 'd.data_classification', 'd.version_no as file_version', 'd.rights_status as file_rights_status', 'd.malware_scan_status', 'd.malware_failure_reason']);
|
||||
$links = DB::table('portal_resource_links')->whereIn('resource_id', $resources->pluck('id'))->orderBy('id')->get()->groupBy('resource_id');
|
||||
$resources->each(fn ($resource) => $resource->links = $links->get($resource->id, collect())->values());
|
||||
@@ -342,6 +345,7 @@ class PortalServicesController extends Controller
|
||||
$malwareHealth['signatures_at'] = $malwareHealth['signatures_at']?->format(DATE_ATOM);
|
||||
|
||||
return Inertia::render('portal/manage', ['resources' => $resources,
|
||||
'managementFilters' => $managementFilters, 'associationOptions' => $this->contentAssociations($request),
|
||||
'requirementCatalogue' => $this->requirementEvidenceEnabled()
|
||||
? collect(is_array($catalogue = config('document-requirements.catalogue', [])) ? $catalogue : [])->map(fn ($item, $key) => ['key' => $key, ...$item])->values()
|
||||
: collect(),
|
||||
@@ -367,6 +371,39 @@ class PortalServicesController extends Controller
|
||||
'possibleDuplicates' => DB::table('portal_resources')->whereNotNull('duplicate_of_resource_id')->count()]);
|
||||
}
|
||||
|
||||
private function filterManagedResources(Builder $query, array $filters): Builder
|
||||
{
|
||||
if (! empty($filters['q'])) {
|
||||
$term = '%'.addcslashes($filters['q'], '%_\\').'%';
|
||||
$query->where(fn ($q) => $q->where('r.title', 'ilike', $term)->orWhere('r.document_number', 'ilike', $term)->orWhere('d.issuer', 'ilike', $term)->orWhere('d.file_name', 'ilike', $term));
|
||||
}
|
||||
if (! empty($filters['state'])) {
|
||||
$query->where('r.published', $filters['state'] === 'published');
|
||||
if ($filters['state'] !== 'published') {
|
||||
$method = $filters['state'] === 'withdrawn' ? 'whereExists' : 'whereNotExists';
|
||||
$query->$method(fn ($q) => $q->selectRaw('1')->from('portal_resource_revisions as history')->whereColumn('history.resource_id', 'r.id')->whereIn('history.change_type', ['unpublished', 'withdrawn']));
|
||||
}
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function contentAssociations(Request $request): array
|
||||
{
|
||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
||||
$resources = $access->full($request->user()) ? DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->whereNull('d.deleted_at')
|
||||
: ($access->editorial($request->user()) ? $access->editorialResources($request->user()) : null);
|
||||
$documents = $resources ? $resources->orderBy('r.title')->get(['r.id as value', 'r.title as label', 'r.document_type']) : collect();
|
||||
return [
|
||||
'sector' => \App\Models\Sector::choices()->orderBy('name')->get(['id as value', 'name as label']),
|
||||
'territory' => app(\App\Services\InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id as value', 'name as label']),
|
||||
'opportunity' => app(PortalProfileAccess::class)->scope(\App\Models\Opportunity::query(), $request->user())->orderBy('title')->get(['id as value', 'title as label']),
|
||||
'document' => $documents,
|
||||
'procedure' => $documents->where('document_type', 'procedure')->values(),
|
||||
'stage' => collect(config('virtual-desk.steps', []))->map(fn ($step, $key) => ['value' => $key, 'label' => $step['title']])->values(),
|
||||
'activity' => app(\App\Services\EconomicReferenceCatalog::class)->activities()->map(fn ($row) => ['value' => $row->id, 'label' => $row->display_label])->values(),
|
||||
];
|
||||
}
|
||||
|
||||
public function upload(Request $request): RedirectResponse
|
||||
{
|
||||
$this->validateManagement($request, ['file' => ['required', 'file', 'mimetypes:application/pdf,text/plain,text/csv,image/jpeg,image/png,image/webp,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.oasis.opendocument.text'.(app(LegacyContent::class)->available() ? ',application/json' : ''), 'max:10240'],
|
||||
@@ -399,7 +436,7 @@ class PortalServicesController extends Controller
|
||||
|
||||
ScanDocumentForMalware::dispatch($id)->afterCommit();
|
||||
|
||||
return to_route('services.manage')->with('success', 'Documento recebido em armazenamento privado e quarentena. Não aparece na biblioteca pública até validação e publicação explícitas.');
|
||||
return to_route('services.manage', array_filter(['intent' => in_array($request->input('intent'), ['document', 'legislation'], true) ? $request->input('intent') : null]))->with('uploaded_document_id', $id)->with('success', 'Documento recebido em armazenamento privado e quarentena. Não aparece na biblioteca pública até validação e publicação explícitas.');
|
||||
}
|
||||
|
||||
public function resource(Request $request): RedirectResponse
|
||||
@@ -663,7 +700,7 @@ class PortalServicesController extends Controller
|
||||
'data_classification' => ['nullable', 'in:internal,public'],
|
||||
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'legislation' => ['required', 'boolean'], 'essential' => ['required', 'boolean'],
|
||||
'associations' => ['nullable', 'array', 'max:40'], 'associations.*.target_type' => ['required', 'in:theme,module,activity,stage,procedure,entity,territory,document,investment_type,legal_source'.($this->requirementEvidenceEnabled() ? ',requirement' : '')],
|
||||
'associations' => ['nullable', 'array', 'max:40'], 'associations.*.target_type' => ['required', 'in:theme,module,activity,stage,procedure,entity,territory,document,investment_type,legal_source,sector,opportunity'.($this->requirementEvidenceEnabled() ? ',requirement' : '')],
|
||||
'associations.*.target_key' => ['required', 'string', 'max:180'],
|
||||
'associations.*.review_status' => ['nullable', 'in:pending,confirmed'],
|
||||
'associations.*.relationship' => ['required', 'in:applies_to,supports,version_of,translation_of,amends,repeals,implements,cites,related_to'],
|
||||
@@ -829,4 +866,17 @@ SQL, [$id]);
|
||||
|
||||
return $ids ?: [$id];
|
||||
}
|
||||
private function articleUrl(int $id): ?string
|
||||
{
|
||||
if (!Schema::hasColumn('portal_resources', 'editorial_content')) return null;
|
||||
$resource = DB::table('portal_resources')->find($id);
|
||||
if (!$resource) return null;
|
||||
if ($resource->editorial_content !== null) return '/artigos/'.$id;
|
||||
try {
|
||||
return app(\App\Services\EditorialReading::class)->original($resource) ? '/artigos/'.$resource->id : null;
|
||||
} catch (\Symfony\Component\HttpKernel\Exception\HttpException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Services\ProactiveSupply;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
final class ProactiveSupplyController extends Controller
|
||||
{
|
||||
public function index(Request $request,ProactiveSupply $service): JsonResponse
|
||||
{
|
||||
$v=$request->validate(['record_id'=>'nullable|integer|min:1']);
|
||||
$record=isset($v['record_id'])?Opportunity::findOrFail($v['record_id']):null;
|
||||
return response()->json($service->search($request->user(),$request->all(),$record))->header('Cache-Control','private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\Procurement;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Inertia;
|
||||
|
||||
class ProcurementController extends Controller
|
||||
{
|
||||
private const STATE_SQL = "CASE WHEN v.payload->>'procedural_state' IN ('cancelled','results') THEN v.payload->>'procedural_state' WHEN ((v.payload->>'deadline')::timestamp AT TIME ZONE (v.payload->>'timezone'))<=CURRENT_TIMESTAMP THEN 'deadline_ended' WHEN v.payload->>'extended'='true' THEN 'extended' ELSE 'open' END";
|
||||
|
||||
private function query(Procurement $service)
|
||||
{
|
||||
abort_unless($service->available(), 404);
|
||||
|
||||
return DB::table('portal_tenders as t')->join('portal_tender_versions as v', fn ($q) => $q->on('v.id', '=', 't.published_version_id')->on('v.tender_id', '=', 't.id'))->whereNotNull('v.published_at');
|
||||
}
|
||||
|
||||
public function index(Request $request, Procurement $service)
|
||||
{
|
||||
$filters = $request->validate(['q' => 'nullable|string|max:150', 'entity' => 'nullable|uuid', 'sector' => 'nullable|integer', 'territory' => 'nullable|uuid', 'modality' => 'nullable|string|max:200', 'financier' => 'nullable|string|max:200', 'state' => 'nullable|in:open,extended,deadline_ended,cancelled,results', 'deadline_before' => 'nullable|date_format:Y-m-d', 'regime' => 'nullable|in:state,external,private,other']);
|
||||
$filters = array_filter($filters, fn ($value) => $value !== null && $value !== '');
|
||||
$query = $this->query($service);
|
||||
if (! empty($filters['q'])) {
|
||||
$query->where(fn ($q) => $q->whereRaw("v.payload->>'title' ILIKE ?", ['%'.$filters['q'].'%'])->orWhereRaw("v.payload->>'object' ILIKE ?", ['%'.$filters['q'].'%'])->orWhereRaw("v.payload->>'reference' ILIKE ?", ['%'.$filters['q'].'%']));
|
||||
}
|
||||
foreach (['entity' => 'organization_id', 'sector' => 'sector_id', 'modality' => 'modality', 'financier' => 'financier', 'regime' => 'regime'] as $filter => $field) {
|
||||
if (! empty($filters[$filter])) {
|
||||
$query->whereRaw('v.payload->>? = ?', [$field, (string) $filters[$filter]]);
|
||||
}
|
||||
}
|
||||
if (! empty($filters['territory'])) {
|
||||
$query->whereRaw("v.payload->>'territory_id' IN (WITH RECURSIVE scope(id,depth) AS (SELECT id,0 FROM geo_locations WHERE id=? AND deleted_at IS NULL UNION ALL SELECT c.id,s.depth+1 FROM geo_locations c JOIN scope s ON c.parent_id=s.id WHERE c.deleted_at IS NULL AND s.depth<4) SELECT id::text FROM scope)", [$filters['territory']]);
|
||||
}
|
||||
if (! empty($filters['state'])) {
|
||||
$query->whereRaw(self::STATE_SQL.' = ?', [$filters['state']]);
|
||||
}
|
||||
if (! empty($filters['deadline_before'])) {
|
||||
$query->whereRaw("left(v.payload->>'deadline',10)<=?", [$filters['deadline_before']]);
|
||||
}
|
||||
$rows = $query->select('t.id', 'v.id as vid')->orderByDesc('v.published_at')->paginate(20)->withQueryString();
|
||||
$rows->through(fn ($r) => ['id' => $r->id, ...$this->summary($service, $r->vid)]);
|
||||
$facets = $this->query($service)->get(['v.payload'])->map(fn ($r) => json_decode($r->payload, true));
|
||||
$options = [];
|
||||
foreach (['entity' => ['organization_id', 'organization_name'], 'sector' => ['sector_id', 'sector_name'], 'territory' => ['territory_id', 'territory_name'], 'modality' => ['modality', 'modality'], 'financier' => ['financier', 'financier']] as $name => [$value,$label]) {
|
||||
$options[$name] = $facets->filter(fn ($p) => ! empty($p[$value]))->map(fn ($p) => ['id' => (string) $p[$value], 'name' => $p[$label]])->unique('id')->values();
|
||||
}
|
||||
|
||||
return Inertia::render('procurement/index', ['items' => $rows, 'filters' => $filters, 'options' => $options, 'regimes' => config('procurement.regimes'), 'management' => $service->access($request->user())])->toResponse($request)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
private function summary(Procurement $service, string $vid): array
|
||||
{
|
||||
$v = $service->publishedVersion($vid);
|
||||
|
||||
return ['publication' => $v, 'state' => $service->state($v)];
|
||||
}
|
||||
|
||||
public function show(Request $request, string $id, Procurement $service)
|
||||
{
|
||||
return $this->detail($request, $id, $service, false);
|
||||
}
|
||||
|
||||
public function print(Request $request, string $id, Procurement $service)
|
||||
{
|
||||
return $this->detail($request, $id, $service, true);
|
||||
}
|
||||
|
||||
private function detail(Request $request, string $id, Procurement $service, bool $print)
|
||||
{
|
||||
$row = $this->query($service)->where('t.id', $id)->firstOrFail(['t.id', 'v.id as vid']);
|
||||
$filters = $request->only(['q', 'entity', 'sector', 'territory', 'modality', 'financier', 'state', 'deadline_before', 'regime', 'page']);
|
||||
|
||||
return Inertia::render('procurement/show', ['id' => $id, ...$this->summary($service, $row->vid), 'printMode' => $print, 'backUrl' => '/concursos'.($filters ? '?'.http_build_query($filters) : ''),
|
||||
'history' => DB::table('portal_tender_versions')->where('tender_id', $id)->whereNotNull('published_at')->orderBy('version')->pluck('id')->map(fn ($vid) => $service->publishedVersion($vid)),
|
||||
'watching' => $request->user() && DB::table('portal_tender_watches')->where('tender_id', $id)->where('user_id', $request->user()->id)->exists()])->toResponse($request)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function manage(Request $request, Procurement $service)
|
||||
{
|
||||
$service->guard($request->user());
|
||||
|
||||
return Inertia::render('procurement/manage', ['items' => DB::table('portal_tenders')->orderByDesc('updated_at')->get(['id', 'draft', 'version', 'published_version_id'])->map(fn ($r) => ['id' => $r->id, 'title' => json_decode($r->draft, true)['title'] ?? 'Rascunho sem título', 'version' => $r->version, 'published' => (bool) $r->published_version_id])])->toResponse($request)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function edit(Request $request, Procurement $service, ?string $id = null)
|
||||
{
|
||||
$service->guard($request->user());
|
||||
$r = $id ? $service->record($id) : null;
|
||||
|
||||
return Inertia::render('procurement/edit', ['record' => $r ? ['id' => $id, 'version' => $r->version, 'draft' => json_decode($r->draft, true), 'published' => (bool) $r->published_version_id] : null,
|
||||
'references' => $service->references($request->user()), 'history' => $id ? DB::table('portal_tender_versions')->where('tender_id', $id)->orderByDesc('version')->get(['version', 'act', 'reason', 'actor_id', 'published_at', 'created_at']) : []])->toResponse($request)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function save(Request $request, Procurement $service, ?string $id = null)
|
||||
{
|
||||
$id = $service->save($request->user(), $id, $request->all());
|
||||
|
||||
return redirect('/management/concursos/'.$id)->with('success', 'Rascunho guardado. A publicação anterior permanece intacta.');
|
||||
}
|
||||
|
||||
public function preview(Request $request, string $id, Procurement $service)
|
||||
{
|
||||
return response()->json($service->preview($request->user(), $id, (string) $request->input('act')))->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function publish(Request $request, string $id, Procurement $service)
|
||||
{
|
||||
$service->publish($request->user(), $id, $request->all());
|
||||
|
||||
return redirect('/management/concursos/'.$id)->with('success', 'Acto publicado, com versão e auditoria. Nenhuma proposta recebida pelo portal.');
|
||||
}
|
||||
|
||||
public function watch(Request $request, string $id, Procurement $service)
|
||||
{
|
||||
$row = $this->query($service)->where('t.id', $id)->firstOrFail(['v.id']);
|
||||
DB::table('portal_tender_watches')->updateOrInsert(['tender_id' => $id, 'user_id' => $request->user()->id], ['seen_version_id' => $row->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
|
||||
return back()->with('success', 'Concurso guardado para acompanhamento. Isto não apresenta uma proposta.');
|
||||
}
|
||||
|
||||
public function unwatch(Request $request, string $id, Procurement $service)
|
||||
{
|
||||
abort_unless($service->available(), 404);
|
||||
DB::table('portal_tender_watches')->where('tender_id', $id)->where('user_id', $request->user()->id)->delete();
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function watched(Request $request, Procurement $service)
|
||||
{
|
||||
$rows = $this->query($service)->join('portal_tender_watches as w', 'w.tender_id', '=', 't.id')->where('w.user_id', $request->user()->id)->get(['t.id', 'v.id as vid', 'w.seen_version_id'])->map(fn ($r) => ['id' => $r->id, 'changed' => $r->seen_version_id !== $r->vid, ...$this->summary($service, $r->vid)]);
|
||||
|
||||
return Inertia::render('procurement/manage', ['watched' => true, 'items' => $rows])->toResponse($request)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,13 @@ class PublicGeographyController extends Controller
|
||||
{
|
||||
public function options(Request $request, InvestmentGeography $geography): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['type' => ['required', 'in:province,district,admin_post,locality'], 'id' => ['nullable', 'uuid'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$data = $request->validate(['corridor' => ['nullable', \Illuminate\Validation\Rule::in(array_keys(config('investment_corridors')))], 'type' => ['required', 'in:province,district,admin_post,locality'], 'id' => ['nullable', 'uuid'], 'parent_id' => ['nullable', 'uuid'], 'q' => ['nullable', 'string', 'max:100'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||
$query = $geography->publicReferences()->where('location_type', $data['type']);
|
||||
if (!empty($data['corridor'])) {
|
||||
$corridors = app(\App\Services\InvestmentCorridorContext::class);
|
||||
if ($data['type'] === 'province') $query->whereIn('id', array_column($corridors->provinces($data['corridor']), 'id'));
|
||||
elseif (!$corridors->compatible($data['corridor'], $data['parent_id'] ?? null)) abort(422, 'O território não pertence ao corredor escolhido.');
|
||||
}
|
||||
if (! empty($data['id'])) {
|
||||
$query->where('id', $data['id']);
|
||||
}
|
||||
@@ -29,6 +34,6 @@ class PublicGeographyController extends Controller
|
||||
->orWhereRaw('source_code ILIKE ?', [$term]));
|
||||
}
|
||||
|
||||
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code']));
|
||||
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code'])->withQueryString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,9 +25,7 @@ class PublicPortalController extends Controller
|
||||
if ($slug === 'mercado-financeiro/fintech') $slug = 'fintech';
|
||||
$sector = Sector::where('slug', $slug)->where('is_active', true)->whereNotNull('published_at')->firstOrFail();
|
||||
|
||||
return Inertia::render('portal/services', ['section' => 'sector', 'sector' => $sector->only(['id', 'name', 'slug', 'description', 'short_description']),
|
||||
'sectorEntry' => array_key_exists($sector->slug, SectorInvestment::CONTENT) ? app(SectorInvestment::class)->publicView($sector) : null,
|
||||
'opportunities' => \App\Services\SectorOrganization::opportunities($sector)->latest('published_at')->limit(12)->get(['id', 'title', 'slug', 'province', 'summary'])]);
|
||||
return Inertia::render('portal/services', ['section' => 'sector', ...app(SectorInvestment::class)->page($sector)]);
|
||||
}
|
||||
|
||||
public function opportunity(string $slug): Response
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Services\SimulationTaxGovernanceAccess;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Explicit fiscal curation of an identified official source; not an independent legal opinion. */
|
||||
final class SimulationFiscalSourceController extends Controller
|
||||
{
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
SimulationTaxGovernanceAccess::requireRole($request->user(), 'editors');
|
||||
$data = $request->validate([
|
||||
'title' => ['required', 'string', 'max:255'], 'url' => ['required', 'url:https', 'max:2000'],
|
||||
'diploma' => ['required', 'string', 'max:255'], 'article' => ['required', 'string', 'max:255'],
|
||||
'competent_entity' => ['required', 'string', 'max:255'], 'valid_from' => ['required', 'date_format:Y-m-d'],
|
||||
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from'],
|
||||
'sha256' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
|
||||
'citation' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
'official_origin' => ['required', 'string', 'min:10', 'max:2000'],
|
||||
]);
|
||||
|
||||
return DB::transaction(function () use ($request, $data): JsonResponse {
|
||||
$actor = $request->user();
|
||||
$acceptance = ['scope' => 'fiscal_parameters', 'basis' => 'Tempo-official-sources-20261008',
|
||||
'responsible_user_id' => $actor->id, 'sha256' => $data['sha256'], 'citation' => $data['citation'],
|
||||
'official_origin' => $data['official_origin'], 'accepted_at' => now()->toISOString(),
|
||||
'legal_opinion' => false, 'independent_review' => false];
|
||||
unset($data['sha256'], $data['citation'], $data['official_origin']);
|
||||
$source = InvestmentLegalSource::create([...$data, 'owner_id' => $actor->id, 'validator_id' => null,
|
||||
'validation_status' => 'pending', 'validated_at' => null, 'version_no' => 1, 'fiscal_acceptance' => $acceptance]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'simulation-fiscal-maintenance',
|
||||
'entity_type' => 'investment_legal_sources', 'entity_id' => $source->id, 'actor_user_id' => $actor->id,
|
||||
'action' => 'official_source_acceptance', 'after_data' => json_encode([
|
||||
'source' => $source->attributesToArray(), 'basis' => $acceptance,
|
||||
'sha256' => hash('sha256', $source->toJson()),
|
||||
], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return response()->json($source->fresh(), 201);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,51 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\SimulationFiscalQaPreview;
|
||||
use App\Services\SimulationTaxParameterResolver;
|
||||
use App\Services\SimulationTaxRuleExpression;
|
||||
use App\Services\SimulationTaxRuleGovernance;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class SimulationTaxRuleGovernanceController extends Controller
|
||||
{
|
||||
public function qaReview(Request $request, string $id, SimulationTaxRuleGovernance $governance): Response
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
$rule = $governance->show($request->user(), $id);
|
||||
abort_unless($rule->status === 'draft' && $rule->rule_code === 'IVA-GERAL-BASE-LIQUIDA', 422,
|
||||
'Seleccione o rascunho do primeiro lote fiscal.');
|
||||
|
||||
return Inertia::render('management/fiscal-qa-review', ['rule' => [
|
||||
'id' => $rule->id, 'code' => $rule->rule_code, 'version' => $rule->rule_version,
|
||||
]]);
|
||||
}
|
||||
|
||||
public function qaPreview(Request $request, string $id, SimulationFiscalQaPreview $preview): JsonResponse
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
$key = $request->header('Idempotency-Key');
|
||||
abort_unless(is_string($key) && strlen($key) >= 16 && strlen($key) <= 128, 428, 'Idempotency-Key é obrigatório.');
|
||||
$input = $request->validate([
|
||||
'base' => ['required', 'string', 'max:40', 'regex:/^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/D'],
|
||||
'reference_date' => ['required', 'date_format:Y-m-d'],
|
||||
'currency' => ['required', 'in:MZN'],
|
||||
'operation' => ['required', 'in:internal_general_net'],
|
||||
]);
|
||||
$result = $preview->create($request->user(), $id, $input, $key);
|
||||
$simulation = $result['simulation'];
|
||||
|
||||
return response()->json(['data' => $simulation, 'replayed' => $result['replayed']], $result['replayed'] ? 200 : 202)
|
||||
->header('Location', url('/api/v1/simulations/'.$simulation->id));
|
||||
}
|
||||
|
||||
public function index(Request $request, SimulationTaxRuleGovernance $governance): JsonResponse
|
||||
{
|
||||
$filters = $request->validate([
|
||||
|
||||
@@ -119,8 +119,8 @@ class VirtualDeskController extends Controller
|
||||
|
||||
public function createRequest(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['service_version_id' => 'required|uuid', 'client_key' => 'required|uuid']);
|
||||
$row = $desk->createRequest($request->user(), $id, $data['service_version_id'], $data['client_key']);
|
||||
$data = $request->validate(['service_version_id' => 'required|uuid', 'client_key' => 'required|uuid', 'opportunity' => 'nullable|string|max:100']);
|
||||
$row = $desk->createRequest($request->user(), $id, $data['service_version_id'], $data['client_key'], $data['opportunity'] ?? null);
|
||||
|
||||
return $request->expectsJson() ? response()->json(['id' => $row->id, 'version' => $row->version], 201) : redirect('/balcao-virtual/pedidos/'.$row->id);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ class EnsureScopedEditorial
|
||||
return $next($request);
|
||||
}
|
||||
abort_unless($access->editorial($actor), 403);
|
||||
$allowed = in_array($request->route()->getName(), ['editorial.edit', 'editorial.save', 'services.resource', 'services.resource.update'], true)
|
||||
$allowed = in_array($request->route()->getName(), ['editorial.edit', 'editorial.save', 'editorial.preview', 'editorial.preview-content', 'services.resource', 'services.resource.update'], true)
|
||||
|| ($request->route()->getName() === 'services.moderate' && $request->route('type') === 'resources');
|
||||
abort_unless($allowed, 403);
|
||||
if ($request->route('id') !== null) {
|
||||
|
||||
@@ -1,31 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\PortalProfileAccess;
|
||||
use App\Services\ScopedPortalAdministration;
|
||||
use App\Services\SimulationTaxGovernanceAccess;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use App\Services\ScopedPortalAdministration;
|
||||
|
||||
final class EnsureScopedPortalAdministration
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$actor=$request->user();abort_unless($actor,403);
|
||||
$scope=app(ScopedPortalAdministration::class);
|
||||
$path=$request->path();
|
||||
$interests=$request->is('management/interests','management/interests/*','api/v1/investment/admin/interests/*');
|
||||
// Exact areas of P1; unrelated management, fiscal rules and private records keep their gate.
|
||||
$catalogue=$request->is('management/economic-references/lot-01','management/economic-references/lot-01/*',
|
||||
'management/education','management/education/*','management/investment/references','management/investment/references/*','api/v1/investment/admin/references','api/v1/investment/admin/references/*',
|
||||
'management/investment/zones','management/investment/zones/*','api/v2/investment/admin/zones','api/v2/investment/admin/zones/*',
|
||||
'management/balcao/atribuicoes','management/balcao/atribuicoes/*','management/balcao/servicos',
|
||||
'management/balcao/fontes') || ($request->isMethod('GET') && $path==='management/balcao-install');
|
||||
$allowed=$interests ? $scope->interestOperator($actor) : ($catalogue && $scope->administrative($actor));
|
||||
abort_unless($allowed || ($actor->can('manage-portal') && !app(\App\Services\PortalProfileAccess::class)->has($actor,'auditor')),403,'Acesso reservado ao âmbito já designado.');
|
||||
$response=$next($request);
|
||||
if (!$request->isMethod('GET') && $response->getStatusCode()<400) {
|
||||
app(\App\Services\PortalProfileAccess::class)->audit($actor,'scoped_administration',[
|
||||
'method'=>$request->method(),'route'=>$request->route()?->uri(),'scope'=>$interests?'assigned-interest':'catalogue-administration']);
|
||||
$actor = $request->user();
|
||||
abort_unless($actor !== null, 403);
|
||||
$scope = app(ScopedPortalAdministration::class);
|
||||
$path = $request->path();
|
||||
$interests = $request->is('management/interests', 'management/interests/*', 'api/v1/investment/admin/interests/*');
|
||||
// Fiscal maintenance reuses authorised administration; unrelated gates remain unchanged.
|
||||
$geometryRead = $request->isMethod('GET') && $path === 'management/territory-geometries';
|
||||
$catalogue = $geometryRead || $request->is('management/territory-geometry-import', 'management/territory-geometry-import/*',
|
||||
'management/economic-references/lot-01', 'management/economic-references/lot-01/*',
|
||||
'management/education', 'management/education/*', 'management/investment/references', 'management/investment/references/*', 'api/v1/investment/admin/references', 'api/v1/investment/admin/references/*',
|
||||
'management/investment/zones', 'management/investment/zones/*', 'api/v2/investment/admin/zones', 'api/v2/investment/admin/zones/*',
|
||||
'management/balcao/atribuicoes', 'management/balcao/atribuicoes/*', 'management/balcao/servicos',
|
||||
'management/balcao/fontes') || ($request->isMethod('GET') && $path === 'management/balcao-install');
|
||||
$fiscal = $request->is('api/v2/investment/admin/tax-rules', 'api/v2/investment/admin/tax-rules/*',
|
||||
'api/v2/investment/admin/tax-rule-sources', 'management/investment/tax-rules/*');
|
||||
$allowed = ($fiscal && SimulationTaxGovernanceAccess::maintainer($actor)) || ($interests ? $scope->interestOperator($actor) : ($catalogue && $scope->administrative($actor)));
|
||||
abort_unless($allowed || ($actor->can('manage-portal') && ! app(PortalProfileAccess::class)->has($actor, 'auditor')), 403, 'Acesso reservado ao âmbito já designado.');
|
||||
$response = $next($request);
|
||||
if (! $request->isMethod('GET') && $response->getStatusCode() < 400) {
|
||||
app(PortalProfileAccess::class)->audit($actor, 'scoped_administration', [
|
||||
'method' => $request->method(), 'route' => $request->route()?->uri(), 'scope' => $fiscal ? 'fiscal-maintenance' : ($interests ? 'assigned-interest' : 'catalogue-administration')]);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ final class EnsureSimulationRecoveryCookie
|
||||
}
|
||||
}
|
||||
|
||||
return $response->withCookie(cookie(
|
||||
$response->headers->setCookie(cookie(
|
||||
self::NAME,
|
||||
$forget ? '' : $token,
|
||||
$minutes,
|
||||
@@ -64,6 +64,7 @@ final class EnsureSimulationRecoveryCookie
|
||||
false,
|
||||
'lax',
|
||||
));
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function isExplicitDraftActivity(Request $request, Response $response): bool
|
||||
|
||||
@@ -48,11 +48,15 @@ class HandleInertiaRequests extends Middleware
|
||||
*/
|
||||
public function share(Request $request): array
|
||||
{
|
||||
$contentManagementAccess=app(\App\Services\ContentManagement::class)->access($request->user());
|
||||
return [
|
||||
...parent::share($request),
|
||||
'name' => config('app.name'),
|
||||
'procurementEnabled' => app(\App\Services\Procurement::class)->available(),
|
||||
'homologationReserved' => (bool) config('portal.homologation_only', false),
|
||||
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
|
||||
'contentManagementHref' => $contentManagementAccess !== [] ? '/gestao-conteudos' : null,
|
||||
'contentManagementAccess'=>$contentManagementAccess,
|
||||
'portalOperator' => config('portal.operator_name'),
|
||||
'portalInstitutionalContactEmail' => filter_var(config('portal.institutional_contact_email'), FILTER_VALIDATE_EMAIL) ?: null,
|
||||
'legacyContentEnabled' => app(LegacyContent::class)->available(),
|
||||
@@ -68,7 +72,7 @@ class HandleInertiaRequests extends Middleware
|
||||
'create' => ['label' => 'Nova oportunidade', 'href' => '/management/opportunities/create'],
|
||||
'installationHref' => '/management/opportunity-management-install',
|
||||
] : null,
|
||||
'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning')],
|
||||
'flash' => ['success' => fn () => $request->session()->get('success'), 'warning' => fn () => $request->session()->get('warning'), 'uploaded_document_id' => fn () => $request->session()->get('uploaded_document_id')],
|
||||
'scopedAdministration' => $request->user() && app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()) ? [
|
||||
['label'=>'Zonas e parques','href'=>'/management/investment/zones'],
|
||||
['label'=>'Referências económicas','href'=>'/management/economic-references/lot-01'],
|
||||
@@ -81,6 +85,7 @@ class HandleInertiaRequests extends Middleware
|
||||
'auth' => [
|
||||
'user' => $request->user(),
|
||||
'canManagePortal' => $request->user()?->can('manage-portal') ?? false,
|
||||
'legacyManagementAccess' => $request->user()?->hasVerifiedEmail() && app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()),
|
||||
],
|
||||
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||
];
|
||||
|
||||
@@ -29,7 +29,9 @@ class ProtectProfileOpportunity
|
||||
if ($record && ($record->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades'))) {
|
||||
abort_if($record->owner_user_id === null && str_starts_with($request->path(), 'minhas-oportunidades'), 403, 'Registo legado não convertido para a política v1.');
|
||||
$access = app(PortalProfileAccess::class);
|
||||
$access->authorize($request->user(), $request->isMethod('GET') || str_ends_with($request->path(), '/workflow') || str_ends_with($request->path(), '/preview') || $request->is('minhas-oportunidades/*/classification/review') ? 'view' : 'edit', $record);
|
||||
// The promotional controller checks its own scoped disclosure capability,
|
||||
// like workflow decisions; publication does not grant draft editing.
|
||||
$access->authorize($request->user(), $request->isMethod('GET') || str_ends_with($request->path(), '/workflow') || str_ends_with($request->path(), '/preview') || $request->is('minhas-oportunidades/*/classification/review', 'minhas-oportunidades/*/divulgacao/previa', 'minhas-oportunidades/*/divulgacao/confirmar') ? 'view' : 'edit', $record);
|
||||
abort_if($request->is('management/opportunity-origin/apply'), 403, 'O cadastro privado v1 não usa a classificação editorial dos exemplos legados.');
|
||||
abort_if($request->isMethod('POST') && str_ends_with($request->path(), '/lifecycle') && ! str_contains($request->path(), '/resources/'), 403, 'Use o workflow com decisões segregadas; o perfil não concede exclusão.');
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ class ResolveSimulationTaxParametersRequest extends FormRequest
|
||||
'component' => ['required', 'in:IRPC,IVA,ISPC,IRPS,INSS,RETENCOES,DIREITOS_ADUANEIROS,ICE'],
|
||||
'period_start' => ['required', 'date_format:Y-m-d'],
|
||||
'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
|
||||
'context' => ['sometimes', 'array:fiscal_periodicity,fiscal_operation,fiscal_residency_assessment,fiscal_residency_country,fiscal_income_category,fiscal_establishments,fiscal_documentation,fiscal_customs_code,fiscal_vat_refund_state'],
|
||||
'context' => ['sometimes', 'array:currency,fiscal_periodicity,fiscal_operation,fiscal_residency_assessment,fiscal_residency_country,fiscal_income_category,fiscal_establishments,fiscal_documentation,fiscal_customs_code,fiscal_vat_refund_state'],
|
||||
'context.*' => ['string', 'max:160'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -19,7 +19,9 @@ class StoreLandAssistanceCaseRequest extends FormRequest
|
||||
{
|
||||
$payload = $this->validated('payload');
|
||||
|
||||
return is_array($payload) ? $payload : [];
|
||||
if (!is_array($payload)) return [];
|
||||
if (!empty($payload['investor_path_case_id'])) return app(\App\Services\InvestmentConsumerScope::class)->bind($this->user(), $payload['investor_path_case_id'], $payload, $this->routeIs('land-assistance.support'));
|
||||
return \Illuminate\Support\Arr::except($payload, ['context_opportunity', 'context_opportunity_snapshot']);
|
||||
}
|
||||
|
||||
public function authorize(): bool
|
||||
@@ -33,7 +35,10 @@ class StoreLandAssistanceCaseRequest extends FormRequest
|
||||
return [
|
||||
'version' => [$this->isMethod('post') && ! $this->routeIs('land-assistance.support') ? 'nullable' : 'required', 'integer', 'min:1'],
|
||||
'context_revision' => ['nullable', 'integer', 'min:0'], 'context_reviewed' => ['nullable', 'boolean'],
|
||||
'payload' => ['required', 'array:support_kind,request_description,project_reference,investor_path_case_id,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,declared_origin_country_code,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'],
|
||||
'payload' => ['required', 'array:context_opportunity,context_opportunity_snapshot,context_reuse,support_kind,request_description,project_reference,investor_path_case_id,applicant_category,full_name,contact_person,email,phone,preferred_contact,country,declared_origin_country_code,nationality,representative_name,representative_role,representation_basis,nuit,constitution_or_residency_note,area_status,parcels,purpose,activity,known_occupants,occupant_description,known_improvements,improvements_description,prior_right_status,prior_right_description,conflict_status,conflict_description,official_process,attachments_to_follow,exploration_plan,consultation,additional_information,truth_declaration,contact_consent'],
|
||||
'payload.context_opportunity' => ['nullable', 'string', 'max:100'],
|
||||
'payload.context_opportunity_snapshot' => ['nullable', 'string', 'max:200000'],
|
||||
'payload.context_reuse' => ['nullable', 'string', 'max:10000'],
|
||||
'payload.support_kind' => ['nullable', 'in:investment,home,family_exploitation,recognition,regularization,delimitation,change_of_use,transfer,existing_process,conflict_guidance,other'],
|
||||
'payload.request_description' => ['nullable', 'string', 'max:4000'],
|
||||
'payload.project_reference' => ['nullable', 'string', 'max:160'],
|
||||
|
||||
@@ -37,7 +37,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
||||
'contact_province', 'contact_district', 'preferred_channel',
|
||||
];
|
||||
$economic = [
|
||||
'journey_type', 'detail_level', 'business_plan_snapshot', 'financial_tools_snapshot', 'project_team_snapshot', 'project_execution_snapshot', 'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'selection_labels', 'project_type',
|
||||
'context_opportunity', 'context_applicability_snapshot', 'investment_regime', 'context_reuse', 'compatible_fields_snapshot', 'published_iva_base', 'published_iva_currency', 'published_iva_date', 'published_iva_scope', 'monthly_iva_settings', 'monthly_iva_snapshot', 'modelo_a_snapshot', 'journey_type', 'detail_level', 'business_plan_snapshot', 'financial_tools_snapshot', 'cashflow_snapshot', 'project_team_snapshot', 'project_execution_snapshot', 'purpose', 'manifestation_type', 'preferred_language', 'project_title', 'project_summary', 'project_problem', 'target_customers', 'value_proposition', 'market_assumption', 'market_source', 'project_milestones', 'selection_labels', 'project_type',
|
||||
'competitor_assumption', 'sales_channel_assumption', 'marketing_approach', 'location_rationale', 'project_risk_responses_snapshot', 'project_questionnaire_version',
|
||||
'customer_validation_status', 'cost_estimate_status', 'location_assessment_status', 'funding_status', 'receivables_timing_status',
|
||||
'project_type_other', 'sector_id', 'activity_id', 'products_services', 'maturity_stage', 'expected_start_date',
|
||||
@@ -50,7 +50,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
||||
'environmental_category', 'community_benefits', 'tax_calculation', 'fiscal_scenario_mode', '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',
|
||||
'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment',
|
||||
'fiscal_currency', 'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment',
|
||||
'fiscal_operation', 'fiscal_activity', 'fiscal_establishments', 'fiscal_documentation',
|
||||
'fiscal_customs_code', 'fiscal_vat_refund_state',
|
||||
'offer_or_demand', 'opportunity_type', 'opportunity_type_other', 'opportunity_description',
|
||||
@@ -71,6 +71,21 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
||||
'economic_snapshot.detail_level' => ['nullable', 'in:simple,advanced'],
|
||||
'economic_snapshot.business_plan_snapshot' => ['nullable', 'string', 'max:60000'],
|
||||
'economic_snapshot.financial_tools_snapshot' => ['nullable', 'string', 'max:30000'],
|
||||
'economic_snapshot.cashflow_snapshot' => ['nullable', 'string', 'max:20000'],
|
||||
'economic_snapshot.context_applicability_snapshot' => ['nullable', 'string', 'max:1000000'],
|
||||
'economic_snapshot.context_opportunity' => ['nullable', 'string', 'max:100'],
|
||||
'economic_snapshot.investment_regime' => ['nullable', 'in:general,industrial_park,zee,zfi'],
|
||||
'economic_snapshot.context_reuse' => ['nullable', 'string', 'max:10000'],
|
||||
'economic_snapshot.compatible_fields_snapshot' => ['nullable', 'string', 'max:10000'],
|
||||
'economic_snapshot.published_iva_base' => ['nullable', 'string', 'max:40'],
|
||||
'economic_snapshot.published_iva_currency' => ['nullable', 'string', 'max:3'],
|
||||
'economic_snapshot.published_iva_date' => ['nullable', 'string', 'max:10'],
|
||||
'economic_snapshot.published_iva_scope' => ['nullable', 'string', 'in:yes,no'],
|
||||
'economic_snapshot.monthly_iva_settings' => ['nullable', 'string', 'max:2000'],
|
||||
'economic_snapshot.monthly_iva_snapshot' => ['nullable', 'string', 'max:60000'],
|
||||
// Preserve accepted books and explicit history through the L3 refund increment.
|
||||
// This is a bounded transport choice, not a business limit on fiscal records.
|
||||
'economic_snapshot.modelo_a_snapshot' => ['nullable', 'string', 'json', 'max:6000000'],
|
||||
'economic_snapshot.project_team_snapshot' => ['nullable', 'string', 'max:30000'],
|
||||
'economic_snapshot.project_execution_snapshot' => ['nullable', 'string', 'max:30000'],
|
||||
'economic_snapshot.project_risk_responses_snapshot' => ['nullable', 'string', 'max:30000'],
|
||||
@@ -278,7 +293,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
||||
'currency', 'funds_origin_countries', 'environmental_category', 'tax_calculation', 'fiscal_scenario_mode', 'offer_or_demand',
|
||||
'opportunity_type', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration',
|
||||
'reuse_simulation', 'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged',
|
||||
'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment', 'fiscal_operation',
|
||||
'fiscal_currency', 'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'fiscal_quarter', 'fiscal_reference_date', 'irps_salary_view', 'fiscal_component', 'fiscal_income_category', 'fiscal_residency_assessment', 'fiscal_operation',
|
||||
'fiscal_documentation', 'fiscal_vat_refund_state'],
|
||||
'personal_snapshot.selection_labels' => ['person_type', 'investor_origin', 'tax_residency_country', 'fiscal_residency_country', 'entity_stage', 'legal_form', 'preferred_channel'],
|
||||
];
|
||||
|
||||
@@ -11,10 +11,71 @@ class StoreSimulationRequest extends FormRequest
|
||||
return true;
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'required' => 'Preencha o campo :attribute. As entradas foram preservadas.',
|
||||
'string' => 'Indique :attribute em formato textual.',
|
||||
'regex' => 'Indique uma base decimal positiva ou zero, com ponto decimal e sem separadores de milhares.',
|
||||
'max' => 'O campo :attribute excede o tamanho permitido.',
|
||||
'in' => 'A opção indicada em :attribute não pertence a este cálculo.',
|
||||
'date_format' => 'Indique uma data de exigibilidade válida.',
|
||||
'boolean' => 'Indique se declara o enquadramento da operação.',
|
||||
'prohibited' => 'O campo :attribute não pode ser definido pelo cliente neste cálculo.',
|
||||
'array' => 'Indique uma lista válida em :attribute.',
|
||||
'monthly_sales.min' => 'Indique pelo menos um mês de vendas.',
|
||||
'monthly_sales.max' => 'Este lote aceita até 12 meses dentro de 2026.',
|
||||
'monthly_sales.*.date.regex' => 'Indique o primeiro dia de um mês de 2026.',
|
||||
'monthly_sales.*.date.distinct' => 'Cada mês deve aparecer apenas uma vez.',
|
||||
'monthly_sales.*.amount.present' => 'Indique o valor das vendas ou deixe-o explicitamente sem informação.',
|
||||
];
|
||||
}
|
||||
|
||||
public function attributes(): array
|
||||
{
|
||||
return ['base' => 'base tributável', 'currency' => 'moeda', 'reference_date' => 'data de exigibilidade',
|
||||
'operation' => 'operação', 'scope_declared' => 'declaração de enquadramento', 'scenario_kind' => 'tipo de cálculo',
|
||||
'rule_id' => 'regra', 'rule_version' => 'versão da regra', 'rate' => 'taxa', 'reduction' => 'redução',
|
||||
'monthly_sales' => 'vendas mensais', 'monthly_sales.*.date' => 'mês da projecção',
|
||||
'monthly_sales.*.amount' => 'vendas declaradas do mês', 'sales_vat_basis' => 'tratamento do IVA nos preços'];
|
||||
}
|
||||
|
||||
/** @return array<string, list<mixed>> */
|
||||
public function rules(): array
|
||||
{
|
||||
if ($this->input('scenario_kind') === 'fiscal_rule_published') {
|
||||
if ($this->exists('monthly_sales')) {
|
||||
return [
|
||||
'scenario_kind' => ['required', 'in:fiscal_rule_published'],
|
||||
'monthly_sales' => ['required', 'array', 'min:1', 'max:12'],
|
||||
'monthly_sales.*' => ['required', 'array:date,amount'],
|
||||
'monthly_sales.*.date' => ['required', 'date_format:Y-m-d', 'regex:/^2026-\d{2}-01$/D', 'distinct'],
|
||||
'monthly_sales.*.amount' => ['present', 'nullable', 'string', 'max:40', 'regex:/^\d+(?:\.\d+)?$/D'],
|
||||
'sales_vat_basis' => ['required', 'in:net,included,unknown'],
|
||||
'currency' => ['required', 'in:MZN'],
|
||||
'scope_declared' => ['required', 'boolean'],
|
||||
'organization_id' => ['nullable', 'uuid', 'exists:organizations,id'],
|
||||
'base' => ['prohibited'], 'rate' => ['prohibited'], 'reduction' => ['prohibited'],
|
||||
'rule_id' => ['prohibited'], 'rule_version' => ['prohibited'], 'fiscal_preview' => ['prohibited'],
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'scenario_kind' => ['required', 'in:fiscal_rule_published'],
|
||||
'base' => ['required', 'string', 'max:40', 'regex:/^\d+(?:\.\d+)?$/'],
|
||||
'currency' => ['required', 'in:MZN'],
|
||||
'reference_date' => ['required', 'date_format:Y-m-d'],
|
||||
'operation' => ['required', 'in:internal_general_net'],
|
||||
'scope_declared' => ['required', 'boolean'],
|
||||
'organization_id' => ['nullable', 'uuid', 'exists:organizations,id'],
|
||||
'rate' => ['prohibited'], 'reduction' => ['prohibited'],
|
||||
'rule_id' => ['prohibited'], 'rule_version' => ['prohibited'],
|
||||
'fiscal_preview' => ['prohibited'],
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'scenario_kind' => ['sometimes', 'in:custom_planning'],
|
||||
'base' => ['required', 'numeric', 'min:0'],
|
||||
'rate' => ['required', 'numeric', 'between:0,100'],
|
||||
'reduction' => ['required', 'numeric', 'between:0,100'],
|
||||
|
||||
+47
-22
@@ -4,6 +4,7 @@ namespace App\Jobs;
|
||||
|
||||
use App\Models\Simulation;
|
||||
use App\Services\SimulationExecution;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
@@ -62,29 +63,39 @@ class RunSimulation implements ShouldQueue
|
||||
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']]);
|
||||
$resultId = (string) Str::uuid();
|
||||
$engineVersion = 'portal-arithmetic-v1+simulation-v'.$simulation->version_no;
|
||||
$result = ['base' => $input['base'], 'rate_percent' => $input['rate'], 'reduction_percent' => $input['reduction'], 'scenario_kind' => 'custom_planning', 'indicative_total' => $row->value,
|
||||
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-arithmetic-v1',
|
||||
'contract_version' => 1,
|
||||
'context' => [
|
||||
'reference_date' => substr((string) $scenario->created_at, 0, 10),
|
||||
'currency' => null,
|
||||
'currency_fraction_digits' => null,
|
||||
'scenario_id' => (string) $scenario->id,
|
||||
'scenario_version' => (int) $scenario->version_no,
|
||||
'engine_version' => $engineVersion,
|
||||
'ruleset_version' => null,
|
||||
],
|
||||
'result' => [
|
||||
'status' => 'calculated',
|
||||
'value' => (string) $row->value,
|
||||
'unit' => null,
|
||||
'explanation' => 'Resultado aritmético determinístico; não constitui cálculo nem conclusão fiscal.',
|
||||
'missing_inputs' => [],
|
||||
'source_ids' => [],
|
||||
]];
|
||||
if (in_array($input['scenario_kind'] ?? null, ['fiscal_rule_qa_preview', 'fiscal_rule_published'], true)) {
|
||||
if ($input['scenario_kind'] === 'fiscal_rule_qa_preview') {
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
}
|
||||
$result = $input['fiscal_preview'];
|
||||
$engineVersion = $result['context']['engine_version'];
|
||||
$result['context']['scenario_id'] = (string) $scenario->id;
|
||||
$result['context']['scenario_version'] = (int) $scenario->version_no;
|
||||
} else {
|
||||
$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'], 'scenario_kind' => 'custom_planning', 'indicative_total' => $row->value,
|
||||
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-arithmetic-v1',
|
||||
'contract_version' => 1,
|
||||
'context' => [
|
||||
'reference_date' => substr((string) $scenario->created_at, 0, 10),
|
||||
'currency' => null,
|
||||
'currency_fraction_digits' => null,
|
||||
'scenario_id' => (string) $scenario->id,
|
||||
'scenario_version' => (int) $scenario->version_no,
|
||||
'engine_version' => $engineVersion,
|
||||
'ruleset_version' => null,
|
||||
],
|
||||
'result' => [
|
||||
'status' => 'calculated',
|
||||
'value' => (string) $row->value,
|
||||
'unit' => null,
|
||||
'explanation' => 'Resultado aritmético determinístico; não constitui cálculo nem conclusão fiscal.',
|
||||
'missing_inputs' => [],
|
||||
'source_ids' => [],
|
||||
]];
|
||||
}
|
||||
$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);
|
||||
@@ -96,11 +107,25 @@ class RunSimulation implements ShouldQueue
|
||||
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);
|
||||
$sourceJson = json_encode(isset($result['fiscal_provenance']) ? [
|
||||
'base' => $result['base'], 'currency' => $result['currency'],
|
||||
'reference_date' => $result['context']['reference_date'],
|
||||
'context' => $result['fiscal_provenance']['context'], 'scope_status' => $result['fiscal_provenance']['scope_status'],
|
||||
] : $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()]);
|
||||
if (isset($result['fiscal_provenance'])) {
|
||||
$provenance = $result['fiscal_provenance'];
|
||||
$provenanceJson = json_encode($provenance, JSON_THROW_ON_ERROR);
|
||||
$canonicalProvenance = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$provenanceJson])->canonical;
|
||||
DB::table('simulation_result_sources')->insert([
|
||||
'id' => (string) Str::uuid(), 'result_id' => $resultId, 'source_type' => $input['scenario_kind'] === 'fiscal_rule_published' ? 'tax_rule_published' : 'tax_rule_draft',
|
||||
'source_id' => $provenance['rule']['id'], 'source_version' => (string) $provenance['rule']['rule_version'],
|
||||
'source_snapshot' => $provenanceJson, 'source_sha256' => hash('sha256', $canonicalProvenance), '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);
|
||||
|
||||
@@ -16,4 +16,9 @@ class InvestmentLegalSource extends Model
|
||||
use HasUuids;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['fiscal_acceptance' => 'array'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,14 @@ class Opportunity extends Model
|
||||
|
||||
protected $appends = ['maturity_catalogue_version'];
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
$data = parent::toArray();
|
||||
if (isset($data['description'])) $data['description'] = \App\Services\OpportunityPublicText::description($this, $data['description']);
|
||||
if ($this->exists && ($proactive = app(\App\Services\ProactiveInvestment::class)->publicData($this))) $data['proactive'] = $proactive;
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function getMaturityCatalogueVersionAttribute(): ?string
|
||||
{
|
||||
// Only published metadata is public; never expose the current private draft.
|
||||
@@ -68,7 +76,8 @@ class Opportunity extends Model
|
||||
$scope = $public ? 'public' : ($visible && $this->owner_user_id !== null ? 'restricted' : 'unpublished');
|
||||
|
||||
return ['scope' => $scope, 'public_catalog' => $public, 'label' => match ($scope) {
|
||||
'public' => 'Publicada no catálogo público',
|
||||
'public' => data_get($this->workflow_context, 'publication.purpose') === 'promotional_preparation'
|
||||
? 'Resumo divulgado — Em preparação; não autoriza execução' : 'Publicada no catálogo público',
|
||||
'restricted' => 'Disponibilizada com acesso restrito — perfis e organização autorizados',
|
||||
default => 'Sem versão disponibilizada; aprovação interna é uma etapa distinta',
|
||||
}];
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/** Public read projection authorized by Tempo; source rows and originals stay private. */
|
||||
class ApprovedAdministrativeBoundaries
|
||||
{
|
||||
public const HASH = '06ab905fcf9b19115c3521bf81de03f37873880f7765f229b9e1f79d99df7adc';
|
||||
|
||||
/** @var array<string,array<string,string>>|null */
|
||||
private ?array $items = null;
|
||||
|
||||
/** @return array<string,array<string,string>> */
|
||||
public function snapshots(): array
|
||||
{
|
||||
if ($this->items !== null) {
|
||||
return $this->items;
|
||||
}
|
||||
$contents = file_get_contents(base_path('docs/investmoz/unification/approved-administrative-boundaries-20261024.json'));
|
||||
if ($contents === false || ! hash_equals(self::HASH, hash('sha256', str_replace("\r\n", "\n", $contents)))) {
|
||||
throw new RuntimeException('Approved administrative boundary manifest changed.');
|
||||
}
|
||||
$manifest = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (count($manifest['items']) !== 408) {
|
||||
throw new RuntimeException('Exact 408-boundary scope required.');
|
||||
}
|
||||
$this->items = array_column($manifest['items'], null, 'id');
|
||||
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
public function allows(string $id, string $territoryId, string $geometryHash, string $propertiesHash): bool
|
||||
{
|
||||
$item = $this->snapshots()[$id] ?? null;
|
||||
|
||||
return $item !== null && $item['territory_id'] === $territoryId
|
||||
&& hash_equals($item['geometry_sha256'], $geometryHash)
|
||||
&& hash_equals($item['properties_sha256'], $propertiesHash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/** Exact replay of the 28 accepted links into the transported project identities. */
|
||||
final class ApprovedAnchorTerritories
|
||||
{
|
||||
public const HASH = 'd2893d0a638d630435aca1890f79a8094dc58eb65bbdd65a470bb685fa075190';
|
||||
|
||||
/** @return array{manifest_sha256:string,projects:list<array<string,mixed>>,links:list<array<string,mixed>>} */
|
||||
public function plan(): array
|
||||
{
|
||||
$file = base_path('docs/investmoz/unification/approved-anchor-territories-20261023.json');
|
||||
$contents = is_file($file) ? file_get_contents($file) : false;
|
||||
if ($contents !== false) {
|
||||
$contents = str_replace("\r\n", "\n", $contents);
|
||||
}
|
||||
if ($contents === false || ! hash_equals(self::HASH, hash('sha256', $contents))) {
|
||||
throw new RuntimeException('Reviewed territorial manifest changed.');
|
||||
}
|
||||
$manifest = json_decode($contents, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (count($manifest['items']) !== 28) {
|
||||
throw new RuntimeException('Exact 28-link scope required.');
|
||||
}
|
||||
$projects = [];
|
||||
$links = [];
|
||||
foreach ($manifest['items'] as $item) {
|
||||
$project = DB::table('projects')->where('id', $item['project_id'])->whereNull('deleted_at')->first();
|
||||
$dossier = DB::table('investment_dossiers')->where('id', $item['dossier_id'])->whereNull('deleted_at')->first();
|
||||
if (! $project || $project->code !== $item['code'] || ! $dossier || $dossier->project_id !== $project->id
|
||||
|| ! hash_equals($item['content_sha256'], hash('sha256', $dossier->content))
|
||||
|| ! hash_equals($item['source_sha256'], hash('sha256', $dossier->source))) {
|
||||
throw new RuntimeException('Project identity or documentary source changed: '.$item['code']);
|
||||
}
|
||||
$original = $item['original_relation'];
|
||||
$geo = DB::table('geo_locations')->where('id', $original['geo_location_id'])->whereNull('deleted_at')->first();
|
||||
foreach (['location_type', 'source_code', 'parent_id', 'data_classification'] as $field) {
|
||||
if (! $geo || $item['territory'][$field] !== $geo->$field) {
|
||||
throw new RuntimeException('Territory identity changed: '.$original['geo_location_id']);
|
||||
}
|
||||
}
|
||||
$metadata = $projects[$project->id]['after_metadata'] ?? json_decode($project->metadata, true, 512, JSON_THROW_ON_ERROR);
|
||||
$key = $geo->id.':'.$original['role'];
|
||||
$evidence = $item['evidence'];
|
||||
// Preserve the original dossier id in evidence and explicitly map the destination.
|
||||
$evidence['transported_dossier_id'] = $dossier->id;
|
||||
if (isset($metadata['documented_location_sources'][$key]) && $metadata['documented_location_sources'][$key] != $evidence) {
|
||||
throw new RuntimeException('Existing territorial evidence differs; no overwrite: '.$item['code']);
|
||||
}
|
||||
$projects[$project->id] ??= ['id' => $project->id, 'code' => $project->code, 'before_version' => (int) $project->version_no, 'before_metadata' => json_decode($project->metadata, true, 512, JSON_THROW_ON_ERROR)];
|
||||
$metadata['documented_location_sources'][$key] = $evidence;
|
||||
$projects[$project->id]['after_metadata'] = $metadata;
|
||||
$existing = DB::table('project_locations')->where('project_id', $project->id)->where('geo_location_id', $geo->id)->where('role', $original['role'])->first();
|
||||
if ($existing && ($existing->deleted_at || $existing->data_classification !== 'public')) {
|
||||
throw new RuntimeException('Archived or restricted territorial relation must not be revived.');
|
||||
}
|
||||
$identity = DB::table('project_locations')->where('id', $original['id'])->first();
|
||||
if ($identity && (! $existing || $identity->id !== $existing->id)) {
|
||||
throw new RuntimeException('Historical relation identity is already occupied.');
|
||||
}
|
||||
$links[] = ['code' => $item['code'], 'already_present' => (bool) $existing, 'row' => [...$original, 'project_id' => $project->id]];
|
||||
}
|
||||
|
||||
return ['manifest_sha256' => self::HASH, 'projects' => array_values($projects), 'links' => $links];
|
||||
}
|
||||
|
||||
/** Caller supplies an authenticated, backed-up transaction; no source publication changes.
|
||||
* @param array{manifest_sha256:string,projects:list<array<string,mixed>>,links:list<array<string,mixed>>} $plan
|
||||
* @return array<string,int>
|
||||
*/
|
||||
public function apply(array $plan): array
|
||||
{
|
||||
if (DB::transactionLevel() < 1 || $this->plan() !== $plan) {
|
||||
throw new RuntimeException('Reviewed transaction and unchanged preview required.');
|
||||
}
|
||||
$inserted = 0;
|
||||
$updated = 0;
|
||||
foreach ($plan['projects'] as $project) {
|
||||
if ($project['before_metadata'] == $project['after_metadata']) {
|
||||
continue;
|
||||
}
|
||||
$count = DB::table('projects')->where('id', $project['id'])->where('version_no', $project['before_version'])->update([
|
||||
'metadata' => json_encode($project['after_metadata'], JSON_THROW_ON_ERROR), 'version_no' => $project['before_version'] + 1, 'updated_at' => now(),
|
||||
]);
|
||||
if ($count !== 1) {
|
||||
throw new RuntimeException('Concurrent project change.');
|
||||
}
|
||||
DB::table('audit_events')->insert(['source_system' => 'approved-anchor-territories-recovery-v1', 'external_id' => self::HASH.':'.$project['id'], 'entity_type' => 'projects', 'entity_id' => $project['id'], 'action' => 'accepted_territories_restored',
|
||||
'data_classification' => 'public', 'before_data' => json_encode(['version_no' => $project['before_version'], 'metadata' => $project['before_metadata']], JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode(['version_no' => $project['before_version'] + 1, 'manifest_sha256' => self::HASH, 'metadata' => $project['after_metadata'], 'new_approval' => false], JSON_THROW_ON_ERROR)]);
|
||||
$updated++;
|
||||
}
|
||||
foreach ($plan['links'] as $link) {
|
||||
if ($link['already_present']) {
|
||||
continue;
|
||||
}
|
||||
DB::table('project_locations')->insert($link['row']);
|
||||
$inserted++;
|
||||
}
|
||||
|
||||
return ['relations_restored' => $inserted, 'projects_updated' => $updated, 'new_dossiers' => 0, 'publication_changes' => 0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\EconomicCluster;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
final class ClusterCompetitiveness
|
||||
{
|
||||
public const FORCES = ['rivalry', 'entrants', 'substitutes', 'suppliers', 'buyers'];
|
||||
|
||||
public const FIELDS = ['evidence', 'source', 'period', 'rationale', 'limitations', 'opportunity'];
|
||||
|
||||
private const SOURCE = 'cluster-competitiveness';
|
||||
|
||||
private function events(string $cluster): Builder
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)
|
||||
->where('entity_type', 'economic_clusters')->where('entity_id', $cluster);
|
||||
}
|
||||
|
||||
private function decode(?object $event): array
|
||||
{
|
||||
return $event ? json_decode(Crypt::decryptString(json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR)['snapshot']), true, 512, JSON_THROW_ON_ERROR)
|
||||
: ['version' => 0, 'draft' => null, 'approved' => null];
|
||||
}
|
||||
|
||||
public function current(string $cluster): array
|
||||
{
|
||||
return $this->decode($this->events($cluster)->orderByRaw("(after_data->>'version')::integer DESC")->first());
|
||||
}
|
||||
|
||||
public function management(string $cluster): array
|
||||
{
|
||||
$state = $this->current($cluster);
|
||||
$state['history'] = $this->events($cluster)->orderByRaw("(after_data->>'version')::integer DESC")->limit(50)->get()
|
||||
->map(fn ($event) => ['version' => json_decode($event->after_data, true)['version'],
|
||||
'action' => $event->action, 'at' => $event->occurred_at, 'actor' => $event->actor_user_id])->all();
|
||||
|
||||
return $state;
|
||||
}
|
||||
|
||||
public function validateDraft(array $draft, string $cluster): array
|
||||
{
|
||||
$rules = ['version' => 'required|integer|in:1', 'clusterId' => 'required|string|in:'.$cluster,
|
||||
'sector' => 'present|nullable|string|max:200', 'region' => 'present|nullable|string|max:1000',
|
||||
'forces' => 'required|array:'.implode(',', self::FORCES)];
|
||||
foreach (self::FORCES as $force) {
|
||||
$rules["forces.$force"] = 'required|array:pressure,'.implode(',', self::FIELDS);
|
||||
$rules["forces.$force.pressure"] = 'present|nullable|in:low,medium,high';
|
||||
foreach (self::FIELDS as $field) {
|
||||
$rules["forces.$force.$field"] = 'present|nullable|string|max:5000';
|
||||
}
|
||||
}
|
||||
$clean = Validator::make($draft, $rules)->validate();
|
||||
$clean['version'] = 1;
|
||||
$clean['sector'] = trim($clean['sector'] ?? '');
|
||||
$clean['region'] = trim($clean['region'] ?? '');
|
||||
foreach (self::FORCES as $force) {
|
||||
foreach (['pressure', ...self::FIELDS] as $field) {
|
||||
$clean['forces'][$force][$field] = trim($clean['forces'][$force][$field] ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
return $clean;
|
||||
}
|
||||
|
||||
private function assertComplete(?array $draft): void
|
||||
{
|
||||
$missing = ! $draft || ! $draft['sector'] || ! $draft['region'];
|
||||
foreach (self::FORCES as $force) {
|
||||
$row = $draft['forces'][$force] ?? [];
|
||||
$missing = $missing || ! in_array($row['pressure'] ?? '', ['low', 'medium', 'high'], true);
|
||||
foreach (self::FIELDS as $field) {
|
||||
$missing = $missing || trim($row[$field] ?? '') === '';
|
||||
}
|
||||
}
|
||||
if ($missing) {
|
||||
throw ValidationException::withMessages(['approval' => 'Complete o âmbito e as evidências, fontes, períodos, justificação, limitações e oportunidades das cinco forças antes de aprovar.']);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reuse the portal's encrypted, append-only audit snapshots; no new schema or mutable publication fields. */
|
||||
public function change(EconomicCluster $cluster, int $actor, int $expected, string $action, array $input = []): array
|
||||
{
|
||||
return DB::transaction(function () use ($cluster, $actor, $expected, $action, $input) {
|
||||
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
|
||||
$before = $this->current($cluster->id);
|
||||
abort_if($before['version'] !== $expected, 409, 'A análise foi alterada. Conserve os campos actuais e compare a versão do servidor antes de voltar a guardar.');
|
||||
$state = $before;
|
||||
if ($action === 'saved') {
|
||||
$state['draft'] = $this->validateDraft($input['draft'], $cluster->id);
|
||||
} elseif ($action === 'restored') {
|
||||
$event = $this->events($cluster->id)->where('after_data->version', $input['revision'])->first();
|
||||
abort_unless($event, 404);
|
||||
$state['draft'] = $this->decode($event)['draft'];
|
||||
} elseif ($action === 'approved') {
|
||||
$this->assertComplete($state['draft']);
|
||||
$state['approved'] = ['draft' => $state['draft'], 'at' => now()->toISOString(), 'actor' => $actor,
|
||||
'version' => $expected + 1, 'evidence' => $input['reason']];
|
||||
} elseif ($action === 'withdrawn') {
|
||||
$state['approved'] = null;
|
||||
} else {
|
||||
throw new \LogicException('Unsupported competitiveness action');
|
||||
}
|
||||
$state['version']++;
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'economic_clusters',
|
||||
'entity_id' => $cluster->id, 'external_id' => $cluster->id.':'.$state['version'], 'actor_user_id' => $actor,
|
||||
'action' => $action, 'data_classification' => 'restricted',
|
||||
'before_data' => json_encode(['version' => $before['version']], JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode(['version' => $state['version'], 'restored_from' => $input['revision'] ?? null,
|
||||
'reason' => Crypt::encryptString($input['reason'] ?? ''),
|
||||
'snapshot' => Crypt::encryptString(json_encode($state, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $this->management($cluster->id);
|
||||
});
|
||||
}
|
||||
|
||||
public function publicData(string $cluster): ?array
|
||||
{
|
||||
$approved = $this->current($cluster)['approved'];
|
||||
|
||||
// Explicit projection: never return editor identity, approval evidence, history or the unapproved draft.
|
||||
return $approved ? ['draft' => $approved['draft'], 'version' => $approved['version'], 'at' => $approved['at']] : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Navigation over existing authorisations; never grants a role or publishes content. */
|
||||
final class ContentManagement
|
||||
{
|
||||
public function access(?User $actor): array
|
||||
{
|
||||
if (! $actor || ! $actor->hasVerifiedEmail()) return [];
|
||||
$profiles = app(PortalProfileAccess::class);
|
||||
$navigation = $profiles->navigation($actor);
|
||||
$legacy = $profiles->legacyWriteAllowed($actor);
|
||||
$documents = app(DocumentManagementAccess::class);
|
||||
$editor = $documents->full($actor) || $documents->editorial($actor);
|
||||
$upload = $editor || $documents->limited($actor);
|
||||
$result = [];
|
||||
if (app(Procurement::class)->available() && app(Procurement::class)->access($actor)) $result['procurement'] = ['index' => '/management/concursos', 'create' => '/management/concursos/novo'];
|
||||
if ($legacy || ($navigation['mine'] ?? null) || ($navigation['review'] ?? null)) {
|
||||
$result['opportunities'] = ['index' => $legacy ? '/management/opportunities' : '/minhas-oportunidades',
|
||||
'create' => $legacy ? '/management/opportunities/create' : ($navigation['create'] ?? null), 'profileWorkflow' => ! $legacy];
|
||||
}
|
||||
if ($upload) $result['documents'] = ['index' => '/management/portal-services', 'edit' => $editor];
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function view(User $actor): array
|
||||
{
|
||||
$access = $this->access($actor);
|
||||
abort_unless($access !== [], 403);
|
||||
$counts = [];
|
||||
if (isset($access['opportunities'])) {
|
||||
$counts['opportunities'] = app(PortalProfileAccess::class)->scope(Opportunity::query(), $actor)
|
||||
->selectRaw("COALESCE(workflow_context->>'working_state',status) as state, count(*) as total")
|
||||
->groupByRaw("COALESCE(workflow_context->>'working_state',status)")->pluck('total', 'state');
|
||||
}
|
||||
if (isset($access['documents'])) {
|
||||
$documents = app(DocumentManagementAccess::class);
|
||||
$query = $documents->full($actor) ? DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->whereNull('d.deleted_at')
|
||||
: ($access['documents']['edit'] ? $documents->editorialResources($actor) : null);
|
||||
$counts['documents'] = $query ? $query->select('r.published', DB::raw('count(*) as total'))->groupBy('r.published')->get()
|
||||
->mapWithKeys(fn ($row) => [$row->published ? 'published' : 'unpublished' => (int) $row->total]) : [];
|
||||
}
|
||||
return ['access' => $access, 'counts' => $counts];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
|
||||
/** Supplement the six named agribusiness sections without changing corridor masters or source documents. */
|
||||
final class CorridorAgribusiness
|
||||
{
|
||||
public function enrich(string $html, array $links = []): string
|
||||
{
|
||||
$data = json_decode(file_get_contents(__DIR__.'/../../database/data/corridor-investment-opportunities.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$doc = new DOMDocument;
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
try {
|
||||
$doc->loadHTML('<?xml encoding="UTF-8"><html><body>'.$html.'</body></html>', LIBXML_NONET);
|
||||
$body = $doc->getElementsByTagName('body')->item(0);
|
||||
if (! $body) {
|
||||
return $html;
|
||||
}
|
||||
$changed = false;
|
||||
foreach ($data['groups'] as $index => $group) {
|
||||
$marker = 'agronegocio-oportunidades-'.($index + 1);
|
||||
if ($doc->getElementById($marker)) {
|
||||
continue;
|
||||
}
|
||||
foreach (iterator_to_array($body->childNodes) as $heading) {
|
||||
if (! $heading instanceof DOMElement) {
|
||||
continue;
|
||||
}
|
||||
$name = preg_replace('/^[a-f]\)\s*/u', '', trim($heading->textContent));
|
||||
if ($name !== $group['name']) {
|
||||
continue;
|
||||
}
|
||||
$chains = $heading->nextSibling;
|
||||
while ($chains && ! $chains instanceof DOMElement) {
|
||||
$chains = $chains->nextSibling;
|
||||
}
|
||||
// Insert only into the exact named section and its existing priority-chain paragraph.
|
||||
if (! $chains || ! str_starts_with(trim($chains->textContent), 'Cadeias de valor prioritárias:')) {
|
||||
continue;
|
||||
}
|
||||
$fragment = $doc->createDocumentFragment();
|
||||
$label = $doc->createElement('p');
|
||||
$strong = $doc->createElement('strong');
|
||||
$strong->appendChild($doc->createTextNode('Oportunidades de investimento em agronegócio:'));
|
||||
$label->appendChild($strong);
|
||||
$fragment->appendChild($label);
|
||||
$list = $doc->createElement('ul');
|
||||
$list->setAttribute('id', $marker);
|
||||
foreach ($group['opportunities'] as $itemIndex => $opportunity) {
|
||||
$item = $doc->createElement('li');
|
||||
$chain = $doc->createElement('strong');
|
||||
$chain->appendChild($doc->createTextNode($opportunity['chain'].': '));
|
||||
$item->appendChild($chain);
|
||||
$item->appendChild($doc->createTextNode($opportunity['description']));
|
||||
if (isset($links[$index][$itemIndex])) {
|
||||
$item->appendChild($doc->createTextNode(' '));
|
||||
$link = $doc->createElement('a');
|
||||
$link->setAttribute('href', $links[$index][$itemIndex]);
|
||||
$link->appendChild($doc->createTextNode('Conhecer a oportunidade e iniciar o roteiro'));
|
||||
$item->appendChild($link);
|
||||
}
|
||||
$list->appendChild($item);
|
||||
}
|
||||
$fragment->appendChild($list);
|
||||
$source = $doc->createElement('p');
|
||||
$source->appendChild($doc->createTextNode('Fonte das oportunidades: '.$data['source']));
|
||||
$fragment->appendChild($source);
|
||||
$body->insertBefore($fragment, $chains->nextSibling);
|
||||
$changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $changed ? implode('', array_map(fn ($node) => $doc->saveHTML($node), iterator_to_array($body->childNodes))) : $html;
|
||||
} finally {
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
/** Source-defined opportunities; never infer a master corridor, site or promoter. */
|
||||
final class CorridorAgribusinessOpportunities
|
||||
{
|
||||
public const SOURCE_HASH = '1473b06c48aa234e771660e3f2a51b9d2e4e1943bd52d878e0ae854ee6657055';
|
||||
|
||||
/** Documentary cross-reference only; keep the two source designations and master records intact. */
|
||||
public function portfolioOpportunityIds(\App\Models\InvestmentDossier $dossier): array
|
||||
{
|
||||
if (!$dossier->corridor_id || data_get($dossier->content, 'code') !== 'COR-02') return [];
|
||||
// COR-02 is Beira e Centro in investment-portfolio.json. The seven entries are explicitly
|
||||
// grouped under Corredor da Beira in the accepted source, not selected by province/name search.
|
||||
$keys = collect($this->entries())->where('corridor', 'Corredor da Beira')->pluck('key');
|
||||
return Opportunity::published()->whereIn('management_creation_key', $keys)
|
||||
->where('workflow_context->corridor_agribusiness->source_sha256', self::SOURCE_HASH)->pluck('id')->all();
|
||||
}
|
||||
public const LIMITATIONS = 'Promotor, implantação exacta, área, montante, financiamento, viabilidade e licenças não indicados nesta fonte. O corredor é um enquadramento documental; não identifica uma parcela nem confirma disponibilidade.';
|
||||
|
||||
public function entries(): array
|
||||
{
|
||||
$data = json_decode(file_get_contents(database_path('data/corridor-investment-opportunities.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
if ($data['source_sha256'] !== self::SOURCE_HASH) throw new \RuntimeException('Fonte divergente; reconciliar antes de cadastrar.');
|
||||
$sector = Sector::where('slug', 'agronegocio')->where('is_active', true)->whereNull('deleted_at')->firstOrFail();
|
||||
$entries = [];
|
||||
foreach ($data['groups'] as $g => $group) {
|
||||
foreach ($group['opportunities'] as $i => $item) {
|
||||
$key = (string) Uuid::uuid5(Uuid::NAMESPACE_URL, 'investmoz:agronegocio:'.self::SOURCE_HASH.':'.$g.':'.$i);
|
||||
$title = Str::limit($item['chain'].' — '.$group['name'], 150, '…');
|
||||
$description = $item['description']."\n\nEnquadramento documental: ".$group['name'].".\n\nFonte: ".$data['source'].'; SHA-256 '.self::SOURCE_HASH.".\n\n".self::LIMITATIONS;
|
||||
$entries[] = ['key' => $key, 'group' => $g, 'index' => $i, 'corridor' => $group['name'], 'chain' => $item['chain'],
|
||||
'source' => $data['source'], 'source_sha256' => self::SOURCE_HASH, 'title' => $title,
|
||||
'summary' => $item['description'], 'description' => $description, 'sector_id' => $sector->id];
|
||||
}
|
||||
}
|
||||
if (count($entries) !== 34) throw new \RuntimeException('O lote deve conter as 34 entradas da fonte.');
|
||||
return $entries;
|
||||
}
|
||||
|
||||
public function register(User $actor, string $organization): array
|
||||
{
|
||||
// The caller uses the ordinary profile creation route and its approved scope.
|
||||
abort_unless(str_starts_with(request()->path(), 'minhas-oportunidades'), 422);
|
||||
return DB::transaction(function () use ($actor, $organization) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(231026, 34)');
|
||||
$result = [];
|
||||
foreach ($this->entries() as $entry) {
|
||||
$record = Opportunity::withTrashed()->where('management_creation_key', $entry['key'])->first();
|
||||
if ($record) {
|
||||
abort_unless(app(PortalProfileAccess::class)->canView($actor, $record), 403);
|
||||
abort_unless(data_get($record->workflow_context, 'corridor_agribusiness.source_sha256') === self::SOURCE_HASH, 409);
|
||||
// Recovery never overwrites editorial changes, withdrawal or archive.
|
||||
$result[] = ['id' => $record->id, 'created' => false, 'key' => $entry['key']];
|
||||
continue;
|
||||
}
|
||||
$record = app(OpportunityManagement::class)->save($actor, ['creation_key' => $entry['key'], 'organization_id' => $organization,
|
||||
'opportunity_category' => 'investment_project', 'sector_id' => $entry['sector_id'],
|
||||
'title' => $entry['title'], 'summary' => $entry['summary'], 'description' => $entry['description'],
|
||||
'canonical' => ['opportunity_category' => 'investment_project', 'official_title' => $entry['title'],
|
||||
'executive_summary' => $entry['summary'], 'demand_statement' => $entry['description'], 'sector_id' => $entry['sector_id']],
|
||||
'reason' => 'Cadastro privado das 34 oportunidades de agronegócio solicitado pela Tempo em 23/10/2026; não constitui publicação nem aprovação de execução.']);
|
||||
$context = $record->workflow_context ?? [];
|
||||
$context['corridor_agribusiness'] = $entry;
|
||||
$context['promotional_summary'] = ['input' => ['title' => $entry['title'], 'summary' => $entry['summary'],
|
||||
'description' => $entry['description'], 'source_reference' => $entry['source'].'; SHA-256 '.self::SOURCE_HASH,
|
||||
'limitations' => self::LIMITATIONS, 'edition' => '', 'source_date' => '', 'territory_ids' => [], 'sector_id' => $entry['sector_id']]];
|
||||
$record->workflow_context = $context;
|
||||
$record->maturity_label = 'Em preparação';
|
||||
$record->save();
|
||||
DB::table('audit_events')->insert(['source_system' => 'corridor-agribusiness-registration', 'entity_type' => 'opportunity',
|
||||
'action' => 'private_source_registered', 'actor_user_id' => $actor->id, 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['record_id' => $record->id, 'source' => $entry, 'no_publication' => true, 'no_master_relation_inferred' => true], JSON_THROW_ON_ERROR)]);
|
||||
$result[] = ['id' => $record->id, 'created' => true, 'key' => $entry['key']];
|
||||
}
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
|
||||
public function articleLinks(): array
|
||||
{
|
||||
$records = Opportunity::published()->whereIn('management_creation_key', array_column($this->entries(), 'key'))->get()->keyBy('management_creation_key');
|
||||
$links = [];
|
||||
foreach ($this->entries() as $entry) {
|
||||
if ($record = $records->get($entry['key'])) $links[$entry['group']][$entry['index']] = '/oportunidades/'.$record->slug;
|
||||
}
|
||||
return $links;
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,9 @@ class DocumentManagementAccess
|
||||
/** Restore the approved editorial operation without a global management grant. */
|
||||
public function editorial(User $actor): bool
|
||||
{
|
||||
return config('portal.homologation_only', false)
|
||||
&& in_array(strtolower(trim($actor->email)), config('homologation_editorial.accounts', []), true)
|
||||
// Tempo's named editorial designation does not depend on whether the
|
||||
// site's technical reviewer reservation is enabled.
|
||||
return in_array(strtolower(trim($actor->email)), config('homologation_editorial.accounts', []), true)
|
||||
&& app(PortalProfileAccess::class)->superuser($actor)
|
||||
&& ! app(PortalProfileAccess::class)->has($actor, 'auditor')
|
||||
&& app(PortalProfileAccess::class)->mfa($actor);
|
||||
@@ -49,6 +50,11 @@ class DocumentManagementAccess
|
||||
->where('d.external_id', $item['external_id']);
|
||||
});
|
||||
}
|
||||
foreach (json_decode(file_get_contents(config_path('legacy_editorial_resources.json')), true, 512, JSON_THROW_ON_ERROR) as $item) {
|
||||
// These exact original bytes contain the legacy identity/source.
|
||||
// Destination upload IDs differ; the approved file scope does not.
|
||||
$query->orWhere('d.sha256', $item['sha256']);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use GuzzleHttp\Psr7\Uri;
|
||||
use GuzzleHttp\Psr7\UriResolver;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** Reads verified originals without writing a derived edition or changing publication. */
|
||||
final class EditorialReading
|
||||
{
|
||||
public function publicResources()
|
||||
{
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||
->where('r.published', true)->where('r.rights_status', 'authorized')->where('d.rights_status', 'authorized')
|
||||
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
|
||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256');
|
||||
}
|
||||
|
||||
public function original(object $resource): ?array
|
||||
{
|
||||
$document = DB::table('documents')->find($resource->document_id);
|
||||
if (! $document || $document->status !== 'active' || $document->malware_scan_status !== 'clean' || ! in_array($document->media_type, ['text/plain', 'application/json'], true)) {
|
||||
return null;
|
||||
}
|
||||
$binary = app(VerifiedDocumentBinary::class)->respond($document);
|
||||
$bytes = $binary instanceof BinaryFileResponse ? file_get_contents($binary->getFile()->getPathname()) : $binary->getContent();
|
||||
if (! is_string($bytes) || strlen($bytes) > 10485760) {
|
||||
return null;
|
||||
}
|
||||
$original = json_decode($bytes, true);
|
||||
|
||||
return is_array($original) && ($original['format'] ?? '') === 'investmoz-legacy-article-v1' && is_string($original['content_html'] ?? null) ? $original : null;
|
||||
}
|
||||
|
||||
public function plain(string $html): string
|
||||
{
|
||||
return trim(html_entity_decode(strip_tags(preg_replace('~</(?:p|div|li|h[1-6]|tr)>|<br\s*/?>~i', "\n\n", $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
|
||||
}
|
||||
|
||||
public function content(object $resource, ?array $original): array
|
||||
{
|
||||
return $resource->editorial_content ? json_decode($resource->editorial_content, true, 512, JSON_THROW_ON_ERROR)
|
||||
: ['body' => $this->plain($original['content_html'] ?? ''), 'image_resource_id' => null, 'image_mode' => 'original', 'preserve_original_html' => true];
|
||||
}
|
||||
|
||||
private function sourceUrl(mixed $url, ?string $base = null): ?string
|
||||
{
|
||||
if (! is_string($url) || trim($url) === '') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$absolute = $base ? (string) UriResolver::resolve(new Uri($base), new Uri($url)) : $url;
|
||||
|
||||
return filter_var($absolute, FILTER_VALIDATE_URL) && in_array(strtolower((string) parse_url($absolute, PHP_URL_SCHEME)), ['http', 'https'], true) ? $absolute : null;
|
||||
} catch (\InvalidArgumentException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function reading(object $resource, ?array $override = null, bool $private = false): array
|
||||
{
|
||||
$original = $this->original($resource);
|
||||
$content = $override ?? $this->content($resource, $original);
|
||||
abort_unless(trim($content['body'] ?? '') !== '', 404, 'Este documento não contém um artigo legível.');
|
||||
$document = DB::table('documents')->find($resource->document_id);
|
||||
// The original is verified above; ordinary text adaptations retain the binary gate too.
|
||||
app(VerifiedDocumentBinary::class)->respond($document);
|
||||
$mode = $content['image_mode'] ?? (! empty($content['image_resource_id']) ? 'selected' : 'none');
|
||||
$originalImageUrl = $this->sourceUrl($original['image_source_url'] ?? null, $original['source_url'] ?? null);
|
||||
$expectedImageSha = $original['image_sha256'] ?? null;
|
||||
if (! $expectedImageSha && $originalImageUrl === 'https://investemoz.tempo.co.mz/images/tempo-background.png') {
|
||||
foreach (json_decode(file_get_contents(config_path('legacy_editorial_resources.json')), true, 512, JSON_THROW_ON_ERROR) as $accepted) {
|
||||
if ($accepted['sha256'] === $document->sha256) {
|
||||
$expectedImageSha = $accepted['original_image_sha256'] ?? null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
$images = $this->publicResources()->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp']);
|
||||
$image = null;
|
||||
if ($mode === 'selected' && ! empty($content['image_resource_id'])) {
|
||||
$image = (clone $images)->where('r.id', $content['image_resource_id'])->first(['r.id', 'r.title']);
|
||||
}
|
||||
if ($mode === 'original' && $original) {
|
||||
$image = (clone $images)->where(function ($q) use ($expectedImageSha, $originalImageUrl) {
|
||||
$q->whereRaw('1=0');
|
||||
if ($expectedImageSha) {
|
||||
$q->orWhere('d.sha256', $expectedImageSha);
|
||||
} elseif ($originalImageUrl) {
|
||||
$q->orWhere('r.source_url', $originalImageUrl)->orWhere('d.original_source', $originalImageUrl);
|
||||
}
|
||||
})->first(['r.id', 'r.title']);
|
||||
}
|
||||
if ($image) {
|
||||
// A public flag alone never licenses missing or changed image bytes.
|
||||
$binary = (clone $images)->where('r.id', $image->id)->first(['d.*']);
|
||||
try {
|
||||
app(VerifiedDocumentBinary::class)->respond($binary);
|
||||
} catch (HttpException) {
|
||||
$image = null;
|
||||
}
|
||||
}
|
||||
$originalFormat = $original && ($content['preserve_original_html'] ?? false) && $content['body'] === $this->plain($original['content_html']);
|
||||
$html = $originalFormat ? app(LegacyContent::class)->sanitize($original['content_html'], true) : null;
|
||||
$imageReferences = [];
|
||||
if ($original) {
|
||||
preg_match_all('~<img\b[^>]*\bsrc\s*=\s*([\'"])(.*?)\1~is', $original['content_html'], $matches);
|
||||
foreach ($matches[2] as $source) {
|
||||
$url = $this->sourceUrl(html_entity_decode($source, ENT_QUOTES | ENT_HTML5, 'UTF-8'), $original['source_url'] ?? null);
|
||||
if ($url) {
|
||||
$imageReferences[] = $url;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['id' => $resource->id, 'title' => $resource->title, 'description' => $resource->description,
|
||||
'author' => $document->issuer, 'body' => $content['body'], 'html' => $html,
|
||||
'image_url' => $image ? '/documentos/'.$image->id.'/view' : null,
|
||||
'image_notice' => $mode === 'selected' && ! $image ? 'A imagem escolhida está indisponível para divulgação; a selecção mantém-se na edição.' : ($mode === 'original' && ! $image && ! empty($original['image_source_url']) ? 'Imagem de origem referenciada, mas sem exemplar público verificado na biblioteca. A referência original mantém-se preservada.' : null),
|
||||
'source_url' => $this->sourceUrl($original['source_url'] ?? $resource->source_url),
|
||||
'published_at' => $original['published_at'] ?? null, 'modified_at' => $original['modified_at'] ?? null,
|
||||
'legacy_id' => $original['legacy_id'] ?? null, 'image_source_url' => $originalImageUrl, 'image_expected_sha256' => $expectedImageSha, 'image_references' => array_values(array_unique($imageReferences)),
|
||||
'metadata_version' => $resource->metadata_version, 'private_preview' => $private,
|
||||
'original_url' => $private ? '/management/documents/'.$resource->document_id.'/download' : '/documentos/'.$resource->id,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ class InvestmentCatalogue
|
||||
/** @return array<string,mixed> */
|
||||
public function filters(Request $request): array
|
||||
{
|
||||
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
||||
$filters = $request->validate(['perspective' => ['nullable', 'in:exists,needs,ideas,opportunities'],'q' => ['nullable', 'string', 'max:120'], 'sector' => ['nullable', 'string', 'max:80'],
|
||||
'preparation' => ['nullable', \Illuminate\Validation\Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
|
||||
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||
@@ -26,7 +26,7 @@ class InvestmentCatalogue
|
||||
'cluster_id' => ['nullable', 'uuid'], 'corridor_id' => ['nullable', 'uuid'], 'project_id' => ['nullable', 'uuid'],
|
||||
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
|
||||
'zee_id' => ['nullable', 'uuid'], 'zfi_id' => ['nullable', 'uuid'], 'park_id' => ['nullable', 'uuid'],
|
||||
'dimension' => ['nullable', 'in:cluster,corridor,zee,zfi'], 'view' => ['nullable', 'in:grid,list,map,combined'],
|
||||
'dimension' => ['nullable', 'in:cluster,corridor,zee,zfi'], 'view' => ['nullable', 'in:grid,list,map,combined,corridors'],
|
||||
'maturity_level' => ['nullable', 'integer', 'between:1,8'], 'facets' => ['nullable', 'array', 'max:20'], 'facets.*' => ['integer', 'min:1'],
|
||||
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
||||
'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])],
|
||||
@@ -63,13 +63,17 @@ class InvestmentCatalogue
|
||||
public function query(array $filters): Builder
|
||||
{
|
||||
$query = Opportunity::published()->with('sector:id,name,slug');
|
||||
if (in_array($filters['perspective'] ?? '', ['exists','needs','ideas'], true)) $query->where('workflow_context->promotional_summary->projection->proactive->group', $filters['perspective']);
|
||||
elseif (($filters['perspective'] ?? '') === 'opportunities') $query->whereNull('workflow_context->promotional_summary->projection->proactive');
|
||||
$associated = $this->publicAssociatedIds($filters);
|
||||
if (($filters['territory_basis'] ?? 'all') === 'direct') {
|
||||
$query->where(fn ($q) => $q->whereNotNull('opportunities.primary_territory_id')->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id')));
|
||||
} elseif (($filters['territory_basis'] ?? 'all') === 'context') {
|
||||
$query->whereNull('opportunities.primary_territory_id')->whereNotExists(fn ($l) => $l->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'));
|
||||
$query->where(fn ($q) => $q->whereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_projects')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('project_id', app(InvestmentRelations::class)->projectIds()))
|
||||
->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_clusters')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('cluster_id', $this->publicStructureIds('clusters', 'cluster_id'))));
|
||||
->orWhereExists(fn ($l) => $l->selectRaw('1')->from('opportunity_clusters')->whereColumn('opportunity_id', 'opportunities.id')->whereIn('cluster_id', $this->publicStructureIds('clusters', 'cluster_id')))
|
||||
->orWhere(fn ($source) => $source->where('workflow_context->corridor_agribusiness->source_sha256', CorridorAgribusinessOpportunities::SOURCE_HASH)
|
||||
->whereIn('workflow_context->corridor_agribusiness->corridor', array_column(config('investment_corridors', []), 'name'))));
|
||||
}
|
||||
if (! empty($filters['opportunity_id'])) {
|
||||
$query->whereKey($filters['opportunity_id']);
|
||||
@@ -78,12 +82,13 @@ class InvestmentCatalogue
|
||||
$includeNational = filter_var($filters['include_national'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
if ($path !== []) {
|
||||
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->where(function ($territory) use ($ids, $includeNational, $filters): void {
|
||||
$query->where(function ($territory) use ($ids, $includeNational, $filters, $path): void {
|
||||
$territory->whereIn('opportunities.primary_territory_id', $ids)
|
||||
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('opportunity_locations as territory_link')
|
||||
->whereColumn('territory_link.opportunity_id', 'opportunities.id')->whereIn('territory_link.geo_location_id', $ids));
|
||||
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
||||
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
|
||||
if (count($path) === 1) $this->approvedCorridorProvince($territory, $path[0]->id);
|
||||
}
|
||||
if ($includeNational) {
|
||||
$territory->orWhere('opportunities.geography_scope', 'national');
|
||||
@@ -160,6 +165,9 @@ class InvestmentCatalogue
|
||||
->whereNull('target.deleted_at')->where('target.data_classification', 'public'));
|
||||
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
||||
app(InvestmentRelations::class)->opportunityTerritories($matches, $locationIds ?? []);
|
||||
if (app(InvestmentGeography::class)->publicReferences()->where('id', $filters['geo_location_id'])->where('location_type', 'province')->exists()) {
|
||||
$this->approvedCorridorProvince($matches, $filters['geo_location_id']);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -210,6 +218,38 @@ class InvestmentCatalogue
|
||||
};
|
||||
}
|
||||
|
||||
private function approvedCorridorProvince($query, string $provinceId): void
|
||||
{
|
||||
$code = app(InvestmentGeography::class)->publicReferences()->where('id', $provinceId)->value('source_code');
|
||||
$names = [];
|
||||
foreach (config('investment_corridors', []) as $entry) {
|
||||
if (in_array($code, $entry['provinces'], true)) $names[] = $entry['name'];
|
||||
}
|
||||
if (!$names) return;
|
||||
$query->orWhere(fn ($context) => $context->whereNull('opportunities.primary_territory_id')
|
||||
->whereNotExists(fn ($link) => $link->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'))
|
||||
->where('workflow_context->corridor_agribusiness->source_sha256', CorridorAgribusinessOpportunities::SOURCE_HASH)
|
||||
->whereIn('workflow_context->corridor_agribusiness->corridor', $names));
|
||||
}
|
||||
|
||||
/** Public result presentation only; no editorial or territorial data is saved. */
|
||||
public function presentLocation(Opportunity $record): Opportunity
|
||||
{
|
||||
$geo = app(InvestmentGeography::class);
|
||||
$paths = [];
|
||||
$ids = array_filter([$record->primary_territory_id, ...$record->additionalTerritories()->pluck('geo_locations.id')->all()]);
|
||||
foreach (array_unique($ids) as $id) {
|
||||
$path = $geo->path($id);
|
||||
if ($path) $paths[] = implode(' / ', array_column($path, 'name'));
|
||||
}
|
||||
if ($paths) $label = implode('; ', array_unique($paths));
|
||||
elseif ($provinces = app(InvestmentCorridorContext::class)->catalogueProvinces($record)) {
|
||||
$label = implode(' / ', array_column($provinces, 'name')).' — contexto provincial do corredor; distrito e posto administrativo não indicados';
|
||||
} else $label = implode(' / ', array_filter([$record->province, $record->district])) ?: 'Localização não indicada';
|
||||
$record->setAttribute('territorial_summary', $label);
|
||||
return $record;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $territoryFilters
|
||||
* @return array<string,mixed> */
|
||||
public function references(bool $management = false, array $territoryFilters = []): array
|
||||
@@ -231,16 +271,25 @@ class InvestmentCatalogue
|
||||
} elseif (in_array($relation, ['clusters', 'corridors'], true)) {
|
||||
$query->whereIn('id', $this->publicStructureIds($relation, $foreign));
|
||||
} else {
|
||||
$query->whereIn('id', InvestmentPortfolioController::visible()->whereNotNull($foreign)->pluck($foreign));
|
||||
$query->whereIn('id', app(OpportunityClassification::class)->targets('project')->select('id'));
|
||||
}
|
||||
}
|
||||
if (! $management && $path !== [] && $relation !== 'locations') {
|
||||
$dossiers = InvestmentPortfolioController::visible();
|
||||
app(InvestmentGeography::class)->constrainDossiersToTerritories($dossiers,
|
||||
app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
|
||||
$query->whereIn('id', $dossiers->whereNotNull($foreign)->select($foreign));
|
||||
$territories = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->where(fn ($area) => $area->whereIn('primary_territory_id', $territories)
|
||||
->orWhereIn('id', $dossiers->whereNotNull($foreign)->select($foreign)));
|
||||
}
|
||||
$result[$relation] = $query->orderBy('name')->get(['id', 'name']);
|
||||
if (! $management && $relation !== 'locations') {
|
||||
$dossiers = InvestmentPortfolioController::visible()->whereIn($foreign, $result[$relation]->pluck('id'))
|
||||
->orderBy('id')->get(['id', $foreign])->unique($foreign)->keyBy($foreign);
|
||||
$result[$relation]->each(function ($record) use ($dossiers): void {
|
||||
$record->url = isset($dossiers[$record->id]) ? '/carteira/'.$dossiers[$record->id]->id : null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
$zones = app(InvestmentZones::class)->visible();
|
||||
@@ -250,24 +299,15 @@ class InvestmentCatalogue
|
||||
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
|
||||
}
|
||||
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
||||
if (! $management && ($path !== [] || ! empty($territoryFilters['sector']))) {
|
||||
$scope = \Illuminate\Support\Arr::only($territoryFilters, ['sector','province_id','district_id','admin_post_id','locality_id','include_national']);
|
||||
$available = ['chain' => [], 'activity' => []];
|
||||
$this->query($scope)->reorder()->chunkById(200, function ($records) use (&$available) {
|
||||
foreach ($records as $record) {
|
||||
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
||||
if (isset($available[$row['target_type']])) $available[$row['target_type']][] = $row['target_id'];
|
||||
}
|
||||
foreach (['subsector_id','economic_activity_id'] as $key) {
|
||||
$id = $record->workflow_context['publication']['taxonomy'][$key] ?? null;
|
||||
if ($id) $available['activity'][] = $id;
|
||||
}
|
||||
}
|
||||
}, 'opportunities.id', 'id');
|
||||
foreach ($available as $kind => $ids) {
|
||||
$result['classification']['targets'][$kind] = collect($result['classification']['targets'][$kind])->whereIn('id', $ids)->values();
|
||||
}
|
||||
if (! $management && $path !== []) {
|
||||
// A chain's documented scope comes from its public cluster, never
|
||||
// from the opportunities surviving the current search.
|
||||
$ids = app(OpportunityClassification::class)->targets('chain')
|
||||
->whereIn('cluster_id', $result['clusters']->pluck('id'))->pluck('id');
|
||||
$result['classification']['targets']['chain'] = collect($result['classification']['targets']['chain'])->whereIn('id', $ids)->values();
|
||||
}
|
||||
// Activities are a public classification catalogue, not evidence of
|
||||
// investment availability in a territory or sector.
|
||||
|
||||
return $result;
|
||||
}
|
||||
@@ -292,6 +332,10 @@ class InvestmentCatalogue
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!empty($selected['corridor_id'])) {
|
||||
$dossier = InvestmentPortfolioController::visible()->where('corridor_id', $selected['corridor_id'])->first();
|
||||
if ($dossier) $ids['corridor_id'] = array_values(array_unique([...($ids['corridor_id'] ?? []), ...app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($dossier)]));
|
||||
}
|
||||
return $ids;
|
||||
}
|
||||
|
||||
@@ -308,6 +352,18 @@ class InvestmentCatalogue
|
||||
/** @return array<string,mixed> */
|
||||
public function context(int $id, bool $management = false): array
|
||||
{
|
||||
$opportunity = Opportunity::findOrFail($id);
|
||||
if (! $management && data_get($opportunity->workflow_context, 'publication.purpose') === OpportunityPromotion::PURPOSE) {
|
||||
// Promotional disclosure includes only its explicit public coverage.
|
||||
// Private profiles, source evidence and other dossier relations are not auto-published.
|
||||
$public = ['profile' => null, 'facets' => collect(), 'zones' => collect(), 'classification' => [], 'source_evidence' => [],
|
||||
'primary_territory_path' => app(InvestmentGeography::class)->path($opportunity->primary_territory_id, true),
|
||||
'opportunity_locations' => app(InvestmentRelations::class)->opportunityLocations($id)];
|
||||
foreach (self::RELATIONS as $relation => $_) $public[$relation] = collect();
|
||||
$public['locations'] = DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')
|
||||
->where('l.opportunity_id', $id)->where('g.data_classification', 'public')->whereNull('g.deleted_at')->get(['g.id', 'g.name']);
|
||||
return $public;
|
||||
}
|
||||
$result = ['profile' => DB::table('opportunity_profiles')->where('opportunity_id', $id)->first(),
|
||||
'facets' => DB::table('opportunity_facets as f')->join('investment_reference_options as o', 'o.id', '=', 'f.option_id')
|
||||
->where('f.opportunity_id', $id)->get(['o.id', 'o.group', 'o.label'])];
|
||||
@@ -411,7 +467,7 @@ class InvestmentCatalogue
|
||||
$located = 0;
|
||||
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.($filters === [] ? '' : '?'.http_build_query($filters))];
|
||||
'location' => $this->presentLocation($record)->getAttribute('territorial_summary'), 'url' => '/oportunidades/'.$record->slug.($filters === [] ? '' : '?'.http_build_query($filters))];
|
||||
foreach ($relations as $relation => $groups) {
|
||||
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Resolve documented complements without creating opportunities or master relations. */
|
||||
final class InvestmentComplements
|
||||
{
|
||||
private const TERMS = [
|
||||
'irrigation' => ['Regadio', 'regadio|irrigação|irrigacao'],
|
||||
'storage' => ['Silos e armazenagem', 'silos?|armazenagem|armazenamento'],
|
||||
'cold' => ['Cadeia de frio', 'frio|refrigeração'],
|
||||
'processing' => ['Processamento', 'processamento|transformação|moagem'],
|
||||
'spinning' => ['Fiação', 'fiação|fiacao'],
|
||||
'logistics' => ['Logística', 'logística|logistica|transporte'],
|
||||
'certification' => ['Certificação', 'certificação|certificacao'],
|
||||
'training' => ['Formação', 'formação|formacao'],
|
||||
'finance' => ['Financiamento', 'financiamento|serviços financeiros'],
|
||||
];
|
||||
|
||||
public function options(string $origin, ?string $territory = null): array
|
||||
{
|
||||
[$originKind, $originId] = array_pad(explode(':', $origin, 2), 2, '');
|
||||
abort_unless(($originKind === 'portfolio' && Str::isUuid($originId)) || ($originKind === 'opportunity' && ctype_digit($originId)), 422, 'Origem complementar inválida.');
|
||||
$principal = null;
|
||||
$relationEvidence = [];
|
||||
if (str_starts_with($origin, 'portfolio:')) {
|
||||
$record = InvestmentPortfolioController::visible()->addSelect('version_no')->findOrFail(substr($origin, 10));
|
||||
$text = trim(($record->content['focus'] ?? '')."\n".($record->content['gaps'] ?? '')."\n".($record->content['description'] ?? ''));
|
||||
$reference = ['key' => $origin, 'title' => $record->title, 'href' => '/carteira/'.$record->id, 'version' => $record->version_no];
|
||||
$ids = app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($record);
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
|
||||
if ($record->$foreign) $ids = [...$ids, ...DB::table('opportunity_'.$relation)->where($foreign, $record->$foreign)->pluck('opportunity_id')->all()];
|
||||
}
|
||||
$basis = $record->source;
|
||||
foreach (array_unique($ids) as $id) $relationEvidence[$id] = ['type' => 'portfolio', 'origin' => $origin, 'source' => $basis];
|
||||
$serviceOrigins = [['dossier', $record->id]];
|
||||
foreach (['project_id' => 'project', 'cluster_id' => 'cluster'] as $foreign => $type) {
|
||||
if ($record->$foreign) $serviceOrigins[] = [$type, $record->$foreign];
|
||||
}
|
||||
} else {
|
||||
$reference = app(InvestorContext::class)->reference($origin);
|
||||
abort_unless($reference['kind'] === 'opportunity', 422);
|
||||
// The context resolver has already checked the actor's private scope.
|
||||
// A private preparation is valid dossier input, not a public offer
|
||||
// from which this public-complement catalogue can infer services.
|
||||
if (($reference['visibility'] ?? 'public') === 'private') return [];
|
||||
$principal = Opportunity::published()->findOrFail($reference['id']);
|
||||
$text = $principal->summary;
|
||||
$basis = 'Resumo cadastrado da oportunidade '.$principal->reference;
|
||||
$projects = DB::table('opportunity_projects')->where('opportunity_id', $principal->id)->pluck('project_id');
|
||||
$links = DB::table('complementary_project_links')->whereIn('anchor_project_id', $projects)
|
||||
->whereNull('deleted_at')->where('data_classification', 'public')->get(['id', 'anchor_project_id', 'complementary_project_id', 'relation_type', 'version_no']);
|
||||
$targetProjects = DB::table('opportunity_projects')->whereIn('project_id', $links->pluck('complementary_project_id'))->get();
|
||||
$ids = [$principal->id, ...$targetProjects->pluck('opportunity_id')->all()];
|
||||
$relationEvidence[$principal->id] = ['type' => 'same_fiche', 'source' => $basis];
|
||||
foreach ($targetProjects as $targetProject) $relationEvidence[$targetProject->opportunity_id] = ['type' => 'complementary_project',
|
||||
'links' => $links->where('complementary_project_id', $targetProject->project_id)->values()->map(fn($link) => (array)$link)->all()];
|
||||
foreach (Opportunity::published()->whereIn('id', $ids)->where('id', '!=', $principal->id)->get() as $linked) $text .= "\n".$linked->summary;
|
||||
if (count($ids) > 1) $basis .= '; relações complementares públicas entre projectos';
|
||||
$serviceOrigins = [['investment', (string) $principal->id]];
|
||||
$classification = app(OpportunityClassification::class);
|
||||
$principalChains = collect($classification->publicRows($principal))->where('target_type', 'chain')->filter(fn($r) => !empty($r['source_reference']));
|
||||
$chains = $principalChains->pluck('target_id')->all();
|
||||
if ($chains) {
|
||||
Opportunity::published()->whereNot('id', $principal->id)->chunkById(100, function ($records) use (&$ids, &$relationEvidence, $chains, $principalChains, $classification) {
|
||||
foreach ($records as $candidate) {
|
||||
$related = collect($classification->publicRows($candidate))->where('target_type', 'chain')->filter(fn($r) => !empty($r['source_reference']));
|
||||
$shared = array_intersect($chains, $related->pluck('target_id')->all());
|
||||
if ($shared) {
|
||||
$ids[] = $candidate->id;
|
||||
$relationEvidence[$candidate->id] ??= ['type' => 'value_chain', 'principal' => $principalChains->whereIn('target_id', $shared)->values()->all(), 'target' => $related->whereIn('target_id', $shared)->values()->all()];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
$territoryReference = $territory ? app(InvestorContext::class)->reference('territory:'.$territory) : null;
|
||||
$candidates = Opportunity::published()->whereIn('id', array_unique($ids))->get();
|
||||
$items = [];
|
||||
foreach (self::TERMS as $code => [$label, $pattern]) {
|
||||
if (!preg_match('/\b(?:'.$pattern.')\b/iu', $text, $match)) continue;
|
||||
$offers = [];
|
||||
foreach ($candidates as $candidate) {
|
||||
// A common corridor alone does not prove the component. Keep the supporting excerpt.
|
||||
if (!preg_match('/\b(?:'.$pattern.')\b/iu', $candidate->title."\n".$candidate->summary, $evidence)) continue;
|
||||
// Mentioning a need for funding/training in a project's summary is not an offer.
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && !preg_match('/\b(?:'.$pattern.')\b/iu', $candidate->title)) continue;
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && preg_match('/\b(?:necessidade|pedido|procura)\b/iu', $candidate->title)) continue;
|
||||
if ($territory && $candidate->primary_territory_id && !$this->compatible($territory, $candidate->primary_territory_id)) continue;
|
||||
$offers[] = ['key' => 'opportunity:'.$candidate->id, 'title' => $candidate->title, 'href' => '/oportunidades/'.$candidate->slug,
|
||||
'relationship' => $relationEvidence[$candidate->id] ?? null,
|
||||
'version' => $candidate->management_version, 'evidence' => $evidence[0], 'location' => ($principal && $principal->id === $candidate->id ? 'Componente referido na própria ficha. ' : '').($candidate->primary_territory_id ? app(InvestorContext::class)->reference('territory:'.$candidate->primary_territory_id)['title'] : 'Implantação por definir')];
|
||||
}
|
||||
// Services are concrete published offerings explicitly associated with this source.
|
||||
$services = [];
|
||||
if (in_array($code, ['certification', 'training', 'finance'], true) && Schema::hasTable('partnership_origins') && Schema::hasTable('partnership_interests')) {
|
||||
if ($serviceOrigins) {
|
||||
$services = DB::table('portal_partnerships as p')->join('partnership_origins as o', 'o.partnership_id', '=', 'p.id')
|
||||
->where(function ($q) use ($serviceOrigins) {
|
||||
foreach ($serviceOrigins as [$type, $id]) $q->orWhere(fn($q) => $q->where('o.type', $type)->where('o.target_id', $id));
|
||||
})->where('p.status', 'published')->where('p.kind', 'offering')
|
||||
->where('p.partnership_type', $code === 'finance' ? 'finance' : 'training')
|
||||
->when($code !== 'finance', fn($q) => $q->where(fn($q) => $q->where('p.title', 'ilike', '%'.$match[0].'%')->orWhereRaw("p.payload->>'summary' ILIKE ?", ['%'.$match[0].'%'])))->distinct()->get(['p.id', 'p.title'])
|
||||
->filter(function ($p) use ($territory) {
|
||||
if (!$territory) return true;
|
||||
$locations = DB::table('partnership_locations')->where('partnership_id', $p->id)->pluck('geo_location_id');
|
||||
return $locations->isEmpty() || $locations->contains(fn($id) => $this->compatible($territory, $id));
|
||||
})->map(fn ($p) => ['key' => 'partnership:'.$p->id, 'title' => $p->title, 'href' => '/parcerias/'.$p->id, 'location' => 'Consultar âmbito na oferta'])->values()->all();
|
||||
}
|
||||
}
|
||||
$excerpt = collect(explode("\n", $text))->first(fn($line) => preg_match('/\b(?:'.$pattern.')\b/iu', $line));
|
||||
$items[] = ['code' => $code, 'title' => $label, 'origin' => $reference, 'territory_id' => $territory, 'territory' => $territoryReference,
|
||||
'source' => $basis, 'excerpt' => $excerpt, 'source_sha256' => hash('sha256', $text), 'opportunities' => $offers, 'services' => $services];
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
|
||||
private function compatible(string $a, string $b): bool
|
||||
{
|
||||
if ($a === $b) return true;
|
||||
$geo = app(InvestmentGeography::class);
|
||||
return in_array($b, $geo->descendants($a), true) || in_array($a, $geo->descendants($b), true);
|
||||
}
|
||||
|
||||
public function resolve(array $input, array $previous = []): array
|
||||
{
|
||||
$resolved = [];
|
||||
foreach ($input as $choice) {
|
||||
$target = $choice['target'] ?? null;
|
||||
$old = collect($previous)->first(fn($r) => $r['origin']['key'] === $choice['origin'] && $r['code'] === $choice['code'] && ($r['target']['key'] ?? null) === $target && ($r['territory_id'] ?? null) === ($choice['territory_id'] ?? null));
|
||||
try {
|
||||
$item = collect($this->options($choice['origin'], $choice['territory_id'] ?? null))->firstWhere('code', $choice['code']);
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
|
||||
if (!$old) throw $e;
|
||||
$item = null;
|
||||
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
|
||||
if (!$old || $e->getStatusCode() !== 404) throw $e;
|
||||
$item = null;
|
||||
}
|
||||
$offer = $target && $item ? collect([...$item['opportunities'], ...$item['services']])->firstWhere('key', $target) : null;
|
||||
if ($old && (!$item || ($target && !$offer) || (!$target && ($item['opportunities'] || $item['services'])))) {
|
||||
$resolved[$old['key']] = [...$old, 'availability' => 'review_required'];
|
||||
continue;
|
||||
}
|
||||
abort_unless($item, 422, 'Complemento sem referência documentada neste investimento.');
|
||||
abort_if($target && !$offer, 422, 'A oferta complementar deixou de estar disponível neste contexto.');
|
||||
abort_if(!$target && ($item['opportunities'] || $item['services']), 422, 'Já existe uma oferta relacionada; seleccione a ficha correspondente.');
|
||||
$key = hash('sha256', $choice['origin'].'|'.$choice['code'].'|'.($target ?? 'idea').'|'.($choice['territory_id'] ?? ''));
|
||||
$resolved[$key] = ['key' => $key, 'origin' => $item['origin'], 'code' => $item['code'], 'title' => $item['title'],
|
||||
'kind' => $target ? (str_starts_with($target, 'opportunity:') ? 'opportunity' : 'service') : 'need',
|
||||
'target' => $offer, 'territory_id' => $item['territory_id'], 'territory' => $item['territory'], 'source' => $item['source'], 'excerpt' => $item['excerpt'], 'source_sha256' => $item['source_sha256']];
|
||||
}
|
||||
return array_values($resolved);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
/** An identified opportunity within the authorised dossier, never the account's last choice. */
|
||||
final class InvestmentConsumerScope
|
||||
{
|
||||
public function key(array $context, ?string $key, bool $required = false): ?string
|
||||
{
|
||||
$choices = $context['opportunity_choices'] ?? [];
|
||||
$key = $key ?: (count($choices) === 1 ? $choices[0]['opportunity']['key'] : null);
|
||||
abort_if($key && !collect($choices)->contains('opportunity.key', $key), 422, 'Escolha uma oportunidade deste dossier.');
|
||||
abort_if($required && count($choices) > 1 && !$key, 422, 'Escolha a oportunidade em tratamento.');
|
||||
return $key;
|
||||
}
|
||||
|
||||
public function facts(array $payload, array $context, ?string $key): array
|
||||
{
|
||||
$key = $this->key($context, $key);
|
||||
$path = $payload['investor_path'] ?? [];
|
||||
$defaults = ['land_needed' => 'unknown', 'external_funding' => 'unknown', 'viability' => 'unknown'];
|
||||
// A dossier-wide dispensation cannot decide a distinct opportunity's needs.
|
||||
if ($key && count($context['opportunity_choices'] ?? []) > 1) return [...$defaults, ...($path['opportunity_facts'][$key] ?? [])];
|
||||
if ($key && isset($path['opportunity_facts'][$key])) return [...$defaults, ...$path['opportunity_facts'][$key]];
|
||||
if (count($context['opportunity_choices'] ?? []) > 1) return $defaults;
|
||||
return [...$defaults, ...($path['facts'] ?? [])];
|
||||
}
|
||||
|
||||
public function context(array $context, ?string $key): array
|
||||
{
|
||||
$choices = $context['opportunity_choices'] ?? [];
|
||||
if (!$choices) return $context;
|
||||
$key = $key ?: (count($choices) === 1 ? $choices[0]['opportunity']['key'] : null);
|
||||
$choice = $key ? collect($choices)->firstWhere('opportunity.key', $key) : null;
|
||||
abort_if($key && !$choice, 422, 'Escolha uma oportunidade deste dossier.');
|
||||
$specific = ['project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'special_zone_id', 'investment_regime'];
|
||||
$context['fields'] = Arr::except($context['fields'], $specific);
|
||||
$context['provenance'] = Arr::except($context['provenance'] ?? [], $specific);
|
||||
$context['selection'] = Arr::except($context['selection'], ['opportunity', 'territory', 'park']);
|
||||
if (!$choice) {
|
||||
$context['opportunity_choices'] = [];
|
||||
$context['requirements_assessment']['requirements'] = [];
|
||||
return $context;
|
||||
}
|
||||
$context['selection']['opportunity'] = $choice['opportunity'];
|
||||
$context['fields'] = [...$context['fields'], ...Arr::only($choice['opportunity']['fields'], $specific)];
|
||||
foreach (Arr::only($choice['opportunity']['fields'], $specific) as $field => $value) $context['provenance'][$field] = Arr::only($choice['opportunity'], ['key','kind','id','title','version','sha256']);
|
||||
unset($context['selection']['sector']);
|
||||
if (!empty($context['fields']['sector_id'])) $context['selection']['sector'] = app(InvestorContext::class)->reference('sector:'.$context['fields']['sector_id']);
|
||||
if ($choice['territory']) {
|
||||
$context['selection']['territory'] = $choice['territory'];
|
||||
$context['fields'] = [...Arr::except($context['fields'], array_keys(InvestmentGeography::FIELDS)), ...$choice['territory']['fields']];
|
||||
foreach ($choice['territory']['fields'] as $field => $value) $context['provenance'][$field] = Arr::only($choice['territory'], ['key','kind','id','title','version','sha256']);
|
||||
} else {
|
||||
$context['fields'] = Arr::except($context['fields'], ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location']);
|
||||
}
|
||||
$park = $choice['park'] ?? null;
|
||||
if ($park) $context['selection']['park'] = $park;
|
||||
$context['fields']['special_zone_id'] = $park['id'] ?? '';
|
||||
$context['fields']['investment_regime'] = $park['fields']['investment_regime'] ?? 'general';
|
||||
$context['opportunity_choices'] = [$choice];
|
||||
$context['requirements_assessment']['requirements'] = array_values(array_filter($context['requirements_assessment']['requirements'] ?? [], fn($r) => $r['opportunity_key'] === $key));
|
||||
$context['consumer_opportunity'] = $choice;
|
||||
$context['complements'] = array_values(array_filter($context['complements'] ?? [], fn($c) => ($c['origin']['key'] ?? null) === $key || ($c['target']['key'] ?? null) === $key || in_array(substr($c['origin']['key'] ?? '',10),array_column($choice['portfolio_origins'] ?? [],'id'),true)));
|
||||
$context['dependency_hash'] = app(InvestorContext::class)->dependencyHash(['opportunity_choices'=>[$choice], 'fields'=>Arr::except($context['fields'],['project_title','project_summary']), 'complements'=>$context['complements']]);
|
||||
return $context;
|
||||
}
|
||||
|
||||
public function bind(User $actor, string $id, array $payload, bool $required = false): array
|
||||
{
|
||||
$case = app(VirtualDesk::class)->case($actor, $id, true);
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
$scoped = $this->context($context, $payload['context_opportunity'] ?? null);
|
||||
$choice = $scoped['consumer_opportunity'] ?? null;
|
||||
abort_if($required && count($context['opportunity_choices'] ?? []) > 1 && !$choice, 422, 'Escolha a oportunidade em tratamento antes de submeter.');
|
||||
if (!$choice) return Arr::except($payload, ['context_opportunity', 'context_opportunity_snapshot']);
|
||||
// Canonical server snapshot; client text cannot establish a different origin or territory.
|
||||
$payload['context_opportunity'] = $choice['opportunity']['key'];
|
||||
$payload['context_opportunity_snapshot'] = json_encode(['context_id' => $id, 'revision' => $context['revision'], 'choice' => $choice, 'requirements' => $scoped['requirements_assessment'] ?? null], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
return $payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Preparation within the existing path; no licence, DUAT or fiscal benefit is granted. */
|
||||
final class InvestmentContextRequirements
|
||||
{
|
||||
public const VERSION = 'context-requirements-20261023';
|
||||
|
||||
public function assess(array $context): array
|
||||
{
|
||||
$rows = [];
|
||||
foreach ($context['opportunity_choices'] ?? [] as $choice) {
|
||||
$activities = $choice['activities'] ?? [];
|
||||
$key = $choice['opportunity']['key'];
|
||||
$common = ['opportunity_key' => $key, 'opportunity_title' => $choice['opportunity']['title']];
|
||||
$add = function ($code, $title, $state, $step, $authority, $documents, $basis, $url) use (&$rows, $common) {
|
||||
$rows[] = [...$common, 'code' => $code, 'title' => $title, 'state' => $state, 'step' => $step,
|
||||
'authority' => $authority, 'documents' => $documents, 'basis' => $basis, 'source_url' => $url,
|
||||
'decision' => 'Preparação; enquadramento e acto concreto conservam confirmação na etapa correspondente.'];
|
||||
};
|
||||
$add('geography', 'Localização e geolocalização', $choice['territory'] ? 'selected' : 'missing', 'S09', 'Cadastro territorial e serviços de cadastro competentes',
|
||||
['Referência administrativa confirmada', 'Planta/esboço e coordenadas quando disponíveis; não inventar polígonos'],
|
||||
'Referência territorial escolhida no dossier; não comprova disponibilidade nem direito de uso.', '/investimentos');
|
||||
$add('land', 'Acesso à terra e DUAT', 'conditional', 'S10', 'Serviços de cadastro e órgão competente para o pedido territorial concreto',
|
||||
['Fundamento do uso: DUAT, arrendamento ou situação declarada', 'Planta/esboço do local; documentação do pedido correspondente'],
|
||||
'Regulamento de Investimento, artigos 9(1)(c)–(d) e 14(1)(c)–(d). A preparação distingue DUAT e arrendamento; escolher território não atribui terra.', PrivateInvestmentPreparation::SOURCE.'#page=42');
|
||||
$add('environment', 'Enquadramento ambiental', 'conditional', 'S08', 'Autoridade de Avaliação do Impacto Ambiental; competência central/provincial conforme categorização',
|
||||
['Descrição da actividade, dimensão e localização', 'Instrumento ambiental definido pela categorização competente; acto e condições quando emitidos'],
|
||||
'Decreto 54/2015: a natureza, dimensão e localização determinam o enquadramento; a categoria não é deduzida do corredor ou do sector.', 'https://sibmoz.gov.mz/legal-framework/');
|
||||
$add('sector', 'Licenciamento sectorial', $activities ? 'declared' : 'missing', 'S08', 'BAU, IP e autoridade sectorial competente conforme a actividade',
|
||||
['Actividades efectivas e modalidade', 'Requerimento e anexos da modalidade aplicável; acto quando emitido'],
|
||||
'Identificar as actividades efectivas antes de seleccionar o procedimento. O nome Agronegócio não escolhe uma licença única.', 'https://www.bau.gov.mz/nossos-servicos/');
|
||||
foreach (['processing' => ['Licenciamento industrial', 'Decreto 22/2014'], 'trade' => ['Licenciamento comercial', 'Decreto 34/2013']] as $activity => [$title, $basis]) {
|
||||
if (in_array($activity, $activities, true)) $add($activity, $title, 'conditional', 'S08', 'BAU, IP / entidade licenciadora da modalidade',
|
||||
['Caracterização do estabelecimento e actividade', 'Documentos e regime aplicáveis, incluindo simplificado ou mera comunicação quando preenchidas as suas condições'],
|
||||
$basis.'; regimes 39/2017 e 27/2023 no catálogo oficial BAU. Dimensão e modalidade ainda devem ser especificadas; não se selecciona automaticamente o regime.', 'https://www.bau.gov.mz/legislacao/');
|
||||
}
|
||||
foreach (['water' => 'Uso de água', 'forestry' => 'Actividade florestal', 'animal' => 'Actividade pecuária', 'transport' => 'Transporte e logística'] as $activity => $title) {
|
||||
if (in_array($activity, $activities, true)) $add($activity, $title, 'undetermined', 'S08', 'Autoridade sectorial competente a identificar para a modalidade declarada',
|
||||
['Modalidade e dimensão da actividade', 'Fonte e documentação sectorial específica a associar ao dossier'],
|
||||
'Actividade declarada; a referência do lote não contém o procedimento específico. Não se considera dispensada ou autorizada.', 'https://www.apiex.gov.mz/wp-content/uploads/2024/01/Mozambique-Business-Licensing-Guide.pdf');
|
||||
}
|
||||
}
|
||||
return ['version' => self::VERSION, 'requirements' => $rows,
|
||||
'fiscal_notice' => 'Localização, corredor, cluster ou projecto âncora não activam benefícios fiscais. O simulador mantém as condições, fonte, período e âmbito próprios; condições ausentes permanecem indeterminadas.'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class InvestmentCorridorContext
|
||||
{
|
||||
public function key(Opportunity $record): ?string
|
||||
{
|
||||
$name = data_get($record->workflow_context, 'corridor_agribusiness.corridor');
|
||||
foreach (config('investment_corridors') as $key => $entry) if ($entry['name'] === $name) return $key;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Reuse Tempo's approved provincial context; never infer a district or master link. */
|
||||
public function catalogueProvinces(Opportunity $record): array
|
||||
{
|
||||
if (data_get($record->workflow_context, 'corridor_agribusiness.source_sha256') !== CorridorAgribusinessOpportunities::SOURCE_HASH) return [];
|
||||
if ($record->primary_territory_id || $record->additionalTerritories()->exists()) return [];
|
||||
$key = $this->key($record);
|
||||
return $key ? $this->provinces($key) : [];
|
||||
}
|
||||
|
||||
public function provinces(string $key): array
|
||||
{
|
||||
$entry = config('investment_corridors.'.$key);
|
||||
abort_unless(is_array($entry), 422, 'Seleccione um corredor disponível.');
|
||||
$records = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')
|
||||
->whereIn('source_code', $entry['provinces'])->get(['id', 'name', 'parent_id', 'location_type', 'source_code'])->all();
|
||||
abort_unless(count($records) === count($entry['provinces']), 503, 'Não foi possível recuperar todas as províncias deste corredor. Tente novamente.');
|
||||
return $records;
|
||||
}
|
||||
|
||||
public function compatible(string $key, ?string $territory): bool
|
||||
{
|
||||
if (!$territory) return true;
|
||||
$path = app(InvestmentGeography::class)->path($territory);
|
||||
return $path !== [] && in_array($path[0]->id, array_column($this->provinces($key), 'id'), true);
|
||||
}
|
||||
|
||||
/** Both membership in the selected area and documented public zone coverage are required. */
|
||||
public function parks(?string $key, ?string $territory): array
|
||||
{
|
||||
if (!$key || !$territory) return [];
|
||||
abort_unless($this->compatible($key, $territory), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
$selectedPath = array_column(app(InvestmentGeography::class)->path($territory), 'id');
|
||||
$candidates = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->orderBy('name')->get();
|
||||
$result = [];
|
||||
foreach ($candidates as $zone) {
|
||||
$ids = DB::table('investment_zone_locations')->where('zone_id', $zone->id)->where('validation_status', 'validated')
|
||||
->whereIn('scope_type', ['legal_scope', 'administrative', 'site'])
|
||||
->where(fn($q)=>$q->whereNull('valid_from')->orWhereDate('valid_from','<=',today()))
|
||||
->where(fn($q)=>$q->whereNull('valid_until')->orWhereDate('valid_until','>=',today()))->get(['geo_location_id','scope_type'])->all();
|
||||
if ($zone->primary_territory_id) $ids[] = (object)['geo_location_id'=>$zone->primary_territory_id,'scope_type'=>'site'];
|
||||
foreach ($ids as $link) {
|
||||
$id=$link->geo_location_id;
|
||||
if (!$this->compatible($key, $id)) continue;
|
||||
$path = array_column(app(InvestmentGeography::class)->path($id), 'id');
|
||||
if (in_array($territory, $path, true) || ($link->scope_type==='legal_scope' && in_array($id, $selectedPath, true))) {
|
||||
$result[] = $zone->only(['id', 'name', 'category', 'version_no']); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Http\Controllers\InvestmentPortfolioController;
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Multiple identified references in the existing encrypted investment context. */
|
||||
final class InvestmentOpportunityChoices
|
||||
{
|
||||
public function portfolioOrigins(array $ids, int $opportunity): array
|
||||
{
|
||||
$origins = [];
|
||||
foreach (array_unique($ids) as $id) {
|
||||
$record = InvestmentPortfolioController::visible()->addSelect('version_no')->findOrFail($id);
|
||||
$kind = null;
|
||||
if (in_array($opportunity, app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($record), true)) $kind = 'corridor';
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
|
||||
if ($record->$foreign && DB::table('opportunity_'.$relation)->where('opportunity_id', $opportunity)->where($foreign, $record->$foreign)->exists()) $kind = rtrim($relation, 's');
|
||||
}
|
||||
abort_unless($kind, 422, 'A associação escolhida não pertence a esta oportunidade.');
|
||||
$origins[] = ['id' => $record->id, 'title' => $record->title, 'kind' => $kind, 'href' => '/carteira/'.$record->id,
|
||||
'version' => $record->version_no, 'sha256' => hash('sha256', json_encode([$record->title, $record->source, $record->content], JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
return $origins;
|
||||
}
|
||||
|
||||
/** Add explicitly consulted associations without resetting saved geography or deliberate answers. */
|
||||
public function mergeEntries(array $saved, array $entries): array
|
||||
{
|
||||
foreach ($entries as $entry) {
|
||||
$index = array_search($entry['opportunity']['key'], array_column(array_column($saved, 'opportunity'), 'key'), true);
|
||||
if ($index === false) { $saved[] = $entry; continue; }
|
||||
$origins = collect([...($saved[$index]['portfolio_origins'] ?? []), ...($entry['portfolio_origins'] ?? [])])->unique('id')->values()->all();
|
||||
if ($origins) $saved[$index]['portfolio_origins'] = $origins;
|
||||
}
|
||||
return $saved;
|
||||
}
|
||||
|
||||
public function resolve(array $choices, array $previous = [], bool $pending = false): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($choices as $choice) {
|
||||
$ref = app(InvestorContext::class)->reference($choice['source']);
|
||||
abort_unless($ref['kind'] === 'opportunity', 422, 'Seleccione uma ficha de oportunidade.');
|
||||
$record = Opportunity::findOrFail($ref['id']);
|
||||
$old = collect($previous)->first(fn ($row) => $row['opportunity']['key'] === $ref['key']);
|
||||
$origins = $this->portfolioOrigins($choice['portfolio_origins'] ?? array_column($old['portfolio_origins'] ?? [], 'id'), (int) $record->id);
|
||||
$corridors = app(InvestmentCorridorContext::class);
|
||||
$corridor = $choice['corridor_key'] ?? $old['corridor_key'] ?? $corridors->key($record);
|
||||
$provinces = $corridor ? $corridors->provinces($corridor) : [];
|
||||
$documented = $record->primary_territory_id;
|
||||
$territory = array_key_exists('territory', $choice) ? $choice['territory'] : ($documented ? 'territory:'.$documented : null);
|
||||
if (!$territory && count($provinces) === 1) $territory = 'territory:'.$provinces[0]->id;
|
||||
if ($corridor && $territory) abort_unless($corridors->compatible($corridor, substr($territory, 10)), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
$previousTerritory = $old['territory']['key'] ?? null;
|
||||
$newAlternative = $documented && $territory !== 'territory:'.$documented
|
||||
&& (! $old || ($old['documented_territory_id'] ?? null) !== $documented || $territory !== $previousTerritory);
|
||||
$corridorChanged = $old && ($old['corridor_key'] ?? $corridors->key($record)) !== $corridor;
|
||||
$incompatibleOld = $corridorChanged && $previousTerritory && !$corridors->compatible($corridor, substr($previousTerritory, 10));
|
||||
if (!$pending && ($newAlternative || ($previousTerritory && $territory !== $previousTerritory && !$incompatibleOld))) {
|
||||
abort_unless(! empty($choice['confirm_location_change']) && mb_strlen(trim($choice['location_reason'] ?? '')) >= 20,
|
||||
422, 'Uma localização documentada ou já confirmada só muda por escolha explícita, com confirmação e motivo.');
|
||||
}
|
||||
$location = $territory ? app(InvestorContext::class)->reference($territory) : null;
|
||||
abort_unless($location === null || $location['kind'] === 'territory', 422);
|
||||
$parkKey = array_key_exists('park', $choice) ? $choice['park'] : ($old['park']['key'] ?? null);
|
||||
$park = $parkKey ? app(InvestorContext::class)->reference($parkKey) : null;
|
||||
if ($park) {
|
||||
$eligible = $corridor ? array_column($corridors->parks($corridor, $location['id'] ?? null), 'id') : [];
|
||||
if (!in_array($park['id'], $eligible, true)) {
|
||||
abort_if(!empty($choice['park']), 422, 'A zona ou parque não é compatível com a localização desta oportunidade.');
|
||||
$park = null;
|
||||
}
|
||||
abort_unless(!$park || $park['kind'] === 'park', 422);
|
||||
}
|
||||
$result[] = ['opportunity' => $ref, 'territory' => $location, ...($origins ? ['portfolio_origins' => $origins] : []),
|
||||
'park' => $park,
|
||||
'corridor_key' => $corridor, 'corridor_name' => $corridor ? config('investment_corridors.'.$corridor.'.name') : null,
|
||||
'allowed_provinces' => array_map(fn($p)=>(array)$p, $provinces),
|
||||
'territory_path' => $location ? array_map(fn ($node) => \Illuminate\Support\Arr::only((array) $node, ['id', 'name', 'parent_id', 'location_type']), app(InvestmentGeography::class)->path($location['id'], true)) : [],
|
||||
'activities' => $choice['activities'] ?? ($old['activities'] ?? []),
|
||||
'documented_territory_id' => $documented, 'location_reason' => $choice['location_reason'] ?? '',
|
||||
'location_state' => $location ? ($documented && $territory === 'territory:'.$documented ? 'documented' : 'investor_selected') : 'undetermined',
|
||||
'location_changed_explicitly' => $old && $territory === $previousTerritory ? (bool) ($old['location_changed_explicitly'] ?? false) : (bool) ($choice['confirm_location_change'] ?? false),
|
||||
'coverage' => data_get($record->workflow_context, 'corridor_agribusiness.corridor'),
|
||||
'source' => data_get($record->workflow_context, 'corridor_agribusiness.source'),
|
||||
'source_sha256' => data_get($record->workflow_context, 'corridor_agribusiness.source_sha256')];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -63,10 +63,13 @@ class InvestmentZones
|
||||
$path = app(InvestmentGeography::class)->selection($filters);
|
||||
if ($path !== []) {
|
||||
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
||||
$query->where(function ($matches) use ($territoryIds, $management): void {
|
||||
$ancestorIds = array_column($path, 'id');
|
||||
$query->where(function ($matches) use ($territoryIds, $ancestorIds, $management): void {
|
||||
$matches->whereIn('primary_territory_id', $territoryIds)
|
||||
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('investment_zone_locations as zl')
|
||||
->whereColumn('zl.zone_id', 'investment_zones.id')->whereIn('zl.geo_location_id', $territoryIds)
|
||||
->whereColumn('zl.zone_id', 'investment_zones.id')->whereIn('zl.scope_type', ['site', 'administrative', 'legal_scope'])
|
||||
->where(fn ($area) => $area->whereIn('zl.geo_location_id', $territoryIds)
|
||||
->orWhere(fn ($coverage) => $coverage->where('zl.scope_type', 'legal_scope')->whereIn('zl.geo_location_id', $ancestorIds)))
|
||||
->where('zl.validation_status', 'validated')->where(fn ($valid) => $valid->whereNull('zl.valid_from')->orWhereDate('zl.valid_from', '<=', today()))
|
||||
->where(fn ($valid) => $valid->whereNull('zl.valid_until')->orWhereDate('zl.valid_until', '>=', today())));
|
||||
if (! $management) {
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Services;
|
||||
use App\Models\ExistingBusiness;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Support\Arr;
|
||||
@@ -12,6 +13,7 @@ use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
/** Context belongs to the existing encrypted dossier. Sources remain read-only. */
|
||||
@@ -21,10 +23,71 @@ final class InvestorContext
|
||||
|
||||
public const SOURCE = 'investor-context';
|
||||
|
||||
public const FIELDS = ['project_title', 'project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location'];
|
||||
public const FIELDS = ['project_title', 'project_summary', 'sector_id', 'sector', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'currency', 'expected_start_date', 'fiscal_period', 'fiscal_periodicity', 'fiscal_month', 'investor_origin', 'person_type', 'entity_stage', 'tax_residency_country', 'fiscal_residency_country', 'activity_id', 'project_type', 'maturity_stage', 'special_zone_id', 'investment_regime', ...PrivateInvestmentPreparation::FIELDS];
|
||||
|
||||
public function __construct(private readonly VirtualDesk $desk) {}
|
||||
|
||||
public function draft(User $actor, string $id): ?array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id, true);
|
||||
$draft = $this->desk->decode($case->payload)['investor_path']['context_drafts'][(string)$actor->id] ?? null;
|
||||
return $draft ? [...$draft, 'needs_review' => (int)$draft['version'] !== (int)$case->version] : null;
|
||||
}
|
||||
|
||||
public function saveDraft(User $actor, string $id, array $input): array
|
||||
{
|
||||
$case=$this->desk->case($actor,$id,true);
|
||||
abort_if($case->closed_at,409);
|
||||
$sequence = (int)($input['draft_sequence'] ?? 0);
|
||||
$entrySources=Validator::make($input,['entry_sources'=>'sometimes|array|max:200','entry_sources.*'=>'string|max:100'])->validate()['entry_sources']??[];
|
||||
unset($input['draft_sequence'],$input['entry_sources']);
|
||||
abort_unless($sequence > 0, 422);
|
||||
$data = $this->input($input);
|
||||
if (isset($data['complements'])) app(InvestmentComplements::class)->resolve($data['complements'], $this->state($case)['complements'] ?? []);
|
||||
foreach ($data['selection'] as $slot=>$key) {
|
||||
if (!$key) continue;
|
||||
$ref=$this->reference($key);
|
||||
abort_unless(in_array($ref['kind'],$slot==='opportunity'?['opportunity','business']:[$slot],true),422,'Referência incompatível com a escolha.');
|
||||
}
|
||||
foreach ($data['opportunity_choices'] ?? [] as $choice) {
|
||||
$ref = $this->reference($choice['source']);
|
||||
abort_unless($ref['kind'] === 'opportunity', 422);
|
||||
$record = Opportunity::findOrFail($ref['id']);
|
||||
app(InvestmentOpportunityChoices::class)->portfolioOrigins($choice['portfolio_origins'] ?? [], (int) $record->id);
|
||||
$key = $choice['corridor_key'] ?? app(InvestmentCorridorContext::class)->key($record);
|
||||
if (!empty($choice['territory'])) {
|
||||
$location = $this->reference($choice['territory']);
|
||||
abort_unless($location['kind'] === 'territory', 422);
|
||||
if ($key) abort_unless(app(InvestmentCorridorContext::class)->compatible($key, $location['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
}
|
||||
}
|
||||
if (isset($data['opportunity_choices'])) app(InvestmentOpportunityChoices::class)->resolve($data['opportunity_choices'], $this->state($case)['opportunity_choices'] ?? [], true);
|
||||
if (!empty($data['selection']['park'])) {
|
||||
$first=$data['opportunity_choices'][0] ?? null;
|
||||
$source=$first['source'] ?? $data['selection']['opportunity'] ?? null;
|
||||
if ($source && str_starts_with($source,'opportunity:')) {
|
||||
$key=$first['corridor_key'] ?? app(InvestmentCorridorContext::class)->key(Opportunity::findOrFail(substr($source,12)));
|
||||
if ($key) {
|
||||
$territory=$first['territory'] ?? $data['selection']['territory'] ?? null;
|
||||
$ids=app(InvestmentCorridorContext::class)->provinces($key);
|
||||
$territory=$territory ? substr($territory,10) : (count($ids)===1?$ids[0]->id:null);
|
||||
$park=$this->reference($data['selection']['park']);
|
||||
abort_unless($park['kind']==='park' && in_array($park['id'],array_column(app(InvestmentCorridorContext::class)->parks($key,$territory),'id'),true),422,'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
}
|
||||
}
|
||||
}
|
||||
return DB::transaction(function () use ($actor, $id, $data, $sequence, $entrySources) {
|
||||
$case = $this->desk->case($actor, $id, true, true);
|
||||
abort_if($case->closed_at || (int)$case->version !== (int)$data['version'], 409, 'O dossier mudou. Recupere os dados antes de continuar.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$previous = $payload['investor_path']['context_drafts'][(string)$actor->id] ?? [];
|
||||
abort_if(($previous['draft_sequence'] ?? 0) > $sequence, 409, 'Existe um rascunho mais recente. Recupere o dossier antes de continuar.');
|
||||
$payload['investor_path']['context_drafts'][(string)$actor->id] = [...$data, 'draft_sequence' => $sequence, 'entry_sources'=>array_values(array_unique([...($previous['entry_sources']??[]),...$entrySources]))];
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload)]);
|
||||
return ['saved' => true];
|
||||
});
|
||||
}
|
||||
|
||||
public function installed(): bool
|
||||
{
|
||||
return Schema::hasTable('investor_navigation_preferences');
|
||||
@@ -34,12 +97,33 @@ final class InvestorContext
|
||||
{
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
|
||||
return $payload['investor_path']['context'] ?? ['revision' => 0, 'selection' => [],
|
||||
$context = $payload['investor_path']['context'] ?? ['revision' => 0, 'selection' => [],
|
||||
'fields' => ['project_title' => $case->title], 'provenance' => ['project_title' => ['kind' => 'dossier', 'id' => $case->id, 'version' => $case->version]], 'review_steps' => []];
|
||||
// Explicit dossier anchor only: never the account's most recent simulation or another owner's draft.
|
||||
if (($case->simulation_id ?? null) && request()->user()?->id === (int) $case->user_id) {
|
||||
$draft = SimulationFormDraft::whereKey($case->simulation_id)->where('owner_user_id', $case->user_id)->whereNull('deleted_at')->first();
|
||||
if ($draft) {
|
||||
$values = [...SimulationFormDraft::decryptSnapshot($draft->personal_snapshot), ...SimulationFormDraft::decryptSnapshot($draft->economic_snapshot)];
|
||||
foreach (Arr::only($values, self::FIELDS) as $key => $value) {
|
||||
if (is_scalar($value) && (string) $value !== '' && (! array_key_exists($key, $context['fields']) || ($context['provenance'][$key]['kind'] ?? null) === 'linked_simulation')) {
|
||||
$context['fields'][$key] = (string) $value;
|
||||
$context['provenance'][$key] = ['kind' => 'linked_simulation', 'id' => $draft->id, 'version' => $draft->version_no, 'sha256' => $draft->snapshot_sha256];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!empty($context['opportunity_choices']) && !array_key_exists('park', $context['opportunity_choices'][0])) $context['opportunity_choices'][0]['park'] = $context['selection']['park'] ?? null;
|
||||
$zone = $context['selection']['park'] ?? null;
|
||||
$context['fields']['investment_regime'] = $zone['fields']['investment_regime'] ?? 'general';
|
||||
$context['fields']['special_zone_id'] = $zone['id'] ?? '';
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
public function dependencyHash(array $selection): string
|
||||
{
|
||||
unset($selection['portfolio'], $selection['selection']['portfolio']);
|
||||
if (isset($selection['opportunity_choices'])) $selection['opportunity_choices'] = array_map(fn($choice)=>Arr::except($choice,['portfolio_origins']),$selection['opportunity_choices']);
|
||||
return hash('sha256', json_encode(Arr::sortRecursive($selection), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
@@ -53,17 +137,20 @@ final class InvestorContext
|
||||
$documents = [];
|
||||
$visibility = 'public';
|
||||
$state = null;
|
||||
$zoneAnalysis = null;
|
||||
if ($kind === 'opportunity') {
|
||||
abort_unless(ctype_digit($id), 422, 'Identificador de oportunidade inválido.');
|
||||
$o = Opportunity::with('sector')->findOrFail((int) $id);
|
||||
$published = Opportunity::published()->whereKey($o->id)->exists();
|
||||
if (!$published) {
|
||||
if (! $published) {
|
||||
abort_unless(request()->user() && $o->status !== 'archived' && app(PortalProfileAccess::class)->canView(request()->user(), $o), 404, 'Ficha privada indisponível neste âmbito.');
|
||||
$visibility = 'private';
|
||||
$state = app(PortalProfileAccess::class)->state($o);
|
||||
}
|
||||
if (request()->user()) $documents = app(OpportunityLibrarySupport::class)->snapshot(request()->user(), $o);
|
||||
$draft = !$published ? app(OpportunityManagement::class)->values($o) : [];
|
||||
if (request()->user()) {
|
||||
$documents = app(OpportunityLibrarySupport::class)->snapshot(request()->user(), $o);
|
||||
}
|
||||
$draft = ! $published ? app(OpportunityManagement::class)->values($o) : [];
|
||||
$title = $draft['canonical']['official_title'] ?? $o->title;
|
||||
$href = $published ? '/oportunidades/'.$o->slug : '/minhas-oportunidades/'.$o->id.'/view';
|
||||
$version = $o->management_version;
|
||||
@@ -72,6 +159,8 @@ final class InvestorContext
|
||||
$fields['sector_id'] = (string) $o->sector_id;
|
||||
$fields['sector'] = $o->sector->name;
|
||||
}
|
||||
$proactive = $published ? app(ProactiveInvestment::class)->publicData($o) : ($draft['proactive'] ?? null);
|
||||
if ($proactive) $zoneAnalysis = ['proactive' => $proactive, 'source_key' => $key, 'source_version' => $version, 'private_source' => !$published];
|
||||
// Text labels do not establish a canonical territorial correspondence.
|
||||
if ($o->province) {
|
||||
$fields['province'] = $o->province;
|
||||
@@ -82,6 +171,18 @@ final class InvestorContext
|
||||
if ($o->primary_territory_id) {
|
||||
$fields = [...$fields, ...$this->territoryFields($o->primary_territory_id)];
|
||||
}
|
||||
} elseif ($kind === 'portfolio') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$dossier = \App\Http\Controllers\InvestmentPortfolioController::visible()->findOrFail($id);
|
||||
$title = $dossier->title;
|
||||
$href = '/carteira/'.$id;
|
||||
// Documentary coverage is not the investor's chosen implantation.
|
||||
$version = DB::table('investment_dossiers')->where('id', $id)->value('version_no');
|
||||
$fields = ['project_title' => $title, 'project_summary' => $dossier->content['description'] ?? $dossier->content['focus'] ?? ''];
|
||||
$state = 'documented_origin';
|
||||
$zoneAnalysis = ['source' => $dossier->source, 'documented_sector' => $dossier->content['sector'] ?? null,
|
||||
'documented_location' => $dossier->content['location'] ?? $dossier->content['region'] ?? null,
|
||||
'geography' => app(InvestmentRelations::class)->dossier($dossier), 'available_opportunity' => false];
|
||||
} elseif ($kind === 'business') {
|
||||
abort_unless(config('existing-business.enabled') && Str::isUuid($id), 404);
|
||||
$o = ExistingBusiness::published()->with('sector')->findOrFail($id);
|
||||
@@ -122,19 +223,28 @@ final class InvestorContext
|
||||
$fields = $this->territoryFields($id);
|
||||
} elseif ($kind === 'park') {
|
||||
abort_unless(Str::isUuid($id), 422);
|
||||
$p = app(InvestmentZones::class)->visible()->where('category', 'industrial_park')->findOrFail($id);
|
||||
$p = app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->findOrFail($id);
|
||||
$title = $p->name;
|
||||
$fields = ['special_zone_id' => (string) $p->id, 'investment_regime' => (string) $p->category];
|
||||
$version = $p->version_no;
|
||||
$zoneAnalysis = ['conditions' => app(InvestmentZoneOperationalDetails::class)->publicData($p)['conditions'] ?? [],
|
||||
'source' => $p->legal_source_id ? DB::table('investment_legal_sources')->where('id', $p->legal_source_id)->first(['title', 'url', 'diploma', 'article', 'valid_from', 'valid_until']) : null,
|
||||
'recognition' => 'undetermined', 'executable_benefit' => false];
|
||||
$href = '/zonas/'.$id;
|
||||
if ($p->primary_territory_id) {
|
||||
$fields = $this->territoryFields($p->primary_territory_id);
|
||||
$fields = [...$fields, ...$this->territoryFields($p->primary_territory_id)];
|
||||
}
|
||||
} else {
|
||||
abort(422, 'Tipo de referência inválido.');
|
||||
}
|
||||
$fields = array_filter($fields, fn ($v) => is_scalar($v) && trim((string) $v) !== '');
|
||||
$record = ['key' => $key, 'kind' => $kind, 'id' => $id, 'title' => $title, 'version' => $version, 'href' => $href, 'fields' => $fields];
|
||||
if ($documents || $visibility === 'private') $record += ['documents' => $documents, 'visibility' => $visibility, 'state' => $state];
|
||||
if ($zoneAnalysis !== null) {
|
||||
$record['analysis'] = $zoneAnalysis;
|
||||
}
|
||||
if ($documents || $visibility === 'private') {
|
||||
$record += ['documents' => $documents, 'visibility' => $visibility, 'state' => $state];
|
||||
}
|
||||
|
||||
return [...$record, 'sha256' => hash('sha256', json_encode($record, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
@@ -170,7 +280,11 @@ final class InvestorContext
|
||||
}
|
||||
if (request()->user()) {
|
||||
$private = app(PortalProfileAccess::class)->scope(Opportunity::query(), request()->user())->where('status', '!=', 'published')->where('status', '!=', 'archived')->when($query, fn ($q) => $q->where('title', 'ilike', '%'.$query.'%'))->orderBy('title')->limit(51)->get();
|
||||
foreach ($private as $o) if (app(PortalProfileAccess::class)->canView(request()->user(), $o)) $items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title.' — preparação privada', 'kind' => 'opportunity'];
|
||||
foreach ($private as $o) {
|
||||
if (app(PortalProfileAccess::class)->canView(request()->user(), $o)) {
|
||||
$items[] = ['key' => 'opportunity:'.$o->id, 'title' => $o->title.' — preparação privada', 'kind' => 'opportunity'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (config('existing-business.enabled')) {
|
||||
foreach (ExistingBusiness::published()->when($query, fn ($q) => $q->where('public_title', 'ilike', '%'.$query.'%'))->orderBy('public_title')->limit(51)->get(['id', 'public_title']) as $o) {
|
||||
@@ -179,7 +293,7 @@ final class InvestorContext
|
||||
}
|
||||
|
||||
return ['opportunities' => $items, 'search_limited' => count($items) > 50, 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
|
||||
'parks' => app(InvestmentZones::class)->visible()->where('category', 'industrial_park')->orderBy('name')->get(['id', 'name', 'version_no'])];
|
||||
'parks' => app(InvestmentZones::class)->visible()->whereIn('category', ['industrial_park', 'zee', 'zfi'])->orderBy('name')->get(['id', 'name', 'category', 'version_no'])];
|
||||
}
|
||||
|
||||
public function current(User $actor): array
|
||||
@@ -232,10 +346,32 @@ final class InvestorContext
|
||||
|
||||
private function input(array $input): array
|
||||
{
|
||||
abort_if(array_diff(array_keys($input), ['version', 'selection', 'declarations', 'replace_fields', 'preview_hash', 'operation_key', 'confirm', '_token']), 422, 'Campo de controlo desconhecido.');
|
||||
abort_if(array_diff(array_keys($input), ['complements', 'opportunity_choices', 'version', 'selection', 'declarations', 'replace_fields', 'preview_hash', 'operation_key', 'confirm', 'document_links', '_token']), 422, 'Campo de controlo desconhecido.');
|
||||
|
||||
return Validator::make($input, ['version' => 'required|integer|min:1', 'selection' => 'present|array:opportunity,sector,territory,park',
|
||||
'selection.*' => 'nullable|string|max:100', 'declarations' => 'nullable|array:project_title,project_summary', 'declarations.project_title' => 'nullable|string|max:200', 'declarations.project_summary' => 'nullable|string|max:5000',
|
||||
abort_if(! app(PrivateInvestmentPreparation::class)->available() && (! empty($input['document_links']) || array_intersect(array_keys(is_array($input['declarations'] ?? null) ? $input['declarations'] : []), PrivateInvestmentPreparation::FIELDS)), 409, 'Esta preparação ainda não está disponível neste ambiente. As respostas foram preservadas.');
|
||||
|
||||
$inputRules = [
|
||||
'document_links' => 'sometimes|array:'.implode(',', PrivateInvestmentPreparation::DOCUMENTS),
|
||||
'document_links.*' => 'nullable|uuid',
|
||||
];
|
||||
foreach (app(PrivateInvestmentPreparation::class)->questions() as $question) {
|
||||
$inputRules['declarations.'.$question['key']] = isset($question['options']) ? ['nullable', Rule::in(array_keys($question['options']))] : ['nullable', 'regex:/^\d+(?:\.\d+)?$/D', 'numeric', 'min:0', 'max:999999999999999999'];
|
||||
}
|
||||
|
||||
return Validator::make($input, [...$inputRules,
|
||||
'complements' => 'sometimes|array|max:100', 'complements.*' => 'array:origin,code,target,territory_id',
|
||||
'complements.*.origin' => 'required|string|max:100', 'complements.*.code' => 'required|string|max:40',
|
||||
'complements.*.target' => 'nullable|string|max:100', 'complements.*.territory_id' => 'nullable|uuid',
|
||||
'opportunity_choices' => 'sometimes|array|max:100', 'opportunity_choices.*' => 'array:source,territory,location_reason,confirm_location_change,activities,corridor_key,portfolio_origins,park',
|
||||
'opportunity_choices.*.portfolio_origins' => 'sometimes|array|max:100', 'opportunity_choices.*.portfolio_origins.*' => 'uuid',
|
||||
'opportunity_choices.*.corridor_key' => ['sometimes', 'nullable', Rule::in(array_keys(config('investment_corridors')))],
|
||||
'opportunity_choices.*.activities' => 'sometimes|array', 'opportunity_choices.*.activities.*' => 'string|distinct|in:production,processing,trade,transport,water,forestry,animal',
|
||||
'opportunity_choices.*.park' => 'sometimes|nullable|string|max:100',
|
||||
'opportunity_choices.*.source' => 'required|string|distinct|max:100', 'opportunity_choices.*.territory' => 'nullable|string|max:100',
|
||||
'opportunity_choices.*.location_reason' => 'nullable|string|max:2000', 'opportunity_choices.*.confirm_location_change' => 'sometimes|boolean',
|
||||
'version' => 'required|integer|min:1', 'selection' => 'present|array:portfolio,opportunity,sector,territory,park',
|
||||
'selection.*' => 'nullable|string|max:100', 'declarations' => 'nullable|array:project_title,project_summary,currency,expected_start_date,investor_origin,person_type,entity_stage,tax_residency_country,fiscal_residency_country,project_type,maturity_stage,'.implode(',', PrivateInvestmentPreparation::FIELDS), 'declarations.project_title' => 'nullable|string|max:200', 'declarations.project_summary' => 'nullable|string|max:5000',
|
||||
'declarations.currency' => 'nullable|regex:/^[A-Z]{3}$/', 'declarations.expected_start_date' => 'nullable|date_format:Y-m-d', 'declarations.investor_origin' => 'nullable|in:national,foreign,mixed', 'declarations.person_type' => 'nullable|in:singular,collective,sole_trader,consortium', 'declarations.entity_stage' => 'nullable|in:existing,being_formed', 'declarations.tax_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.fiscal_residency_country' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'declarations.project_type' => 'nullable|string|max:100', 'declarations.maturity_stage' => 'nullable|string|max:100',
|
||||
'replace_fields' => 'nullable|array', 'replace_fields.*' => 'string|in:'.implode(',', self::FIELDS)])->validate();
|
||||
}
|
||||
|
||||
@@ -247,7 +383,41 @@ final class InvestorContext
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'O dossier mudou; recupere a versão atual.');
|
||||
app(InvestorPath::class)->view($actor, $id);
|
||||
$old = $this->state($case);
|
||||
$complements = array_key_exists('complements', $data) ? app(InvestmentComplements::class)->resolve($data['complements'], $old['complements'] ?? []) : ($old['complements'] ?? []);
|
||||
$links = $old['preparation_documents'] ?? [];
|
||||
foreach ($data['document_links'] ?? [] as $key => $document) {
|
||||
if ($document) {
|
||||
abort_unless(DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.id', $document)->whereNull('d.deleted_at')->exists(), 422, 'Seleccione um documento já associado a este dossier; os dados anteriores foram preservados.');
|
||||
$links[$key] = $document;
|
||||
} else {
|
||||
unset($links[$key]);
|
||||
}
|
||||
}
|
||||
$choices = $old['opportunity_choices'] ?? [];
|
||||
if (! array_key_exists('opportunity_choices', $data) && array_key_exists('territory', $data['selection'])) {
|
||||
$source = $data['selection']['opportunity'] ?? ($old['selection']['opportunity']['key'] ?? null);
|
||||
if ($source && str_starts_with($source, 'opportunity:')) {
|
||||
$documented = Opportunity::findOrFail(substr($source, 12))->primary_territory_id;
|
||||
abort_if($documented && $data['selection']['territory'] !== 'territory:'.$documented, 422,
|
||||
'Confirme a alternativa territorial por ficha e indique o motivo; a localização documentada foi preservada.');
|
||||
}
|
||||
}
|
||||
if (array_key_exists('opportunity_choices', $data)) {
|
||||
$choices = app(InvestmentOpportunityChoices::class)->resolve($data['opportunity_choices'], $choices);
|
||||
$data['selection']['opportunity'] = $choices[0]['opportunity']['key'] ?? null;
|
||||
// Shared fields concern the first identified opportunity; other sites remain separate.
|
||||
$data['selection']['territory'] = $choices[0]['territory']['key'] ?? null;
|
||||
if (array_key_exists('park', $data['opportunity_choices'][0] ?? [])) $data['selection']['park'] = $choices[0]['park']['key'] ?? null;
|
||||
} elseif (array_key_exists('opportunity', $data['selection']) && $choices !== []) {
|
||||
abort(422, 'Actualize a selecção identificada de oportunidades; não substitua silenciosamente o conjunto por uma ficha.');
|
||||
}
|
||||
$selection = $old['selection'];
|
||||
foreach ($complements as $complement) {
|
||||
if (($complement['availability'] ?? '') === 'review_required') continue;
|
||||
foreach ([$complement['origin']['key'], $complement['target']['key'] ?? ''] as $key) {
|
||||
if (str_starts_with($key, 'opportunity:')) abort_unless(in_array($key, array_column(array_column($choices, 'opportunity'), 'key'), true), 422, 'Conserve a oportunidade escolhida ou retire explicitamente a sua relação complementar.');
|
||||
}
|
||||
}
|
||||
foreach ($data['selection'] as $slot => $key) {
|
||||
if ($key === null || $key === '') {
|
||||
unset($selection[$slot]);
|
||||
@@ -259,6 +429,16 @@ final class InvestorContext
|
||||
abort_unless(in_array($ref['kind'], $expected, true), 422, 'Referência incompatível com a dimensão.');
|
||||
$selection[$slot] = $ref;
|
||||
}
|
||||
$corridor = $choices[0]['corridor_key'] ?? (isset($selection['opportunity']) && $selection['opportunity']['kind'] === 'opportunity'
|
||||
? app(InvestmentCorridorContext::class)->key(Opportunity::findOrFail($selection['opportunity']['id'])) : null);
|
||||
if ($corridor && isset($selection['territory'])) abort_unless(app(InvestmentCorridorContext::class)->compatible($corridor, $selection['territory']['id']), 422, 'A localização não pertence ao corredor escolhido.');
|
||||
if ($corridor && isset($selection['park'])) {
|
||||
$eligible = array_column(app(InvestmentCorridorContext::class)->parks($corridor, $selection['territory']['id'] ?? null), 'id');
|
||||
if (!in_array($selection['park']['id'], $eligible, true)) {
|
||||
abort_if(!empty($data['selection']['park']), 422, 'A zona ou parque não tem enquadramento compatível documentado nesta localização.');
|
||||
unset($selection['park']);
|
||||
}
|
||||
}
|
||||
// A new opportunity may propose its explicitly stored sector; it never matches names.
|
||||
if (isset($data['selection']['opportunity']) && ! array_key_exists('sector', $data['selection']) && isset($selection['opportunity']['fields']['sector_id'])) {
|
||||
if (Sector::where('is_active', true)->whereKey($selection['opportunity']['fields']['sector_id'])->exists()) {
|
||||
@@ -267,7 +447,7 @@ final class InvestorContext
|
||||
}
|
||||
$proposed = [];
|
||||
$origins = [];
|
||||
foreach (['opportunity', 'sector', 'park', 'territory'] as $slot) {
|
||||
foreach (['portfolio', 'opportunity', 'sector', 'park', 'territory'] as $slot) {
|
||||
if (in_array($slot, ['park', 'territory'], true) && array_intersect(array_keys($selection[$slot]['fields'] ?? []), array_keys(InvestmentGeography::FIELDS))) {
|
||||
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location'] as $key) {
|
||||
unset($proposed[$key],$origins[$key]);
|
||||
@@ -299,30 +479,65 @@ final class InvestorContext
|
||||
}
|
||||
// Remove inherited subordinate geography only when its source was actually replaced.
|
||||
foreach ($fields as $key => $value) {
|
||||
if (! array_key_exists($key, $proposed) && in_array($key, ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'sector_id', 'sector'], true) && isset($provenance[$key]['key'])) {
|
||||
if (! array_key_exists($key, $proposed) && in_array($key, ['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'location', 'sector_id', 'sector', 'special_zone_id', 'investment_regime'], true) && isset($provenance[$key]['key'])) {
|
||||
unset($fields[$key],$provenance[$key]);
|
||||
}
|
||||
}
|
||||
if ($corridor) {
|
||||
foreach (['province_id','district_id','admin_post_id','locality_id','province','district','location'] as $key) {
|
||||
if (isset($selection['territory']['fields'][$key])) {
|
||||
$fields[$key]=(string)$selection['territory']['fields'][$key];
|
||||
$provenance[$key]=Arr::except($selection['territory'],['fields']);
|
||||
} else unset($fields[$key],$provenance[$key]);
|
||||
}
|
||||
$fields['special_zone_id']=$selection['park']['id']??'';
|
||||
$fields['investment_regime']=$selection['park']['fields']['investment_regime']??'general';
|
||||
}
|
||||
$replaced = [];
|
||||
foreach (array_unique([...array_keys($old['fields']), ...array_keys($fields)]) as $key) {
|
||||
if (($old['fields'][$key] ?? null) !== ($fields[$key] ?? null)) {
|
||||
$replaced[] = ['field' => $key, 'before' => $old['fields'][$key] ?? null, 'after' => $fields[$key] ?? null];
|
||||
}
|
||||
}
|
||||
foreach (['opportunity', 'sector', 'territory', 'park'] as $slot) {
|
||||
foreach (['portfolio', 'opportunity', 'sector', 'territory', 'park'] as $slot) {
|
||||
if (($old['selection'][$slot] ?? null) !== ($selection[$slot] ?? null)) {
|
||||
$changed[] = $slot;
|
||||
}
|
||||
}
|
||||
$dependencyChanged = $this->dependencyHash($old['selection']) !== $this->dependencyHash($selection);
|
||||
$changedFields = array_column($replaced, 'field');
|
||||
if ($complements !== ($old['complements'] ?? [])) $changed[] = 'complements';
|
||||
$choicesChanged = $choices !== ($old['opportunity_choices'] ?? []);
|
||||
$choiceInputsChanged = array_map(fn($c)=>Arr::except($c,['portfolio_origins']),$choices) !== array_map(fn($c)=>Arr::except($c,['portfolio_origins']),$old['opportunity_choices']??[]);
|
||||
if ($choiceInputsChanged) $changed = array_values(array_unique([...$changed, 'opportunity', 'territory']));
|
||||
elseif ($choicesChanged) $changed[] = 'portfolio_origins';
|
||||
$conditionsChanged = (bool) array_intersect($changedFields, array_diff(self::FIELDS, ['project_title', 'project_summary']));
|
||||
$dependencyChanged = $choiceInputsChanged || in_array('complements', $changed, true) || $this->dependencyHash($old['selection']) !== $this->dependencyHash($selection) || $conditionsChanged;
|
||||
$privateConditionsChanged = (bool) array_intersect($changedFields, PrivateInvestmentPreparation::FIELDS);
|
||||
$calculationInputsChanged = $choiceInputsChanged || $this->dependencyHash($old['selection']) !== $this->dependencyHash($selection) || (bool) array_intersect($changedFields, array_diff(self::FIELDS, ['project_title', 'project_summary', ...array_diff(PrivateInvestmentPreparation::FIELDS, ['total_investment', 'area_required', 'area_unit'])]));
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$results = $payload['investor_path']['results'] ?? [];
|
||||
$requests = DB::table('desk_requests')->where('case_id', $id)->orderBy('id')->get(['id', 'status', 'protocol', 'version'])->all();
|
||||
$steps = $dependencyChanged ? array_values(array_unique([...(array_intersect($changed, ['opportunity', 'sector']) ? ['S02', 'S03', 'S04', 'S08', 'S12', 'S13', 'S14', 'S15', 'S17'] : []), ...(array_intersect($changed, ['territory', 'park']) ? ['S08', 'S09', 'S10', 'S11', 'S17'] : [])])) : [];
|
||||
$plan = ['case_id' => $id, 'version' => (int) $case->version, 'revision' => (int) $old['revision'], 'selection' => $selection, 'fields' => $fields, 'provenance' => $provenance,
|
||||
'updated' => $replaced, 'maintained' => $kept, 'changed_dimensions' => $changed, 'dependent_results' => (int) $case->user_id === $actor->id && $dependencyChanged ? array_map(fn ($r) => ['id' => $r['id'], 'engine' => $r['engine']], $results) : [],
|
||||
'requests' => $requests, 'review_steps' => $steps, 'dependency_changed' => $dependencyChanged, 'documents_preserved' => DB::table('desk_documents')->where('case_id', $id)->count(),
|
||||
if (array_intersect($changedFields, array_diff(self::FIELDS, ['project_title', 'project_summary', ...PrivateInvestmentPreparation::FIELDS]))) {
|
||||
$steps = array_values(array_unique([...$steps, 'S02', 'S03', 'S08', 'S12', 'S13', 'S17']));
|
||||
}
|
||||
if ($privateConditionsChanged) {
|
||||
$steps = array_values(array_unique([...$steps, 'S02', 'S05', 'S06', 'S07']));
|
||||
}
|
||||
if (in_array('complements', $changed, true)) $steps = array_values(array_unique([...$steps, 'S02', 'S08']));
|
||||
$privatePreparation = null;
|
||||
if (app(PrivateInvestmentPreparation::class)->available()) {
|
||||
$docs = $this->preparationDocuments($id);
|
||||
$beforePreparation = app(PrivateInvestmentPreparation::class)->assess($old, $docs);
|
||||
$afterPreparation = app(PrivateInvestmentPreparation::class)->assess(['fields' => $fields, 'selection' => $selection, 'preparation_documents' => $links], $docs);
|
||||
$privatePreparation = ['before' => $beforePreparation, 'after' => $afterPreparation];
|
||||
}
|
||||
$plan = ['complements' => $complements, 'opportunity_choices' => $choices, 'case_id' => $id, 'version' => (int) $case->version, 'revision' => (int) $old['revision'], 'selection' => $selection, 'fields' => $fields, 'provenance' => $provenance,
|
||||
'preparation_documents' => $links, 'private_investment' => $privatePreparation,
|
||||
'updated' => $replaced, 'maintained' => $kept, 'changed_dimensions' => $changed, 'dependent_results' => (int) $case->user_id === $actor->id && $calculationInputsChanged ? array_map(fn ($r) => ['id' => $r['id'], 'engine' => $r['engine']], $results) : [],
|
||||
'requests' => $requests, 'review_steps' => $steps, 'dependency_changed' => $dependencyChanged, 'calculation_inputs_changed' => $calculationInputsChanged, 'documents_preserved' => DB::table('desk_documents')->where('case_id', $id)->count(),
|
||||
'notice' => 'Não confirma incentivos, licenças, disponibilidade de terra, reserva ou autorização. Submissões e decisões anteriores mantêm o conteúdo enviado.'];
|
||||
$plan['requirements_assessment'] = app(InvestmentContextRequirements::class)->assess(['opportunity_choices' => $choices, 'fields' => $fields]);
|
||||
$hash = hash_hmac('sha256', json_encode(Arr::sortRecursive([$actor->id, $data, $plan]), JSON_THROW_ON_ERROR), config('app.key'));
|
||||
|
||||
return [...$plan, 'preview_hash' => $hash];
|
||||
@@ -349,7 +564,7 @@ final class InvestorContext
|
||||
$before = $this->state($case);
|
||||
$plan = $this->preview($actor, $id, $input);
|
||||
abort_unless(hash_equals($plan['preview_hash'], $control['preview_hash']), 409, 'O dossier ou uma fonte mudou desde a prévia; compare novamente.');
|
||||
if (! $plan['changed_dimensions'] && ! $plan['updated'] && empty($input['declarations']) && empty($input['replace_fields'])) {
|
||||
if (! $plan['changed_dimensions'] && ! $plan['updated'] && empty($input['declarations']) && empty($input['replace_fields']) && empty($input['document_links'])) {
|
||||
$result = ['case_id' => $id, 'version' => (int) $case->version, 'revision' => $before['revision'], 'changed' => false, 'replayed' => false];
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'desk_cases', 'entity_id' => $id, 'actor_user_id' => $actor->id, 'correlation_id' => $control['operation_key'], 'action' => 'context_unchanged', 'data_classification' => 'restricted', 'after_data' => json_encode(['case_id' => $id, 'request_hash' => $requestHash, 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
@@ -361,14 +576,17 @@ final class InvestorContext
|
||||
foreach ($plan['review_steps'] as $step) {
|
||||
$review[$step] = ['revision' => $revision, 'reason' => 'O contexto mudou; reveja os pressupostos e a evidência aplicável.'];
|
||||
}
|
||||
$context = ['revision' => $revision, 'selection' => $plan['selection'], 'fields' => $plan['fields'], 'provenance' => $plan['provenance'], 'review_steps' => $review,
|
||||
'dependency_hash' => $this->dependencyHash($plan['selection']), 'updated_at' => now()->toIso8601String(), 'updated_by' => $actor->id];
|
||||
if ($plan['dependency_changed']) {
|
||||
$context = ['opportunity_choices' => $plan['opportunity_choices'], 'preparation_documents' => $plan['preparation_documents'], 'preparation_snapshot' => $plan['private_investment']['after'] ?? $before['preparation_snapshot'] ?? null, 'revision' => $revision, 'selection' => $plan['selection'], 'fields' => $plan['fields'], 'provenance' => $plan['provenance'], 'review_steps' => $review,
|
||||
'dependency_hash' => $this->dependencyHash([...($plan['opportunity_choices'] !== [] ? ['opportunity_choices' => $plan['opportunity_choices']] : []), ...($plan['complements'] ? ['complements' => $plan['complements']] : []), 'selection' => $plan['selection'], 'fields' => Arr::except($plan['fields'], ['project_title', 'project_summary'])]), 'updated_at' => now()->toIso8601String(), 'updated_by' => $actor->id];
|
||||
$context['requirements_assessment'] = $plan['requirements_assessment'];
|
||||
$context['complements'] = $plan['complements'];
|
||||
if ($plan['calculation_inputs_changed']) {
|
||||
foreach ($payload['investor_path']['results'] ?? [] as $i => $r) {
|
||||
$payload['investor_path']['results'][$i] = [...$r, 'context_state' => 'review_required', 'context_invalidated_revision' => $revision, 'context_invalidated_at' => now()->toIso8601String()];
|
||||
}
|
||||
}
|
||||
$payload['investor_path']['context'] = $context;
|
||||
unset($payload['investor_path']['context_drafts'][(string)$actor->id]);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'title' => $context['fields']['project_title'] ?? $case->title, 'version' => $case->version + 1, 'updated_at' => now()]);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'investment_context_changed', ['before' => $before, 'after' => $context, 'affected_result_ids' => array_column($plan['dependent_results'], 'id'), 'preserved_request_ids' => array_column($plan['requests'], 'id')]);
|
||||
$result = ['case_id' => $id, 'version' => (int) $case->version + 1, 'revision' => $revision, 'replayed' => false];
|
||||
@@ -378,12 +596,15 @@ final class InvestorContext
|
||||
}, 3);
|
||||
}
|
||||
|
||||
public function view(User $actor, string $id): array
|
||||
public function view(User $actor, string $id, ?string $opportunity = null): array
|
||||
{
|
||||
$case = $this->desk->case($actor, $id);
|
||||
abort_unless($this->desk->owns($actor, $case, false) || $actor->can('manage-portal'), 403);
|
||||
$ctx = $this->state($case);
|
||||
$path = app(InvestorPath::class)->view($actor, $id);
|
||||
$ctx['land_preparation'] = $this->landPreparation($case, $opportunity);
|
||||
$path = app(InvestorPath::class)->view($actor, $id, $opportunity);
|
||||
$ctx['path_applicability'] = ['definition_id' => $path['definition_id'], 'definition_version' => $path['definition_version'], 'source_sha256' => $path['source_sha256'],
|
||||
'steps' => array_values(array_map(fn ($step) => Arr::only($step, ['code', 'title', 'applicability', 'reason', 'state', 'context_review_required']), array_filter($path['steps'], fn ($step) => ! empty($step['branch']))))];
|
||||
|
||||
$simulatorRevision = null;
|
||||
if ((int) $case->user_id === $actor->id && $case->simulation_id) {
|
||||
@@ -396,18 +617,79 @@ final class InvestorContext
|
||||
}
|
||||
}
|
||||
|
||||
return ['simulator_context_revision' => $simulatorRevision, 'case' => $path['case'], 'context' => $ctx, 'steps' => array_map(fn ($s) => Arr::only($s, ['code', 'title', 'state', 'context_review_required']), $path['steps']),
|
||||
$preparation = app(PrivateInvestmentPreparation::class)->available() ? app(PrivateInvestmentPreparation::class)->assess(app(InvestmentConsumerScope::class)->context($ctx, $opportunity), $this->preparationDocuments($id)) : null;
|
||||
$ctx['preparation_assessment'] = $preparation;
|
||||
|
||||
$prefill = $this->prefill($ctx, $opportunity);
|
||||
$saved = $this->desk->decode($case->payload);
|
||||
if (!empty($saved['reuse_consent'])) {
|
||||
$contacts = array_filter(['email' => $saved['email'] ?? null, 'phone' => $saved['profile']['phone'] ?? null], fn($v) => is_string($v) && $v !== '');
|
||||
$prefill['simulator'] = [...$contacts, ...$prefill['simulator']];
|
||||
$prefill['land'] = [...$contacts, ...(!empty($saved['name']) ? ['full_name' => $saved['name']] : []), ...$prefill['land']];
|
||||
}
|
||||
return ['private_investment' => $preparation, 'preparation_documents' => $this->preparationDocuments($id), 'simulator_context_revision' => $simulatorRevision, 'case' => $path['case'], 'context' => $ctx, 'steps' => array_map(fn ($s) => Arr::only($s, ['code', 'title', 'state', 'context_review_required']), $path['steps']),
|
||||
'can_write' => $path['canWrite'], 'next' => $path['next'], 'results' => $path['results'], 'requests' => $path['requests'],
|
||||
'prefill' => $this->prefill($ctx), 'notice' => 'A seleção apoia a preparação e não confirma benefícios, licenças, direitos ou disponibilidade.'];
|
||||
'prefill' => $prefill, 'notice' => 'A seleção apoia a preparação e não confirma benefícios, licenças, direitos ou disponibilidade.'];
|
||||
}
|
||||
|
||||
public function prefill(array $ctx): array
|
||||
public function preparationDocuments(string $id): array
|
||||
{
|
||||
$f = $ctx['fields'];
|
||||
$sim = Arr::only($f, ['project_title', 'project_summary', 'sector_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id']);
|
||||
return DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->whereNull('d.deleted_at')->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.version_no', 'd.sha256'])->map(fn ($row) => (array) $row)->all();
|
||||
}
|
||||
|
||||
public function landPreparation(\stdClass $case, ?string $opportunity = null): array
|
||||
{
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$ctx = $this->state($case);
|
||||
$key = app(InvestmentConsumerScope::class)->key($ctx, $opportunity);
|
||||
$path = $payload['investor_path'] ?? [];
|
||||
$need = app(InvestmentConsumerScope::class)->facts($payload, $ctx, $key)['land_needed'];
|
||||
|
||||
return ['need' => in_array($need, ['yes', 'no'], true) ? $need : 'unknown', 'reason' => $key ? ($path['opportunity_fact_reasons'][$key]['land_needed'] ?? '') : ($path['fact_reasons']['land_needed'] ?? '')];
|
||||
}
|
||||
|
||||
public function prefill(array $ctx, ?string $opportunity = null): array
|
||||
{
|
||||
$original = $ctx;
|
||||
$ctx = app(InvestmentConsumerScope::class)->context($ctx, $opportunity);
|
||||
$f = $ctx['fields'];
|
||||
$sim = Arr::except(Arr::only($f, self::FIELDS), ['sector', 'province', 'district', 'location', ...array_diff(PrivateInvestmentPreparation::FIELDS, ['total_investment', 'area_required', 'area_unit'])]);
|
||||
// Entering this tool from an investment dossier selects the existing investment-analysis route.
|
||||
// The reconciliation preserves any purpose deliberately chosen in an existing simulator draft.
|
||||
$sim += ['journey_type' => 'investor', 'journey_type_label' => 'Avaliar o meu investimento', 'purpose' => 'simulate_only', 'purpose_label' => 'Apenas simular'];
|
||||
if (($ctx['land_preparation']['need'] ?? null) === 'yes') {
|
||||
$tenure = ['duat' => ['duat', 'DUAT'], 'lease' => ['leased', 'Arrendado']][$f['site_tenure'] ?? ''] ?? null;
|
||||
if ($tenure) [$sim['land_status'], $sim['land_status_label']] = $tenure;
|
||||
}
|
||||
// Human labels travel with the exact existing identifiers, not inferred locations.
|
||||
foreach (app(InvestmentGeography::class)->publicReferences()->whereIn('id', array_values(Arr::only($f, array_keys(InvestmentGeography::FIELDS))))->get(['id', 'name']) as $place) {
|
||||
foreach (array_keys(InvestmentGeography::FIELDS) as $key) {
|
||||
if (($f[$key] ?? null) === $place->id) $sim[$key.'_label'] = $place->name;
|
||||
}
|
||||
}
|
||||
if (! empty($f['sector_id']) && ($sector = Sector::where('is_active', true)->find($f['sector_id']))) $sim['sector_id_label'] = $sector->name;
|
||||
$zone = $ctx['selection']['park'] ?? null;
|
||||
$sim['context_applicability_snapshot'] = json_encode([
|
||||
'version' => 1, 'context_revision' => $ctx['revision'],
|
||||
'consumer_opportunity' => $ctx['consumer_opportunity']['opportunity']['key'] ?? null,
|
||||
'portfolio_origin' => $ctx['selection']['portfolio'] ?? null,
|
||||
'zone' => $zone ? Arr::only($zone, ['id', 'title', 'href', 'version', 'sha256', 'fields', 'analysis']) : null,
|
||||
'provenance' => $ctx['provenance'],
|
||||
'opportunity_choices' => $ctx['opportunity_choices'] ?? [],
|
||||
'complements' => $ctx['complements'] ?? [],
|
||||
'requirements_assessment' => $ctx['requirements_assessment'] ?? null,
|
||||
'path' => $ctx['path_applicability'] ?? null,
|
||||
'land_preparation' => $ctx['land_preparation'] ?? null,
|
||||
'field_provenance' => array_map(fn($origin) => Arr::only($origin, ['kind', 'title', 'version', 'context_revision']), $ctx['provenance'] ?? []),
|
||||
'preparation' => isset($ctx['preparation_assessment']) ? Arr::except($ctx['preparation_assessment'], ['questions']) : null,
|
||||
'fields' => Arr::only($f, ['investor_origin', 'tax_residency_country', 'entity_stage', 'currency', 'expected_start_date', 'investment_regime']),
|
||||
'notice' => 'Referências e declarações para preparação; sem reconhecimento automático de elegibilidade ou benefício.',
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
$scoped = app(InvestmentConsumerScope::class)->context($original, $opportunity);
|
||||
$f = $scoped['fields'];
|
||||
return ['simulator' => $sim, 'land' => array_filter(['project_reference' => $f['project_title'] ?? null, 'activity' => $f['sector'] ?? null, 'purpose' => $f['project_summary'] ?? null, 'parcels' => [Arr::only($f, array_keys(InvestmentGeography::FIELDS))]], fn ($v) => $v !== null),
|
||||
'desk' => array_filter(['title' => $f['project_title'] ?? null, 'territory_id' => $f['locality_id'] ?? $f['admin_post_id'] ?? $f['district_id'] ?? $f['province_id'] ?? null, 'location_source' => isset($f['province_id']) ? 'Referência consultada no contexto v'.($ctx['revision'] ?? 0).': '.($f['location'] ?? 'território identificado').'. Não confirma disponibilidade.' : null, 'description' => $f['project_summary'] ?? null, 'sector' => $f['sector'] ?? null, ...Arr::only($f, array_keys(InvestmentGeography::FIELDS))], fn ($v) => $v !== null),
|
||||
'submission' => array_filter(['sector' => $f['sector'] ?? null, 'objective' => $f['project_summary'] ?? null, 'location' => $f['location'] ?? null], fn ($v) => $v !== null)];
|
||||
'submission' => array_filter(['currency' => $f['currency'] ?? null, 'sector' => $f['sector'] ?? null, 'objective' => $f['project_summary'] ?? null, 'location' => $f['location'] ?? null], fn ($v) => $v !== null)];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ final class InvestorPath
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function view(User $actor, string $id): array
|
||||
public function view(User $actor, string $id, ?string $opportunity = null): array
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
$case = $this->desk->case($actor, $id);
|
||||
@@ -79,18 +79,26 @@ final class InvestorPath
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$path = $payload['investor_path'] ?? [];
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
$facts = $path['facts'] ?? ['land_needed' => 'unknown', 'external_funding' => 'unknown', 'viability' => 'unknown'];
|
||||
$scope = app(InvestmentConsumerScope::class);
|
||||
$opportunity = $scope->key($context, $opportunity);
|
||||
$allChoices = $context['opportunity_choices'] ?? [];
|
||||
$facts = $scope->facts($payload, $context, $opportunity);
|
||||
$factReasons = $opportunity ? ($path['opportunity_fact_reasons'][$opportunity] ?? []) : ($path['fact_reasons'] ?? []);
|
||||
$context = $scope->context($context, $opportunity);
|
||||
$records = DB::table('journey_steps')->where('journey_id', $journey->id)->whereNull('deleted_at')->get()->keyBy('step_code');
|
||||
$steps = [];
|
||||
foreach ($definition['steps'] as $step) {
|
||||
$row = $records->get($step['code']);
|
||||
abort_unless($row !== null, 409, 'Etapa em falta; reparar a instalação sem reconstruir o histórico.');
|
||||
$detail = $this->desk->decode($row->path_detail);
|
||||
if ($opportunity && (count($allChoices) > 1 || isset($detail['opportunities'][$opportunity]))) {
|
||||
$detail = $detail['opportunities'][$opportunity] ?? ['state' => 'not_started'];
|
||||
}
|
||||
$value = $step['branch'] ? ($facts[$step['branch']] ?? 'unknown') : 'yes';
|
||||
$applicable = $value === 'unknown' ? 'undetermined' : ($value === 'no' ? 'not_needed_for_preparation' : 'applicable');
|
||||
$state = $value === 'no' ? 'dispensed' : $detail['state'];
|
||||
$steps[] = [...$step, 'id' => $row->id, 'version' => $row->version_no, 'state' => $state, 'saved_state' => $detail['state'],
|
||||
'applicability' => $applicable, 'reason' => $value === 'no' ? ($path['fact_reasons'][$step['branch']] ?? '') : ($detail['reason'] ?? ''),
|
||||
'applicability' => $applicable, 'reason' => $value === 'no' ? ($factReasons[$step['branch']] ?? '') : ($detail['reason'] ?? ''),
|
||||
'detail' => $detail, 'preparation_allowed' => $value !== 'no',
|
||||
'action_gaps' => []];
|
||||
}
|
||||
@@ -136,22 +144,29 @@ final class InvestorPath
|
||||
$documents = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
|
||||
->where('l.case_id', $id)->whereNull('d.deleted_at')
|
||||
->when(! $owner && ! $manager, fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', $requests->pluck('id'))))
|
||||
->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status']);
|
||||
->get(['l.id', 'l.document_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.version_no', 'd.sha256']);
|
||||
// Only the private draft owner can receive the financial snapshot/result. Dossier access alone is insufficient.
|
||||
$results = (int) $case->user_id === $actor->id ? ($path['results'] ?? []) : [];
|
||||
$next = collect($steps)->first(fn ($step) => $step['preparation_allowed'] && ! in_array($step['state'], ['completed', 'approved', 'waiting_external', 'submitted', 'reviewing'], true));
|
||||
|
||||
$landCase = (int) $case->user_id === $actor->id
|
||||
? LandAssistanceCase::where('user_id', $actor->id)->latest('updated_at')->get()
|
||||
->first(fn ($land) => ($land->payload['investor_path_case_id'] ?? null) === $id) : null;
|
||||
->first(fn ($land) => ($land->payload['investor_path_case_id'] ?? null) === $id
|
||||
&& (!$allChoices || ($opportunity && ($land->payload['context_opportunity'] ?? null) === $opportunity))) : null;
|
||||
|
||||
return ['case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
|
||||
$preparation = ($owner || $manager) && app(PrivateInvestmentPreparation::class)->available() ? app(PrivateInvestmentPreparation::class)->assess($context, $documents->map(fn ($d) => (array) $d)->all()) : null;
|
||||
if ($preparation && $preparation['enabled']) {
|
||||
$next = ['code' => 'S06', 'title' => $preparation['next'], 'action' => 'Preparar', 'href' => '/investimentos/'.$id.'/contexto/editar#preparation-questions'];
|
||||
}
|
||||
|
||||
return ['private_investment' => $preparation, 'case' => ['id' => $id, 'title' => $case->title, 'version' => $case->version, 'closed' => $case->closed_at !== null],
|
||||
'journey_id' => $journey->id, 'definition_id' => $version->id, 'definition_version' => $version->version_no, 'source_sha256' => $definition['source_sha256'],
|
||||
'phases' => $definition['phases'], 'steps' => $steps, 'facts' => $facts, 'fact_reasons' => $path['fact_reasons'] ?? [],
|
||||
'phases' => $definition['phases'], 'steps' => $steps, 'facts' => $facts, 'fact_reasons' => $factReasons,
|
||||
'context_opportunity' => $opportunity, 'opportunity_options' => $allChoices,
|
||||
'fintech' => ($owner || $manager) && (isset($path['fintech']) || collect($path['sector_contexts'] ?? [])->contains(fn ($s) => in_array($s['slug'], ['fintech', 'tecnologias-de-informacao', 'mercado-financeiro'], true)) || collect($path['content_sources'] ?? [])->contains('return_href', '/tech-fintech')) ? app(FintechInvestment::class)->view($payload, $steps) : null,
|
||||
'canWrite' => $owner && ! $case->closed_at, 'canReview' => $manager && (int) $case->user_id !== $actor->id && ! $case->closed_at,
|
||||
'next' => $next ? ['code' => $next['code'], 'title' => $next['title'], 'action' => 'Preparar', 'href' => '#'.$next['code']] : null,
|
||||
'investment_context' => ($owner || $manager) ? $context : null,
|
||||
'next' => $next ? ['code' => $next['code'], 'title' => $next['title'], 'action' => 'Preparar', 'href' => $next['href'] ?? '#'.$next['code']] : null,
|
||||
'investment_context' => ($owner || $manager) ? [...$context, 'opportunity_choices' => $opportunity ? $context['opportunity_choices'] : $allChoices] : null,
|
||||
'results' => $results, 'requests' => $requests, 'documents' => $documents,
|
||||
'zone_contexts' => ($owner || $manager) ? ($path['zone_contexts'] ?? []) : [],
|
||||
'sector_contexts' => ($owner || $manager) ? ($path['sector_contexts'] ?? []) : [],
|
||||
@@ -162,25 +177,31 @@ final class InvestorPath
|
||||
->get(['id', 'title', 'status', 'version_no', 'due_at', 'assignee_user_id']),
|
||||
'services' => DB::table('desk_service_versions')->where('status', 'published')->orderByDesc('version')->get(['id', 'code', 'definition'])
|
||||
->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title']]),
|
||||
'tools' => ['simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '') : null,
|
||||
'desk' => '/balcao-virtual/dossiers/'.$id, 'guidance' => '/balcao-virtual/dossiers/'.$id.'/orientacao',
|
||||
'tools' => ['simulator' => (int) $case->user_id === $actor->id ? '/simulador-fiscal?context='.$id.($case->simulation_id ? '&draft='.$case->simulation_id : '').($opportunity ? '&opportunity='.urlencode($opportunity) : '') : null,
|
||||
'desk' => '/balcao-virtual/dossiers/'.$id.($opportunity ? '?opportunity='.urlencode($opportunity) : ''), 'guidance' => '/balcao-virtual/dossiers/'.$id.'/orientacao',
|
||||
'library' => '/documentos?context='.$id, 'opportunities' => '/oportunidades?context='.$id, 'territory' => '/zonas?context='.$id, 'partners' => '/parcerias/painel?context='.$id,
|
||||
'land' => (int) $case->user_id === $actor->id ? ($landCase ? '/investidor/terra-duat/'.$landCase->id : '/investidor/terra-duat/novo?context='.$id) : null]];
|
||||
'land' => ($facts['land_needed'] ?? 'unknown') !== 'no' && (int) $case->user_id === $actor->id ? ($landCase ? '/investidor/terra-duat/'.$landCase->id : '/investidor/terra-duat/novo?context='.$id.($opportunity ? '&opportunity='.urlencode($opportunity) : '')) : null]];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function facts(User $actor, string $id, array $input): void
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1',
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'context_opportunity' => 'nullable|string|max:100',
|
||||
'land_needed' => ['required', Rule::in(['yes', 'no', 'unknown'])], 'external_funding' => ['required', Rule::in(['yes', 'no', 'unknown'])],
|
||||
'viability' => ['required', Rule::in(['unknown', 'proceed', 'reformulate', 'archive'])],
|
||||
'reason' => 'required|string|min:3|max:3000'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $data): void {
|
||||
$case = $this->writable($actor, $id, $data['version']);
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$choice = app(InvestmentConsumerScope::class)->key(app(InvestorContext::class)->state($case), $data['context_opportunity'] ?? null, true);
|
||||
foreach (['land_needed', 'external_funding', 'viability'] as $key) {
|
||||
$payload['investor_path']['facts'][$key] = $data[$key];
|
||||
$payload['investor_path']['fact_reasons'][$key] = $data['reason'];
|
||||
if ($choice) {
|
||||
$payload['investor_path']['opportunity_facts'][$choice][$key] = $data[$key];
|
||||
$payload['investor_path']['opportunity_fact_reasons'][$choice][$key] = $data['reason'];
|
||||
} else {
|
||||
$payload['investor_path']['facts'][$key] = $data[$key];
|
||||
$payload['investor_path']['fact_reasons'][$key] = $data['reason'];
|
||||
}
|
||||
}
|
||||
$this->savePayload($case, $payload);
|
||||
$this->desk->event($this->desk->case($actor, $id), $actor, 'path_applicability_declared', $data);
|
||||
@@ -190,7 +211,7 @@ final class InvestorPath
|
||||
/** @param array<string,mixed> $input */
|
||||
public function stage(User $actor, string $id, string $code, array $input): void
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'state' => ['required', Rule::in(array_diff(InvestorPathDefinition::STATES, ['dispensed']))],
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'context_opportunity' => 'nullable|string|max:100', 'state' => ['required', Rule::in(array_diff(InvestorPathDefinition::STATES, ['dispensed']))],
|
||||
'reason' => 'required|string|min:3|max:3000', 'action' => ['required', Rule::in(['prepare', 'submit', 'execute', 'operate', 'review', 'record_external'])],
|
||||
'document_id' => 'nullable|uuid', 'authority' => 'nullable|string|max:200', 'reference' => 'nullable|string|max:300',
|
||||
'context_revision' => 'nullable|integer|min:0', 'context_reviewed' => 'nullable|boolean', 'decision_date' => 'nullable|date_format:Y-m-d|before_or_equal:today'])->validate();
|
||||
@@ -198,7 +219,8 @@ final class InvestorPath
|
||||
$case = $this->desk->case($actor, $id, false, true);
|
||||
abort_if($case->closed_at, 409);
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'O dossier mudou; recupere a versão actual.');
|
||||
$view = $this->view($actor, $id);
|
||||
$key = app(InvestmentConsumerScope::class)->key(app(InvestorContext::class)->state($case), $data['context_opportunity'] ?? null, true);
|
||||
$view = $this->view($actor, $id, $key);
|
||||
$step = $this->findStep($view, $code);
|
||||
abort_unless($step !== null && $step['preparation_allowed'], 422, 'Etapa dispensada de preparação; altere os pressupostos com fundamento.');
|
||||
$state = $data['state'];
|
||||
@@ -233,7 +255,10 @@ final class InvestorPath
|
||||
}
|
||||
abort_if($state === 'completed' && ($step['context_review_required'] ?? false) && (! (bool) ($data['context_reviewed'] ?? false) || ($data['context_revision'] ?? -1) !== ($view['investment_context']['revision'] ?? 0)), 422, 'O contexto desta etapa exige nova conferência fundamentada; o registo anterior permanece no histórico.');
|
||||
$detail = [...$data, 'context_dependency_hash' => $view['investment_context']['dependency_hash'] ?? null, 'fintech_fingerprint' => $view['fintech']['review_fingerprints'][$code] ?? null, 'scope' => $scope, 'actor_id' => $actor->id, 'recorded_at' => now()->toIso8601String()];
|
||||
DB::table('journey_steps')->where('id', $step['id'])->update(['path_detail' => $this->desk->encode($detail),
|
||||
$stored = $this->desk->decode(DB::table('journey_steps')->where('id', $step['id'])->value('path_detail'));
|
||||
if ($key) $stored['opportunities'][$key] = $detail;
|
||||
else $stored = [...$stored, ...$detail];
|
||||
DB::table('journey_steps')->where('id', $step['id'])->update(['path_detail' => $this->desk->encode($stored),
|
||||
'status' => in_array($state, ['completed', 'approved'], true) ? 'completed' : ($state === 'not_started' ? 'pending' : 'active'),
|
||||
'version_no' => $step['version'] + 1, 'updated_at' => now()]);
|
||||
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
|
||||
@@ -262,11 +287,12 @@ final class InvestorPath
|
||||
abort_unless(is_array($parsed) && ($parsed['version'] ?? null) === 1 && is_array($parsed['data'] ?? null), 422, 'Snapshot financeiro incompatível.');
|
||||
$payload = $this->desk->decode($case->payload);
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
$opportunity = app(InvestmentConsumerScope::class)->key($context, $economic['context_opportunity'] ?? null, true);
|
||||
if ($context['revision'] > 0) {
|
||||
abort_unless(($data['context_revision'] ?? -1) === $context['revision'], 409, 'O contexto mudou; recupere e confira os pressupostos antes de devolver o resultado.');
|
||||
abort_unless($data['context_reviewed'] ?? false, 422, 'Confirme a revisão dos pressupostos financeiros para este contexto.');
|
||||
}
|
||||
$resultKey = hash('sha256', $draft->id.':'.$draft->version_no.':'.$snapshot.':context:'.$context['revision']);
|
||||
$resultKey = hash('sha256', $draft->id.':'.$draft->version_no.':'.$snapshot.':context:'.$context['revision'].($opportunity ? ':'.$opportunity : ''));
|
||||
foreach ($payload['investor_path']['results'] ?? [] as $result) {
|
||||
if ($result['source_key'] === $resultKey) {
|
||||
return $result;
|
||||
@@ -275,6 +301,7 @@ final class InvestorPath
|
||||
abort_unless((int) $case->version === $data['version'], 409, 'Recupere a versão actual do dossier.');
|
||||
$result = ['id' => (string) Str::uuid(), 'source_key' => $resultKey, 'draft_id' => $draft->id, 'draft_version' => $draft->version_no,
|
||||
'snapshot_sha256' => $draft->snapshot_sha256, 'financial_snapshot' => $snapshot,
|
||||
'context_opportunity' => $opportunity,
|
||||
'currency' => $economic['currency'] ?? null, 'engine' => 'financial-calculators:v1',
|
||||
'kind' => 'local_calculation_inputs', 'context_state' => 'current', 'context_revision' => $context['revision'], 'context_dependency_hash' => $context['dependency_hash'] ?? app(InvestorContext::class)->dependencyHash([]), 'recorded_at' => now()->toIso8601String()];
|
||||
$payload['investor_path']['results'][] = $result;
|
||||
|
||||
@@ -35,7 +35,7 @@ final class LegacyContent
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function article(string $slug = 'agronegocio'): array
|
||||
public function article(string $slug = 'agronegocio', bool $includeRelated = true): array
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
$identity = config('legacy_content.articles.'.$slug);
|
||||
@@ -78,15 +78,31 @@ final class LegacyContent
|
||||
$image = $this->publicResources()->where('r.id', $adaptation['image_resource_id'])->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->first();
|
||||
}
|
||||
}
|
||||
if ($slug === 'agronegocio') {
|
||||
$localHtml = app(CorridorAgribusiness::class)->enrich($localHtml, app(CorridorAgribusinessOpportunities::class)->articleLinks());
|
||||
}
|
||||
preg_match_all('~href="([^"]+)"~i', $localHtml, $existingLinks);
|
||||
$alreadyLinked = array_map(fn ($href) => html_entity_decode($href, ENT_QUOTES | ENT_HTML5, 'UTF-8'), $existingLinks[1]);
|
||||
$relatedArticles = array_values(array_filter($this->related($identity['group'], $slug), fn ($item) => !in_array($item['href'], $alreadyLinked, true)));
|
||||
$relatedArticles = [];
|
||||
if ($includeRelated) {
|
||||
foreach ($this->related($identity['group'], $slug) as $item) {
|
||||
if (in_array($item['href'], $alreadyLinked, true)) continue;
|
||||
try {
|
||||
$relatedArticles[] = $this->article($item['slug'], false);
|
||||
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $error) {
|
||||
if ($error->getStatusCode() !== 404) throw $error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['id' => (int) $row->resource_id, 'document_id' => $row->id, 'version' => (int) $row->metadata_version,
|
||||
'sha256' => trim($row->sha256), 'title' => $source['title'], 'author' => $source['author'],
|
||||
'legacy_id' => $source['legacy_id'], 'legacy_category' => $source['legacy_category'],
|
||||
'published_at' => $source['published_at'], 'modified_at' => $source['modified_at'], 'source_url' => $source['source_url'],
|
||||
'href' => '/'.$slug, 'html' => $localHtml,
|
||||
'href' => '/'.$slug, 'html' => $localHtml, 'summary' => self::excerpt($localHtml),
|
||||
'opportunities_href' => $sector ? '/oportunidades?sector='.rawurlencode($sector->slug) : null,
|
||||
'opportunities_label' => $sector ? 'Ver oportunidades de '.$sector->name : null,
|
||||
'has_opportunities' => count($opportunities) > 0,
|
||||
'landing_href' => '/explorar/'.$identity['group'], 'start_href' => '/investimentos/a-partir-de/'.$slug,
|
||||
'group' => config('legacy_content.groups.'.$identity['group']),
|
||||
'related_articles' => $relatedArticles,
|
||||
@@ -101,6 +117,22 @@ final class LegacyContent
|
||||
'consultation_state' => 'public', 'legal_state' => 'not_applicable', 'calculation_use' => false];
|
||||
}
|
||||
|
||||
/** An excerpt of the displayed edition, never a claim about returns or availability. */
|
||||
public static function excerpt(string $html): string
|
||||
{
|
||||
$plain = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
||||
if (str_contains($plain, 'Hotelaria e resorts') && str_contains($plain, 'Ecoturismo')
|
||||
&& str_contains($plain, 'Infraestruturas turísticas') && str_contains($plain, 'Oportunidades Regionais')) {
|
||||
return 'Conheça os temas de turismo e hospitalidade abordados no guia: hotelaria, ecoturismo, infraestruturas de apoio e referências regionais. Use este enquadramento para preparar a sua ideia de investimento.';
|
||||
}
|
||||
preg_match_all('~<p\b[^>]*>(.*?)</p>~isu', $html, $paragraphs);
|
||||
foreach ([...($paragraphs[1] ?? []), $html] as $paragraph) {
|
||||
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags($paragraph), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
|
||||
if (mb_strlen($text) >= 60) return \Illuminate\Support\Str::limit($text, 320);
|
||||
}
|
||||
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
|
||||
}
|
||||
|
||||
/** Resolve a library identity, preserving the already stored source URLs and versions. */
|
||||
/** @return array<string, mixed> */
|
||||
public function articleForResource(int $resourceId): array
|
||||
@@ -250,7 +282,7 @@ final class LegacyContent
|
||||
}
|
||||
|
||||
/** Allow presentation markup only. No scripts, styles, events, embeds or remote image execution. */
|
||||
public function sanitize(string $html): string
|
||||
public function sanitize(string $html, bool $preserveStructure = false): string
|
||||
{
|
||||
$doc = new DOMDocument;
|
||||
$old = libxml_use_internal_errors(true);
|
||||
@@ -267,7 +299,7 @@ final class LegacyContent
|
||||
}
|
||||
$headingOffset = 2 - (empty($sourceLevels) ? 2 : min($sourceLevels));
|
||||
$previousHeading = 1;
|
||||
$clean = function (DOMNode $node) use (&$clean, $doc, $headingOffset, &$previousHeading): void {
|
||||
$clean = function (DOMNode $node) use (&$clean, $doc, $headingOffset, &$previousHeading, $preserveStructure): void {
|
||||
foreach (iterator_to_array($node->childNodes) as $child) {
|
||||
if (! $child instanceof DOMElement) {
|
||||
continue;
|
||||
@@ -282,7 +314,7 @@ final class LegacyContent
|
||||
$node->replaceChild($section, $child);
|
||||
$child = $section;
|
||||
}
|
||||
if (! in_array(strtolower($child->tagName), ['p', 'strong', 'b', 'em', 'i', 'ul', 'ol', 'li', 'br', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'a'], true)) {
|
||||
if (! in_array(strtolower($child->tagName), array_merge(['p', 'strong', 'b', 'em', 'i', 'ul', 'ol', 'li', 'br', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'a'], $preserveStructure ? ['div', 'span', 'small', 'section', 'table', 'caption', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'figure', 'figcaption'] : []), true)) {
|
||||
$node->removeChild($child);
|
||||
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
|
||||
/** Read-only grouping of the existing public catalogue. */
|
||||
final class OpportunityCorridorExplorer
|
||||
{
|
||||
public function groups(array $filters): array
|
||||
{
|
||||
$catalogue = app(InvestmentCatalogue::class);
|
||||
$groups = [];
|
||||
foreach ($catalogue->query($filters)->get() as $record) {
|
||||
$context = $catalogue->context($record->id);
|
||||
$classification = $context['classification'] ?? [];
|
||||
$corridors = collect($context['corridors'])->mapWithKeys(fn ($c) => ['corridor:'.$c->id => $c->name])->all();
|
||||
foreach ($classification as $relation) {
|
||||
if ($relation['target_type'] === 'corridor' && ! in_array($relation['purpose'], ['proximity', 'administrative_boundary'], true)) {
|
||||
$corridors['corridor:'.$relation['target_id']] = $relation['label'];
|
||||
}
|
||||
}
|
||||
// The approved source names are not aliases for similarly named master records.
|
||||
$source = data_get($record->workflow_context, 'corridor_agribusiness');
|
||||
$chain = null;
|
||||
if (is_array($source) && ($source['source_sha256'] ?? null) === CorridorAgribusinessOpportunities::SOURCE_HASH) {
|
||||
$corridors['source:'.hash('sha256', $source['corridor'])] = $source['corridor'];
|
||||
$chain = $source['chain'];
|
||||
}
|
||||
$chains = collect($classification)->where('target_type', 'chain')->pluck('label')->all();
|
||||
if ($chain) $chains[] = $chain;
|
||||
$stages = collect($classification)->pluck('production_stage')->filter()->unique()->values()->all();
|
||||
// Keep the source's actual activity description rather than inventing stage labels.
|
||||
if ($stages === [] && $chain && ! empty($source['summary'])) $stages = [$source['summary']];
|
||||
$path = collect($context['primary_territory_path'] ?? []);
|
||||
$province = $path->firstWhere('location_type', 'province')->name ?? $record->province;
|
||||
$district = $path->firstWhere('location_type', 'district')->name ?? $record->district;
|
||||
$contextProvinces = app(InvestmentCorridorContext::class)->catalogueProvinces($record);
|
||||
$provinceOptions = $province ? [$province] : array_column($contextProvinces, 'name');
|
||||
$item = ['id' => $record->id, 'title' => $record->title, 'slug' => $record->slug, 'summary' => $record->summary,
|
||||
'province' => $province, 'district' => $district, 'provinces' => $provinceOptions,
|
||||
'territorial_summary' => $catalogue->presentLocation($record)->getAttribute('territorial_summary'), 'chains' => array_values(array_unique($chains)),
|
||||
'stages' => $stages, 'maturity_label' => $record->maturity_label];
|
||||
foreach ($corridors ?: ['other' => 'Outras localizações'] as $key => $name) {
|
||||
$groups[$key] ??= ['id' => $key, 'name' => $name, 'opportunities' => []];
|
||||
$groups[$key]['opportunities'][$record->id] = $item;
|
||||
}
|
||||
}
|
||||
foreach ($groups as &$group) {
|
||||
$group['opportunities'] = array_values($group['opportunities']);
|
||||
$group['count'] = count($group['opportunities']);
|
||||
$group['locations'] = array_values(array_unique(array_filter(array_map(fn ($r) => implode(' / ', array_filter([$r['province'], $r['district']])), $group['opportunities']))));
|
||||
}
|
||||
unset($group);
|
||||
uasort($groups, fn ($a, $b) => ($a['id'] === 'other' ? 1 : 0) <=> ($b['id'] === 'other' ? 1 : 0) ?: strnatcasecmp($a['name'], $b['name']));
|
||||
return array_values($groups);
|
||||
}
|
||||
}
|
||||
@@ -21,12 +21,15 @@ class OpportunityManagement
|
||||
|
||||
public const MATURITY_FIELDS = ['maturity_level', 'maturity_label', 'maturity_stage', 'maturity_catalogue_version'];
|
||||
|
||||
public const PRIVATE_DRAFT_FIELDS = [...self::MATURITY_FIELDS, 'real_estate', 'canonical'];
|
||||
public const PRIVATE_DRAFT_FIELDS = [...self::MATURITY_FIELDS, 'real_estate', 'canonical', 'proactive'];
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function values(Opportunity $record): array
|
||||
{
|
||||
$base = $record->only(self::FIELDS);
|
||||
if (data_get($record->workflow_context, 'publication.purpose') === OpportunityPromotion::PURPOSE) {
|
||||
$base = [...$base, ...($record->workflow_context['promotional_private_base'] ?? [])];
|
||||
}
|
||||
$draft = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
|
||||
return [...$base, ...($this->closed($record) ? $draft : array_intersect_key($draft, array_flip(self::PRIVATE_DRAFT_FIELDS)))];
|
||||
@@ -60,7 +63,7 @@ class OpportunityManagement
|
||||
abort_if(array_key_exists('organization_id', $input) && $input['organization_id'] !== $existingRecord->organization_id, 403, 'A organização não pode ser alterada por edição.');
|
||||
}
|
||||
} elseif ($profileCreation) {
|
||||
abort_unless($access->canCreate($actor, $input['organization_id'] ?? null, $input['opportunity_category'] ?? ''), 403);
|
||||
abort_unless(($access->canCreate($actor, $input['organization_id'] ?? null, $input['opportunity_category'] ?? '') || (isset($input['proactive']) && empty($input['organization_id']) && !$access->has($actor, 'auditor') && $access->internalAssignment($actor, $input['opportunity_category'] ?? '') !== null)), 403);
|
||||
} else {
|
||||
abort_unless($access->legacyWriteAllowed($actor), 403, 'O papel v1 não usa a criação legada para contornar o seu âmbito.');
|
||||
}
|
||||
@@ -89,6 +92,7 @@ class OpportunityManagement
|
||||
'opportunity_category' => ['nullable', Rule::in(self::CATEGORIES)],
|
||||
'real_estate' => ['sometimes', 'array'],
|
||||
'canonical' => ['sometimes', 'array'],
|
||||
'proactive' => ['sometimes', 'array'],
|
||||
'estimated_investment_amount' => ['nullable', 'regex:/^\d{1,16}(\.\d{1,2})?$/'],
|
||||
'estimated_investment_currency' => ['nullable', 'in:MZN,USD,EUR,ZAR'],
|
||||
'reason' => ['required', 'string', 'min:20', 'max:1000'],
|
||||
@@ -124,6 +128,7 @@ class OpportunityManagement
|
||||
$this->check($record, $data['etag']);
|
||||
abort_if($record->trashed() || $record->status === 'archived', 409, 'Restaure antes de editar.');
|
||||
}
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
$before = $record->getAttributes();
|
||||
$previousCanonical = $record->exists ? ($this->values($record)['canonical'] ?? []) : [];
|
||||
$changes = array_intersect_key($data, array_flip([...self::FIELDS, ...self::PRIVATE_DRAFT_FIELDS]));
|
||||
@@ -167,7 +172,7 @@ class OpportunityManagement
|
||||
$record->management_version = 1;
|
||||
$record->estimated_investment_currency = null;
|
||||
if ($profileCreation) {
|
||||
abort_unless($access->canCreate($actor, $data['organization_id'] ?? null, $data['opportunity_category'] ?? ''), 403);
|
||||
abort_unless(($access->canCreate($actor, $data['organization_id'] ?? null, $data['opportunity_category'] ?? '') || (isset($data['proactive']) && empty($data['organization_id']) && !$access->has($actor, 'auditor') && $access->internalAssignment($actor, $data['opportunity_category'] ?? '') !== null)), 403);
|
||||
$record->owner_user_id = $actor->id;
|
||||
$record->organization_id = $data['organization_id'] ?? null;
|
||||
$record->workflow_context = ['policy_version' => PortalProfileAccess::VERSION, 'contributors' => [$actor->id]];
|
||||
@@ -184,12 +189,12 @@ class OpportunityManagement
|
||||
$record->management_draft = json_encode([...$previous, ...$changes], JSON_THROW_ON_ERROR);
|
||||
} else {
|
||||
foreach ($changes as $key => $value) {
|
||||
if (in_array($key, ['real_estate', 'canonical', 'maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
|
||||
if (in_array($key, ['real_estate', 'canonical', 'proactive', 'maturity_stage', 'maturity_catalogue_version'], true) || (($changes['maturity_catalogue_version'] ?? null) === OpportunityMaturity::VERSION && in_array($key, ['maturity_level', 'maturity_label'], true))) {
|
||||
continue;
|
||||
}
|
||||
$record->{$key} = $value;
|
||||
}
|
||||
if (isset($changes['maturity_catalogue_version']) || array_key_exists('real_estate', $changes) || array_key_exists('canonical', $changes)) {
|
||||
if (isset($changes['maturity_catalogue_version']) || array_key_exists('real_estate', $changes) || array_key_exists('canonical', $changes) || array_key_exists('proactive', $changes)) {
|
||||
// The existing draft JSON holds the versioned catalogue; legacy columns stay intact.
|
||||
$previous = $record->management_draft ? json_decode($record->management_draft, true, 512, JSON_THROW_ON_ERROR) : [];
|
||||
$record->management_draft = json_encode([...$previous, ...array_intersect_key($changes, array_flip(self::PRIVATE_DRAFT_FIELDS))], JSON_THROW_ON_ERROR);
|
||||
@@ -222,6 +227,7 @@ class OpportunityManagement
|
||||
$record = Opportunity::withTrashed()->whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_if($record->owner_user_id !== null, 403, 'A v1 exige pedido e decisão de arquivo; não concede exclusão ou restauro ao Promotor.');
|
||||
$this->check($record, $data['etag']);
|
||||
if (array_key_exists('proactive', $data)) $data['proactive'] = app(ProactiveInvestment::class)->draft($data['proactive'], $record, $actor);
|
||||
$before = $record->getAttributes();
|
||||
if ($data['action'] === 'restore') {
|
||||
abort_unless($record->trashed() || $record->status === 'archived', 409, 'Registo não está eliminado/arquivado.');
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Tempo's promotional disclosure, independent of investment execution approval. */
|
||||
final class OpportunityPromotion
|
||||
{
|
||||
public const PURPOSE = 'promotional_preparation';
|
||||
public const NOTICE = 'Em preparação. A divulgação não confirma financiamento, disponibilidade de terreno, licenças ou autorização de execução do investimento.';
|
||||
|
||||
public function allowed(User $actor, Opportunity $record): bool
|
||||
{
|
||||
$access = app(PortalProfileAccess::class);
|
||||
if ($record->trashed() || $record->owner_user_id === null || ! $access->canView($actor, $record)
|
||||
|| $access->has($actor, 'auditor') || in_array($record->status, ['archived', 'rejected'], true)) return false;
|
||||
// Never overwrite a normal approved publication or its workflow decisions.
|
||||
if ($record->published_at && data_get($record->workflow_context, 'publication.purpose') !== self::PURPOSE) return false;
|
||||
$internal = $access->internalAssignment($actor, $record->opportunity_category);
|
||||
return ($internal && $access->promoterRecordScope($actor, $record) && $access->operational($actor, 'edit', $record->id))
|
||||
|| ($access->scoped($actor, 'publisher', $record->organization_id, $record->opportunity_category)
|
||||
&& $access->operational($actor, 'publish', $record->id));
|
||||
}
|
||||
|
||||
private function authorize(User $actor, Opportunity $record): void
|
||||
{
|
||||
abort_unless($this->allowed($actor, $record), 403, 'A designação e o âmbito existentes não autorizam esta divulgação.');
|
||||
if (! app(PortalProfileAccess::class)->mfa($actor)) {
|
||||
throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(['message' => 'Confirme a entrada normal com MFA recente para divulgar.'], 403)->header('X-Portal-Reauthentication', 'required'));
|
||||
}
|
||||
}
|
||||
|
||||
public function editor(User $actor, Opportunity $record): array
|
||||
{
|
||||
abort_unless($this->allowed($actor, $record), 403);
|
||||
$saved = data_get($record->workflow_context, 'promotional_summary', []);
|
||||
// Only previously public text is recovered automatically. No private contact/document is copied.
|
||||
$existing = data_get($record->workflow_context, 'publication.purpose') === self::PURPOSE;
|
||||
$form = $saved['input'] ?? ['title' => $existing ? $record->title : '', 'summary' => $existing ? $record->summary : '',
|
||||
'description' => $existing ? $record->description : '', 'source_reference' => '', 'edition' => '', 'source_date' => '',
|
||||
'limitations' => '', 'territory_ids' => $existing ? DB::table('opportunity_locations')->where('opportunity_id', $record->id)->pluck('geo_location_id')->all() : [],
|
||||
'sector_id' => $record->sector_id];
|
||||
return ['record' => ['id' => $record->id, 'reference' => $record->reference], 'etag' => app(OpportunityManagement::class)->etag($record),
|
||||
'proactiveRelations' => app(ProactiveInvestment::class)->publicationRelations($record), 'proactiveKind' => app(OpportunityManagement::class)->values($record)['proactive']['kind'] ?? null, 'proactiveEnabled' => isset(app(OpportunityManagement::class)->values($record)['proactive']), 'proactiveEvidence' => array_values(array_filter(app(OpportunityManagement::class)->values($record)['proactive']['evidence'] ?? [], fn ($e) => $e['access'] === 'public')), 'proactiveOptions' => app(ProactiveInvestment::class)->options(), 'initial' => [...$form, ...($saved['input']['proactive_public'] ?? null ? ['proactive_public' => $saved['input']['proactive_public']] : [])], 'publicNow' => $existing && $record->status === 'published',
|
||||
'reauthenticationRequired' => ! app(PortalProfileAccess::class)->mfa($actor),
|
||||
'sectors' => \App\Models\Sector::catalog()->orderBy('name')->get(['id', 'name']),
|
||||
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type']),
|
||||
'history' => DB::table('audit_events')->where('source_system', 'tempo-preparation-publication')
|
||||
->where('after_data->record_id', $record->id)->orderByDesc('occurred_at')->get(['id', 'action', 'actor_user_id', 'occurred_at'])];
|
||||
}
|
||||
|
||||
public function preview(User $actor, Opportunity $record, array $input): array
|
||||
{
|
||||
$this->authorize($actor, $record);
|
||||
$data = Validator::make($input, ['etag' => 'required|string|size:64', 'action' => 'required|in:disclose,withdraw',
|
||||
'title' => 'required_if:action,disclose|nullable|string|max:255', 'summary' => 'required_if:action,disclose|nullable|string|max:499',
|
||||
'description' => 'nullable|string|max:6000', 'limitations' => 'nullable|string|max:2500',
|
||||
'source_reference' => 'nullable|string|max:2000', 'edition' => 'nullable|string|max:150', 'source_date' => 'nullable|date_format:Y-m-d',
|
||||
'proactive_public' => 'sometimes|array', 'proactive_reviewed' => 'sometimes|boolean',
|
||||
'sector_id' => ['nullable', 'integer', Rule::in(\App\Models\Sector::catalog()->pluck('id')->all())],
|
||||
'territory_ids' => 'sometimes|array|max:30', 'territory_ids.*' => 'required|uuid|distinct',
|
||||
])->validate();
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $data['etag']), 409, 'A ficha mudou. Reabra antes de preparar outra prévia.');
|
||||
if ($data['action'] === 'withdraw') abort_unless(data_get($record->workflow_context, 'publication.purpose') === self::PURPOSE, 409);
|
||||
$paths = [];
|
||||
foreach ($data['territory_ids'] ?? [] as $id) {
|
||||
$path = app(InvestmentGeography::class)->path($id, true);
|
||||
abort_unless(count($path) > 0 && collect($path)->contains('id', $id), 422, 'Seleccione apenas territórios públicos existentes.');
|
||||
$paths[] = $path;
|
||||
}
|
||||
$text = fn ($key) => trim(strip_tags($data[$key] ?? ''));
|
||||
$body = implode("\n\n", array_filter([$text('description'), self::NOTICE,
|
||||
'Limitações e lacunas: '.($text('limitations') ?: 'Informação ainda por completar.'),
|
||||
'Fonte: '.($text('source_reference') ?: 'Não indicada.'), 'Edição: '.($text('edition') ?: 'Não indicada.'),
|
||||
'Data-base: '.($data['source_date'] ?? 'Não indicada.')]));
|
||||
$body = OpportunityPublicText::description($record, $body);
|
||||
$projection = ['title' => $text('title'), 'summary' => $text('summary'), 'description' => $body,
|
||||
'sector_id' => $data['sector_id'] ?? null, 'maturity_label' => 'Em preparação', 'notice' => self::NOTICE,
|
||||
'territories' => array_map(fn ($p) => ['id' => end($p)->id, 'label' => implode(' / ', array_column($p, 'name'))], $paths)];
|
||||
if ($data['action'] === 'disclose' && ($proactive = app(ProactiveInvestment::class)->publication($record, $data))) { $projection['proactive'] = $proactive; $projection['description'] .= "\n\n".implode("\n", [$proactive['group'] === 'ideas' ? 'Ideia em preparação' : ($proactive['group'] === 'needs' ? 'Necessidade — '.$proactive['state'] : 'O que existe'), 'Necessidade: '.$proactive['need'], 'Proposta: '.$proactive['proposal'], 'Fundamento: '.$proactive['basis'], 'Limitações: '.$proactive['limitations'], 'Próximo passo: '.$proactive['next_action'], ProactiveInvestment::NOTICE]); }
|
||||
if ($data['action'] === 'disclose') abort_unless($projection['title'] !== '' && $projection['summary'] !== '', 422, 'Indique título e resumo em texto simples.');
|
||||
if ($data['action'] === 'withdraw') $projection = [...$projection, ...$record->only(['title', 'summary', 'description', 'sector_id', 'maturity_label'])];
|
||||
$payload = ['actor_id' => $actor->id, 'record_id' => $record->id, 'etag' => $data['etag'], 'action' => $data['action'],
|
||||
'input' => $data, 'projection' => $projection, 'expires' => now()->addMinutes(15)->timestamp];
|
||||
return ['action' => $data['action'], 'projection' => $projection, 'token' => Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR)),
|
||||
'current' => $record->only(['title', 'summary', 'description', 'status']), 'writes' => false];
|
||||
}
|
||||
|
||||
public function confirm(User $actor, int $id, array $input): array
|
||||
{
|
||||
$data = Validator::make($input, ['token' => 'required|string|max:300000', 'operation_key' => 'required|uuid',
|
||||
'confirm' => 'required|accepted', 'reason' => 'required|string|min:10|max:1000'])->validate();
|
||||
try { $preview = json_decode(Crypt::decryptString($data['token']), true, flags: JSON_THROW_ON_ERROR); }
|
||||
catch (\Throwable) { abort(422, 'Prévia inválida. Prepare outra prévia.'); }
|
||||
abort_unless(($preview['actor_id'] ?? null) === $actor->id && ($preview['record_id'] ?? null) === $id, 403);
|
||||
return DB::transaction(function () use ($actor, $id, $data, $preview) {
|
||||
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['promotional-operation:'.$data['operation_key']]);
|
||||
$record = Opportunity::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
$this->authorize($actor, $record);
|
||||
$digest = hash('sha256', $data['token'].'|'.$data['reason']);
|
||||
$replay = DB::table('audit_events')->where('source_system', 'tempo-preparation-publication')
|
||||
->where('after_data->operation_key', $data['operation_key'])->first();
|
||||
if ($replay) {
|
||||
$prior = json_decode($replay->after_data, true);
|
||||
abort_unless($prior['record_id'] === $id && (int) $replay->actor_user_id === $actor->id && hash_equals($prior['request_hash'], $digest), 409, 'Chave usada noutra operação.');
|
||||
return ['id' => $id, 'replayed' => true, 'message' => 'Operação já registada; nenhuma alteração repetida.'];
|
||||
}
|
||||
abort_unless(($preview['expires'] ?? 0) >= now()->timestamp, 409, 'A prévia expirou. Prepare outra prévia.');
|
||||
abort_unless(hash_equals(app(OpportunityManagement::class)->etag($record), $preview['etag']), 409, 'Alteração concorrente: a ficha foi preservada. Reabra e reveja a nova versão.');
|
||||
$before = $record->getRawOriginal();
|
||||
$oldLocations = DB::table('opportunity_locations')->where('opportunity_id', $id)->pluck('geo_location_id')->all();
|
||||
$context = $record->workflow_context ?? [];
|
||||
if ($preview['action'] === 'withdraw') {
|
||||
$record->status = 'suspended';
|
||||
$record->published_at = null;
|
||||
$context['publication']['visibility'] = 'withdrawn';
|
||||
$action = 'promotional_summary_withdrawn';
|
||||
} else {
|
||||
$p = $preview['projection'];
|
||||
if ($p['sector_id'] !== null) abort_unless(\App\Models\Sector::catalog()->whereKey($p['sector_id'])->exists(), 409, 'O sector deixou de estar disponível no catálogo. Prepare outra prévia.');
|
||||
$paths = [];
|
||||
foreach ($preview['input']['territory_ids'] ?? [] as $territory) {
|
||||
$path = app(InvestmentGeography::class)->path($territory, true);
|
||||
abort_unless(count($path) && collect($path)->contains('id', $territory), 409, 'Um território deixou de estar disponível. Prepare outra prévia.');
|
||||
$paths[] = $path;
|
||||
}
|
||||
$currentTerritories = array_map(fn ($path) => ['id' => end($path)->id, 'label' => implode(' / ', array_column($path, 'name'))], $paths);
|
||||
abort_unless($currentTerritories === $p['territories'], 409, 'O enquadramento territorial mudou. Prepare outra prévia.');
|
||||
// Preserve the original private draft bytes; retain its former base
|
||||
// columns in the existing hidden context before projecting public text.
|
||||
$context['promotional_private_base'] ??= $record->only(OpportunityManagement::FIELDS);
|
||||
$context['working_state'] ??= app(PortalProfileAccess::class)->state($record);
|
||||
$context['promotional_summary'] = ['input' => $preview['input'], 'projection' => $p];
|
||||
$context['publication'] = ['visibility' => 'public', 'purpose' => self::PURPOSE, 'actor_id' => $actor->id,
|
||||
'at' => now()->toIso8601String(), 'execution_approved' => false, 'private_draft_preserved' => true];
|
||||
$action = data_get($before, 'status') === 'published' ? 'promotional_summary_updated' : 'promotional_summary_published';
|
||||
foreach (['title', 'summary', 'description', 'sector_id', 'maturity_label'] as $field) $record->{$field} = $p[$field];
|
||||
foreach (['promoter_name', 'promoter_type', 'financing_modality', 'expected_impact', 'maturity_level', 'estimated_investment_amount', 'estimated_investment_currency'] as $field) $record->{$field} = null;
|
||||
$main = $paths[0] ?? [];
|
||||
$record->primary_territory_id = $main ? end($main)->id : null;
|
||||
$record->province = collect($main)->firstWhere('location_type', 'province')?->name;
|
||||
$record->district = collect($main)->firstWhere('location_type', 'district')?->name;
|
||||
$record->geography_scope = count($paths) > 1 ? 'multiple' : ($main ? 'specific' : 'unspecified');
|
||||
DB::table('opportunity_locations')->where('opportunity_id', $id)->delete();
|
||||
foreach ($preview['input']['territory_ids'] ?? [] as $territory) DB::table('opportunity_locations')->insert(['opportunity_id' => $id, 'geo_location_id' => $territory]);
|
||||
$record->status = 'published';
|
||||
$record->is_featured = false;
|
||||
$record->last_validated_at = null;
|
||||
$record->published_at = now();
|
||||
}
|
||||
$record->workflow_context = $context;
|
||||
$record->management_version++;
|
||||
$record->save();
|
||||
DB::table('audit_events')->insert(['source_system' => 'tempo-preparation-publication', 'entity_type' => 'opportunity',
|
||||
'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'correlation_id' => (string) Str::uuid(),
|
||||
'before_data' => json_encode(['record_id' => $id, 'record' => $before, 'territories' => $oldLocations], JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode(['record_id' => $id, 'operation_key' => $data['operation_key'], 'request_hash' => $digest,
|
||||
'reason' => $data['reason'], 'projection' => $preview['projection'], 'execution_approved' => false,
|
||||
'record' => $record->getRawOriginal()], JSON_THROW_ON_ERROR)]);
|
||||
return ['id' => $id, 'replayed' => false, 'message' => $preview['action'] === 'withdraw' ? 'Resumo retirado; cadastro e histórico preservados.' : 'Resumo divulgado como Em preparação. Não autoriza execução do investimento.'];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
|
||||
/** Presentation only: originals, editorial fields and audit records remain intact. */
|
||||
final class OpportunityPublicText
|
||||
{
|
||||
public static function description(Opportunity $record, string $text): string
|
||||
{
|
||||
$source = data_get($record->workflow_context, 'corridor_agribusiness');
|
||||
if (! is_array($source) || ($source['source_sha256'] ?? null) !== CorridorAgribusinessOpportunities::SOURCE_HASH) return $text;
|
||||
|
||||
$hash = CorridorAgribusinessOpportunities::SOURCE_HASH;
|
||||
$sourceLine = 'Fonte: '.$source['source'].'; SHA-256 '.$hash;
|
||||
$paragraphs = explode("\n\n", $text);
|
||||
$result = [];
|
||||
foreach ($paragraphs as $paragraph) {
|
||||
$paragraph = trim($paragraph);
|
||||
if (in_array($paragraph, [$sourceLine, $sourceLine.'.', 'Edição: Não indicada.', 'Data-base: Não indicada.',
|
||||
'Limitações e lacunas: '.CorridorAgribusinessOpportunities::LIMITATIONS,
|
||||
OpportunityPromotion::NOTICE], true)) continue;
|
||||
if ($paragraph === 'Enquadramento documental: '.$source['corridor'].'.') $paragraph = $source['corridor'].'.';
|
||||
if ($paragraph === CorridorAgribusinessOpportunities::LIMITATIONS) {
|
||||
$paragraph = 'A localização exacta, a disponibilidade de terreno e as condições do investimento serão definidas durante a preparação do projecto.';
|
||||
}
|
||||
if ($paragraph !== '') $result[] = $paragraph;
|
||||
}
|
||||
return implode("\n\n", $result);
|
||||
}
|
||||
}
|
||||
@@ -184,7 +184,9 @@ class PortalProfileAccess
|
||||
|
||||
public function canCreate(User $actor, ?string $organization, string $type): bool
|
||||
{
|
||||
$included = in_array($type, OpportunityCanonicalContract::BASE_CATEGORIES, true) || app(OpportunityModularProfiles::class)->enabled();
|
||||
// Draft preparation is allowed within the assigned modality. Executable
|
||||
// submission support is checked separately by the canonical contract.
|
||||
$included = in_array($type, OpportunityManagement::CATEGORIES, true);
|
||||
|
||||
// This is creation as an authorized Promotor, never an exceptional SU act.
|
||||
return $included && $this->available() && $this->scoped($actor, 'promoter', $organization, $type) && ! $this->has($actor, 'auditor');
|
||||
@@ -243,7 +245,9 @@ class PortalProfileAccess
|
||||
|
||||
return $this->canView($actor, $record) && $this->promoterRecordScope($actor, $record) && ! $record->trashed()
|
||||
&& in_array($this->state($record), ['draft', 'needs_information'], true)
|
||||
&& $this->scoped($actor, 'promoter', $record->organization_id, $newType ?? $record->opportunity_category)
|
||||
&& ($this->scoped($actor, 'promoter', $record->organization_id, $newType ?? $record->opportunity_category)
|
||||
|| ($record->organization_id === null && isset(app(OpportunityManagement::class)->values($record)['proactive'])
|
||||
&& $this->internalAssignment($actor, $newType ?? $record->opportunity_category) !== null))
|
||||
&& $this->operational($actor, 'edit', $record->id);
|
||||
}
|
||||
|
||||
@@ -370,7 +374,8 @@ class PortalProfileAccess
|
||||
foreach (json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR) as $type) {
|
||||
$key = ($grant->organization_id ?? 'individual').'|'.$type;
|
||||
if (! isset($seen[$key]) && $this->canCreate($actor, $grant->organization_id, $type)) {
|
||||
$contexts[] = ['organization_id' => $grant->organization_id, 'type' => $type];
|
||||
$contexts[] = ['organization_id' => $grant->organization_id,
|
||||
'organization_name' => $grant->organization_id ? DB::table('organizations')->where('id', $grant->organization_id)->value('name') : null, 'type' => $type];
|
||||
$seen[$key] = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Brick\Math\BigDecimal;
|
||||
|
||||
/** Adapter of the dossier's declared context to preparation of a private-investment request. No tax or entitlement decision. */
|
||||
final class PrivateInvestmentPreparation
|
||||
{
|
||||
public const VERSION = 'private-investment-preparation-2026-v1';
|
||||
|
||||
public const SOURCE = 'https://pt.apiex.gov.mz/wp-content/uploads/2025/02/LEGISLACAO-DE-INVESTIMENTOS-EM-MOCAMBIQUE.pdf';
|
||||
|
||||
public const HASH = 'ba1e9eaabfec5d0c4cb2d9f2444a6860f7a90f222034764197829be402d408ed';
|
||||
|
||||
public const FIELDS = ['investment_form', 'investment_preparation', 'investment_activity_scope', 'implementation_mode', 'capital_origin', 'site_tenure', 'project_concession', 'significant_implications', 'land_extension', 'forest_concession', 'forest_concession_hectares', 'total_investment', 'area_required', 'area_unit'];
|
||||
|
||||
public const DOCUMENTS = ['identity', 'registration', 'name_reservation', 'site_plan', 'lease', 'duat', 'representation_license', 'feasibility', 'financial_capacity', 'foreign_capital'];
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return (bool) config('investor-path.private_preparation', false);
|
||||
}
|
||||
|
||||
public function questions(): array
|
||||
{
|
||||
$tri = ['unknown' => 'Por determinar', 'yes' => 'Sim', 'no' => 'Não'];
|
||||
|
||||
return [
|
||||
['key' => 'investment_preparation', 'label' => 'Pretende preparar o pedido de garantias/incentivos ao investimento privado?', 'options' => $tri, 'source' => 'Lei 8/2023, artigo 2'],
|
||||
['key' => 'investment_activity_scope', 'label' => 'Natureza efectiva da actividade do projecto', 'options' => ['unknown' => 'Por determinar', 'general' => 'Outra actividade económica', 'extractive' => 'Prospecção, pesquisa ou produção extractiva', 'processing' => 'Processamento industrial mineiro/petrolífero', 'public_nonprofit' => 'Investimento público ou exclusivamente social/sem fins lucrativos'], 'source' => 'Lei 8/2023, artigos 2 e 22'],
|
||||
['key' => 'investment_form', 'label' => 'Tipo deste investimento', 'options' => ['unknown' => 'Por determinar', 'direct' => 'Directo', 'indirect' => 'Indirecto'], 'source' => 'Lei 8/2023, artigo 14(b); Regulamento, artigo 13', 'help' => 'O limiar monetário do artigo 13 aplica-se ao investimento directo. A forma indirecta não é convertida silenciosamente em directa.'],
|
||||
['key' => 'implementation_mode', 'label' => 'Modalidade da empresa implementadora', 'options' => ['unknown' => 'Por determinar', 'domestic_entity' => 'Empresa constituída/em constituição em Moçambique', 'foreign_representation' => 'Representação comercial estrangeira'], 'source' => 'Regulamento 8/2024, artigo 9(2)'],
|
||||
['key' => 'capital_origin', 'label' => 'Origem dos capitais/recursos deste investimento', 'options' => ['unknown' => 'Por determinar', 'national' => 'Nacionais', 'external' => 'Provenientes do exterior', 'mixed' => 'Mistos'], 'source' => 'Lei 8/2023, glossário; Regulamento, artigos 4–6'],
|
||||
['key' => 'site_tenure', 'label' => 'Fundamento declarado da utilização das instalações', 'options' => ['unknown' => 'Por determinar', 'lease' => 'Arrendamento', 'duat' => 'DUAT'], 'source' => 'Regulamento, artigos 9(1)(d) e 14(1)(d)'],
|
||||
['key' => 'project_concession', 'label' => 'O empreendimento é PPP ou concessão empresarial?', 'options' => $tri, 'source' => 'Lei 8/2023, artigo 22(1)(b)(ii)'],
|
||||
['key' => 'significant_implications', 'label' => 'Existem previsíveis implicações económicas, ambientais, de segurança ou saúde pública que exijam autorização?', 'options' => $tri, 'source' => 'Lei 8/2023, artigo 22(1)(b)(i)', 'help' => 'Declare o enquadramento conhecido; o nome do sector não responde a esta pergunta. Sem fundamento suficiente, mantenha por determinar.'],
|
||||
['key' => 'land_extension', 'label' => 'O projecto requer extensão de terra?', 'options' => $tri, 'source' => 'Lei 8/2023, artigo 22(1)(b)(iii)'],
|
||||
['key' => 'forest_concession', 'label' => 'O projecto requer concessão florestal?', 'options' => $tri, 'source' => 'Lei 8/2023, artigo 22(1)(b)(iv)'],
|
||||
['key' => 'forest_concession_hectares', 'label' => 'Área da concessão florestal (hectares)', 'type' => 'number', 'when' => ['field' => 'forest_concession', 'equals' => 'yes'], 'source' => 'Lei 8/2023, artigo 22(1)(b)(iv)'],
|
||||
['key' => 'total_investment', 'label' => 'Valor total do investimento na moeda do projecto', 'type' => 'number', 'source' => 'Regulamento, artigo 13(2)'],
|
||||
['key' => 'area_required', 'label' => 'Área de terra requerida', 'type' => 'number', 'when' => ['field' => 'land_extension', 'equals' => 'yes'], 'source' => 'Lei 8/2023, artigo 22(1)(b)(iii)'],
|
||||
['key' => 'area_unit', 'label' => 'Unidade da área requerida', 'options' => ['ha' => 'Hectares', 'm2' => 'Metros quadrados'], 'when' => ['field' => 'land_extension', 'equals' => 'yes'], 'source' => 'Conversão de unidade exacta; não é benefício ou condição adicional'],
|
||||
];
|
||||
}
|
||||
|
||||
private function number(array $f, string $key): ?BigDecimal
|
||||
{
|
||||
$value = $f[$key] ?? '';
|
||||
|
||||
return is_scalar($value) && preg_match('/^\d+(?:\.\d+)?$/D', (string) $value) ? BigDecimal::of((string) $value) : null;
|
||||
}
|
||||
|
||||
public function assess(array $context, array $documents = []): array
|
||||
{
|
||||
$f = $context['fields'] ?? [];
|
||||
$missing = [];
|
||||
$answer = function (string $key) use ($f, &$missing): ?bool {
|
||||
if (! in_array($f[$key] ?? '', ['yes', 'no'], true)) {
|
||||
$missing[] = $key;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $f[$key] === 'yes';
|
||||
};
|
||||
$enabled = ($f['investment_preparation'] ?? '') === 'yes';
|
||||
$date = $f['expected_start_date'] ?? '';
|
||||
$period = preg_match('/^2026-\d{2}-\d{2}$/D', $date) === 1;
|
||||
$scope = $f['investment_activity_scope'] ?? 'unknown';
|
||||
$covered = in_array($scope, ['general', 'processing'], true);
|
||||
$mode = 'indeterminate';
|
||||
$reasons = [];
|
||||
if ($enabled) {
|
||||
if (! $date) {
|
||||
$missing[] = 'expected_start_date';
|
||||
}
|
||||
if ($scope === 'unknown' || $scope === '') {
|
||||
$missing[] = 'investment_activity_scope';
|
||||
}
|
||||
if (empty($f['currency'])) {
|
||||
$missing[] = 'currency';
|
||||
}
|
||||
if ($covered && $period) {
|
||||
$triggers = [];
|
||||
if ($scope === 'processing') {
|
||||
$triggers['processing'] = true;
|
||||
$reasons[] = 'Processamento industrial mineiro/petrolífero: Lei 8/2023, artigo 22(1)(b)(v).';
|
||||
}
|
||||
$amount = $this->number($f, 'total_investment');
|
||||
$triggers['amount'] = $amount && ($f['currency'] ?? '') === 'MZN' && ($f['investment_form'] ?? '') === 'direct' ? $amount->isGreaterThan('32000000000') : null;
|
||||
if (! in_array($f['investment_form'] ?? '', ['direct', 'indirect'], true)) {
|
||||
$missing[] = 'investment_form';
|
||||
}
|
||||
if (($f['investment_form'] ?? '') === 'indirect') {
|
||||
$reasons[] = 'Investimento indirecto: a classificação pela dimensão e o encaminhamento monetário não são determinados por este lote. As restantes condições documentadas continuam avaliadas.';
|
||||
}
|
||||
if (! $amount) {
|
||||
$missing[] = 'total_investment';
|
||||
}
|
||||
if (($f['currency'] ?? '') !== 'MZN') {
|
||||
$reasons[] = 'A condição monetária não é determinada noutra moeda: não se fez conversão.';
|
||||
}
|
||||
foreach (['project_concession', 'significant_implications'] as $key) {
|
||||
$triggers[$key] = $answer($key);
|
||||
}
|
||||
$land = $answer('land_extension');
|
||||
if ($land === true) {
|
||||
$area = $this->number($f, 'area_required');
|
||||
$unit = $f['area_unit'] ?? '';
|
||||
if (! $area) {
|
||||
$missing[] = 'area_required';
|
||||
}if (! in_array($unit, ['ha', 'm2'], true)) {
|
||||
$missing[] = 'area_unit';
|
||||
}
|
||||
$triggers['land_extension'] = $area && in_array($unit, ['ha', 'm2'], true) ? $area->isGreaterThanOrEqualTo($unit === 'ha' ? '10000' : '100000000') : null;
|
||||
} else {
|
||||
$triggers['land_extension'] = $land;
|
||||
}
|
||||
$forest = $answer('forest_concession');
|
||||
if ($forest === true) {
|
||||
$area = $this->number($f, 'forest_concession_hectares');
|
||||
if (! $area) {
|
||||
$missing[] = 'forest_concession_hectares';
|
||||
}$triggers['forest_concession'] = $area ? $area->isGreaterThan('100000') : null;
|
||||
} else {
|
||||
$triggers['forest_concession'] = $forest;
|
||||
}
|
||||
foreach (['amount' => 'Valor superior a 32 mil milhões MZN — R13(2), R21(2)(a)', 'project_concession' => 'PPP/concessão empresarial — Lei 8/2023, art. 22(1)(b)(ii), R21(2)(b)', 'significant_implications' => 'Implicações significativas declaradas — Lei 8/2023, art. 22(1)(b)(i), R21(1)', 'land_extension' => 'Extensão de terra igual/superior a 10 mil hectares — Lei 8/2023, art. 22(1)(b)(iii), R21(2)(c)', 'forest_concession' => 'Concessão florestal superior a 100 mil hectares — Lei 8/2023, art. 22(1)(b)(iv), R21(2)(d)'] as $condition => $description) {
|
||||
if (($triggers[$condition] ?? null) === true) {
|
||||
$reasons[] = $description.'.';
|
||||
}
|
||||
}
|
||||
$mode = in_array(true, $triggers, true) ? 'authorization' : (in_array(null, $triggers, true) ? 'indeterminate' : 'registration');
|
||||
$reasons[] = $mode === 'authorization' ? 'Foi identificada uma condição de autorização; as restantes condições desconhecidas não foram presumidas negativas.' : ($mode === 'registration' ? 'As condições de autorização deste lote foram declaradas negativas e o montante não ultrapassa o limite.' : 'Falta resolver pelo menos uma condição de autorização.');
|
||||
}
|
||||
foreach (['implementation_mode', 'capital_origin', 'site_tenure', 'entity_stage'] as $key) {
|
||||
if (empty($f[$key]) || $f[$key] === 'unknown') {
|
||||
$missing[] = $key;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($mode === 'authorization' && in_array(true, array_intersect_key($triggers, array_flip(['amount', 'project_concession', 'land_extension', 'forest_concession'])), true)) {
|
||||
$missing = array_values(array_diff($missing, ['investment_form', 'project_concession', 'significant_implications', 'land_extension', 'forest_concession', 'forest_concession_hectares', 'area_required', 'area_unit', 'total_investment']));
|
||||
}
|
||||
$base = $enabled && $covered && $period ? true : null;
|
||||
if (! $enabled || in_array($scope, ['extractive', 'public_nonprofit'], true) || ($date && ! $period)) {
|
||||
$base = false;
|
||||
}
|
||||
$rules = [
|
||||
['identity', 'Identificação do investidor', $base, 'S06', 'R9(1)(a) / R14(1)(a)', 41, 'Identificação do proponente do pedido.'],
|
||||
['registration', 'Certidão de registo comercial', $base === true ? (($f['entity_stage'] ?? '') === 'existing' ? true : (($f['entity_stage'] ?? '') === 'being_formed' ? false : null)) : $base, 'S05', 'R9(1)(b) / R14(1)(b)', 41, 'Alternativa para empresa já registada.'],
|
||||
['name_reservation', 'Reserva da denominação social', $base === true ? (($f['entity_stage'] ?? '') === 'being_formed' ? true : (($f['entity_stage'] ?? '') === 'existing' ? false : null)) : $base, 'S05', 'R9(1)(b) / R14(1)(b)', 41, 'Alternativa para empresa em constituição.'],
|
||||
['site_plan', 'Planta ou esboço do local', $base, 'S06', 'R9(1)(c) / R14(1)(c)', 42, 'Local de implantação identificado; não certifica disponibilidade.'],
|
||||
];
|
||||
foreach (['lease' => 'Contrato de arrendamento', 'duat' => 'Título DUAT'] as $key => $label) {
|
||||
$rules[] = [$key, $label, $base === true ? (($f['site_tenure'] ?? 'unknown') === 'unknown' ? null : ($f['site_tenure'] ?? '') === $key) : $base, 'S06', 'R9(1)(d) / R14(1)(d)', 42, 'Alternativa correspondente à utilização declarada das instalações.'];
|
||||
}
|
||||
$rules[] = ['representation_license', 'Licença de representação comercial', $base === true ? (($f['implementation_mode'] ?? 'unknown') === 'unknown' ? null : ($f['implementation_mode'] ?? '') === 'foreign_representation') : $base, 'S06', 'R9(2)', 42, 'Só para a modalidade representação comercial estrangeira; não decorre da nacionalidade.'];
|
||||
foreach (['feasibility' => 'Estudo de viabilidade técnica e económico-financeira', 'financial_capacity' => 'Comprovação da capacidade financeira'] as $key => $label) {
|
||||
$rules[] = [$key, $label, $base === true ? ($mode === 'indeterminate' ? null : $mode === 'authorization') : $base, 'S02', 'R14(1)–(2)', 45, 'Integra a preparação do pedido de autorização.'];
|
||||
}
|
||||
$rules[] = ['foreign_capital', 'Prova de realização/registo do aporte externo', $base === true ? (($f['capital_origin'] ?? 'unknown') === 'unknown' ? null : in_array($f['capital_origin'] ?? '', ['external', 'mixed'], true)) : $base, 'S06', 'R5(1)–(5)', 39, 'Preparação específica do aporte externo; formalidades cambiais concretas não calculadas.'];
|
||||
$links = $context['preparation_documents'] ?? [];
|
||||
$requirements = [];
|
||||
foreach ($rules as [$key,$label,$applies,$stage,$article,$page,$reason]) {
|
||||
$doc = isset($links[$key]) ? collect($documents)->firstWhere('document_id', $links[$key]) : null;
|
||||
$requirements[] = ['key' => $key, 'label' => $label, 'state' => $applies === false ? 'not_applicable' : ($applies === null ? 'indeterminate' : ($doc ? 'associated' : 'missing')), 'required' => $applies === true, 'document_id' => $links[$key] ?? null, 'document' => $doc, 'stage' => $stage, 'reason' => $reason, 'source' => ['reference' => $article, 'url' => self::SOURCE.'#page='.$page, 'sha256' => self::HASH, 'period' => '2026; Regulamento desde 07/03/2024'], 'legal_verification' => 'not_inferred'];
|
||||
}
|
||||
$authoritySource = ['reference' => 'R13(1)', 'url' => self::SOURCE.'#page=45'];
|
||||
$zone = $context['selection']['park'] ?? null;
|
||||
$amount = $this->number($f, 'total_investment');
|
||||
$authority = 'Por determinar neste lote';
|
||||
if ($base === true && $mode === 'registration' && $amount && ($f['currency'] ?? '') === 'MZN') {
|
||||
$special = in_array($zone['fields']['investment_regime'] ?? '', ['zee', 'zfi'], true);
|
||||
$authority = $special ? ($amount->isLessThanOrEqualTo('6500000000') ? 'APIEX — condicionado ao enquadramento ZEE/ZFI efectivamente reconhecido' : 'Ministro que superintende Finanças') : ($amount->isLessThanOrEqualTo('3500000000') ? 'Governador da Província' : ($amount->isLessThanOrEqualTo('6500000000') ? 'APIEX' : 'Ministro que superintende Finanças'));
|
||||
}
|
||||
if ($base === true && $mode === 'authorization') {
|
||||
$council = array_intersect_key($triggers, array_flip(['amount', 'project_concession', 'land_extension', 'forest_concession']));
|
||||
$authority = in_array(true, $council, true) ? 'Conselho de Ministros' : (in_array(null, $council, true) ? 'Autorização identificada; completar as condições em falta para distinguir a entidade decisória' : 'Ministro que superintende Finanças; eventual submissão ao Conselho de Ministros nos termos do R21(3)');
|
||||
$authoritySource = ['reference' => 'R21(1)–(3)', 'url' => self::SOURCE.'#page=50'];
|
||||
}
|
||||
|
||||
$labels = array_column($this->questions(), 'label', 'key') + ['currency' => 'Moeda do projecto', 'expected_start_date' => 'Data prevista de início', 'entity_stage' => 'Situação da entidade'];
|
||||
$missingLabels = array_map(fn ($key) => $labels[$key] ?? $key, array_values(array_unique($missing)));
|
||||
|
||||
return ['version' => self::VERSION, 'enabled' => $enabled, 'period_covered' => $period, 'scope_covered' => $covered, 'mode' => $mode, 'reason' => $reasons, 'missing_fields' => array_values(array_unique($missing)), 'missing_labels' => $missingLabels, 'questions' => $this->questions(), 'requirements' => $requirements, 'authority' => $authority, 'authority_source' => $authoritySource, 'next' => $base === false ? 'Rever o âmbito/período; este lote não cobre o pedido' : ($mode === 'indeterminate' ? 'Completar condições do enquadramento' : ($mode === 'authorization' ? 'Preparar estudo e documentos do pedido de autorização' : 'Preparar documentos do pedido de mero registo')), 'calculation_notice' => 'O regime procedimental não altera a taxa de IVA. Reutilize a simulação geral apenas no seu âmbito e período; benefícios, apuramento final e conversão cambial não são presumidos.', 'source' => ['url' => self::SOURCE, 'sha256' => self::HASH], 'notice' => 'Preparação informativa baseada em declarações; documentos associados não constituem validação jurídica, certificado ou submissão à Administração.'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Analysis in the existing opportunity draft; publication and private preparation remain separate. */
|
||||
final class ProactiveInvestment
|
||||
{
|
||||
public const VERSION = 1;
|
||||
public const NOTICE = 'A ausência de registo não comprova ausência de oferta. Proximidade não comprova contrato, participação, energia acessível, terra disponível ou benefício fiscal. Necessidade confirmada não comprova viabilidade comercial; hipótese de fornecimento não é encomenda.';
|
||||
public const GROUPS = ['exists' => 'O que existe', 'needs' => 'Necessidades identificadas', 'ideas' => 'Ideias de investimento'];
|
||||
|
||||
public function draft(array $input, ?Opportunity $record = null, ?\App\Models\User $actor = null): array
|
||||
{
|
||||
$d = Validator::make(['proactive' => $input], [
|
||||
'proactive' => 'required|array:version,kind,evidence,need,idea,relations,supply_comparisons', 'proactive.version' => 'required|integer|in:1',
|
||||
'proactive.kind' => 'required|in:exists,needs,ideas', 'proactive.evidence' => 'present|array|max:60',
|
||||
'proactive.evidence.*' => 'array:id,category,purpose,statement,interpretation,source,locator,period,scope,coverage,verified_on,access,document_id,observation_id',
|
||||
'proactive.evidence.*.observation_id'=>'sometimes|nullable|string|size:64',
|
||||
'proactive.supply_comparisons'=>'sometimes|array|max:40',
|
||||
'proactive.evidence.*.id' => 'required|uuid|distinct',
|
||||
'proactive.evidence.*.category' => 'required|in:activity,resource,infrastructure,supply,demand',
|
||||
'proactive.evidence.*.purpose' => 'required|in:local,methodology',
|
||||
'proactive.evidence.*.access' => 'required|in:internal,public',
|
||||
'proactive.evidence.*.document_id' => 'nullable|uuid',
|
||||
'proactive.evidence.*.verified_on' => 'nullable|date_format:Y-m-d|before_or_equal:today',
|
||||
...collect(['statement','interpretation','source','locator','period','scope','coverage'])->mapWithKeys(fn ($k) => ['proactive.evidence.*.'.$k => 'present|nullable|string|max:4000'])->all(),
|
||||
'proactive.need' => 'required|array:state,problem,observed_supply,observed_demand,type,clients,evidence_ids,limitations,missing,confirmation',
|
||||
'proactive.need.state' => 'required|in:hypothesis,confirmed',
|
||||
'proactive.need.type' => 'nullable|in:quantity,quality,logistics,processing,coordination,support',
|
||||
...collect(['problem','observed_supply','observed_demand','clients','limitations','missing','confirmation'])->mapWithKeys(fn ($k) => ['proactive.need.'.$k => 'present|nullable|string|max:6000'])->all(),
|
||||
'proactive.need.evidence_ids' => 'present|array|max:60', 'proactive.need.evidence_ids.*' => 'uuid|distinct',
|
||||
'proactive.idea' => 'required|array:solution,activity,chain_id,stage,coverage,mode,resources,assumptions,conditions,pending,next_action',
|
||||
'proactive.idea.chain_id' => ['nullable','uuid',Rule::exists('value_chains','id')->whereNull('deleted_at')],
|
||||
'proactive.idea.mode' => 'nullable|in:create,expand,associate',
|
||||
...collect(['solution','activity','stage','coverage','resources','assumptions','conditions','pending','next_action'])->mapWithKeys(fn ($k) => ['proactive.idea.'.$k => 'present|nullable|string|max:6000'])->all(),
|
||||
'proactive.relations' => 'present|array|max:40',
|
||||
'proactive.relations.*' => 'array:id,kind,target_id,relation,reference,evidence_ids',
|
||||
'proactive.relations.*.id' => 'required|uuid|distinct',
|
||||
'proactive.relations.*.kind' => 'required|in:project,cluster,corridor,park,chain',
|
||||
'proactive.relations.*.target_id' => 'required|uuid',
|
||||
'proactive.relations.*.relation' => 'required|in:documented,hypothesis,proximity',
|
||||
'proactive.relations.*.reference' => 'required|string|max:4000',
|
||||
'proactive.relations.*.evidence_ids' => 'present|array|max:60', 'proactive.relations.*.evidence_ids.*' => 'uuid|distinct',
|
||||
])->validate()['proactive'];
|
||||
$actor??=auth()->user();
|
||||
if (!empty($d['supply_comparisons'])) $d['supply_comparisons']=app(ProactiveSupply::class)->comparisons($actor,$d['supply_comparisons'],$record);
|
||||
foreach($d['evidence'] as &$proof){
|
||||
if(!empty($proof['observation_id'])){
|
||||
$canonical=app(ProactiveSupply::class)->evidence($actor,$proof['observation_id'],$record);
|
||||
if($proof['access']!=='internal') $this->fail('evidence','A observação da base interna não pode ser reclassificada como pública.');
|
||||
$proof=array_replace($proof,$canonical);
|
||||
}
|
||||
}
|
||||
unset($proof);
|
||||
foreach($d['supply_comparisons']??[] as $comparison){
|
||||
if(!in_array($comparison['observation_id'],array_column($d['evidence'],'observation_id'),true))$this->fail('supply_comparisons','A comparação deve conservar a evidência interna da observação seleccionada.');
|
||||
}
|
||||
$ids = array_column($d['evidence'], 'id');
|
||||
foreach ([$d['need'], ...$d['relations']] as $row) {
|
||||
if (array_diff($row['evidence_ids'], $ids)) $this->fail('evidence', 'Seleccione apenas evidências desta análise.');
|
||||
}
|
||||
$seen = [];
|
||||
foreach ($d['evidence'] as $e) {
|
||||
$key = mb_strtolower(trim(($e['source'] ?? '').'|'.($e['locator'] ?? '').'|'.($e['statement'] ?? '')));
|
||||
if (trim($key, '| ') !== '' && isset($seen[$key])) $this->fail('evidence', 'A mesma evidência já foi registada; edite a entrada existente.');
|
||||
$seen[$key] = true;
|
||||
if (! empty($e['document_id'])) $this->document($record, $e['document_id'], $e['access'] === 'public');
|
||||
}
|
||||
$seen = [];
|
||||
foreach ($d['relations'] as $row) {
|
||||
$target = app(OpportunityClassification::class)->targets($row['kind'])->where('id', $row['target_id'])->exists();
|
||||
if (! $target) $this->fail('relations', 'Referência existente indisponível; não foi criada outra empresa, zona ou estrutura.');
|
||||
$key = $row['kind'].'|'.$row['target_id'];
|
||||
if (isset($seen[$key])) $this->fail('relations', 'A referência já está nesta análise; reúna o fundamento na entrada existente.');
|
||||
$seen[$key] = true;
|
||||
if ($row['relation'] === 'documented' && ! $row['evidence_ids']) $this->fail('relations', 'Relação documentada exige evidência seleccionada; mantenha hipótese ou proximidade quando não demonstrada.');
|
||||
}
|
||||
if ($d['kind'] !== 'exists' && $d['need']['state'] === 'confirmed') {
|
||||
foreach (['problem','observed_supply','observed_demand','type','clients','confirmation'] as $field) {
|
||||
if (trim($d['need'][$field] ?? '') === '') $this->fail('need.'.$field, 'Confirmação exige observação e fundamento concretos; pode guardar como hipótese.');
|
||||
}
|
||||
if (! $d['need']['evidence_ids']) $this->fail('need.evidence_ids', 'Uma hipótese não é confirmada sem evidência seleccionada.');
|
||||
foreach ($d['evidence'] as $e) {
|
||||
if (! in_array($e['id'], $d['need']['evidence_ids'], true)) continue;
|
||||
if ($e['purpose'] !== 'local') $this->fail('need.evidence_ids', 'Uma referência metodológica internacional não confirma oferta ou procura local. Preserve a hipótese e recolha evidência local.');
|
||||
foreach (['statement','source','locator','period','scope','coverage','verified_on'] as $field) {
|
||||
if (trim($e[$field] ?? '') === '') $this->fail('evidence', 'Evidência da necessidade confirmada: faltam facto, fonte, localizador, período, abrangência, cobertura ou data de verificação.');
|
||||
}
|
||||
}
|
||||
}
|
||||
return $d;
|
||||
}
|
||||
|
||||
private function document(?Opportunity $record, string $id, bool $public): void
|
||||
{
|
||||
$row = $record?->exists ? DB::table('opportunity_documents as link')->join('documents as d','d.id','=','link.document_id')
|
||||
->where('link.opportunity_id', $record->id)->where('d.id', $id)->whereNull('link.deleted_at')->first(['d.data_classification','d.status','d.malware_scan_status','d.sha256','d.malware_scanned_sha256','d.rights_status','link.payload','link.deleted_at']) : null;
|
||||
if (! $row) $this->fail('evidence', 'Documento não associado à ficha neste âmbito; reutilize o gestor documental existente.');
|
||||
if ($public && ($row->data_classification !== 'public' || $row->status !== 'active' || $row->malware_scan_status !== 'clean' || $row->sha256 !== $row->malware_scanned_sha256 || $row->rights_status === 'restricted' || data_get(json_decode($row->payload, true), 'visibility') !== 'public')) {
|
||||
$this->fail('evidence', 'Documento interno, restrito ou sem disponibilização pública: preserve a evidência interna, sem a divulgar.');
|
||||
}
|
||||
}
|
||||
|
||||
/** No private field is copied into the public summary automatically. */
|
||||
public function publication(Opportunity $record, array $input): ?array
|
||||
{
|
||||
$private = app(OpportunityManagement::class)->values($record)['proactive'] ?? null;
|
||||
if (! $private) {
|
||||
if (isset($input['proactive_public'])) $this->fail('publication', 'Prepare a análise antes de divulgar esta síntese.');
|
||||
return null;
|
||||
}
|
||||
$d = Validator::make($input, [
|
||||
'proactive_reviewed' => 'required|accepted',
|
||||
'proactive_public' => 'required|array:group,state,need,proposal,basis,limitations,next_action,evidence_ids,chain_id,stage,resources,assumptions,conditions,relation_ids',
|
||||
'proactive_public.group' => 'required|in:exists,needs,ideas',
|
||||
'proactive_public.resources'=>'nullable|string|max:2500', 'proactive_public.assumptions'=>'nullable|string|max:2500', 'proactive_public.conditions'=>'nullable|string|max:2500',
|
||||
'proactive_public.relation_ids'=>'sometimes|array|max:40', 'proactive_public.relation_ids.*'=>'uuid|distinct',
|
||||
'proactive_public.state' => 'required|in:hypothesis,confirmed', 'proactive_public.chain_id' => 'nullable|uuid', 'proactive_public.stage' => 'nullable|string|max:1000',
|
||||
'proactive_public.need'=>'required_unless:proactive_public.group,exists|nullable|string|max:2500', 'proactive_public.proposal'=>'required_if:proactive_public.group,ideas|nullable|string|max:2500',
|
||||
...collect(['basis','limitations','next_action'])->mapWithKeys(fn ($k) => ['proactive_public.'.$k => 'required|string|max:2500'])->all(),
|
||||
'proactive_public.evidence_ids' => 'present|array|max:60', 'proactive_public.evidence_ids.*' => 'uuid|distinct',
|
||||
])->validate()['proactive_public'];
|
||||
$d += ['need'=>'','proposal'=>''];
|
||||
if ($d['group'] !== $private['kind']) $this->fail('publication', 'O grupo público deve corresponder à análise guardada.');
|
||||
$proofs = [];
|
||||
foreach ($d['evidence_ids'] as $id) {
|
||||
$e = collect($private['evidence'])->firstWhere('id', $id);
|
||||
if (! $e || $e['access'] !== 'public') $this->fail('publication', 'Não pode divulgar evidência interna nem a sua fonte indirectamente. Redija uma síntese independente ou seleccione evidência pública autorizada.');
|
||||
if (! empty($e['document_id'])) $this->document($record, $e['document_id'], true);
|
||||
$proofs[] = array_intersect_key($e, array_flip(['id','category','purpose','statement','source','locator','period','scope','coverage','verified_on']));
|
||||
}
|
||||
if ($d['group'] !== 'exists' && $d['state'] === 'confirmed' && ($private['need']['state'] !== 'confirmed' || array_diff($private['need']['evidence_ids'], $d['evidence_ids']))) $this->fail('publication', 'Confirmação pública exige a necessidade confirmada e o fundamento público seleccionado; pode divulgar uma hipótese com limitações explícitas.');
|
||||
if (!empty($d['chain_id']) && !app(OpportunityClassification::class)->targets('chain')->where('id', $d['chain_id'])->exists()) $this->fail('publication', 'Cadeia de valor pública indisponível.');
|
||||
$relations=[];
|
||||
foreach ($d['relation_ids'] ?? [] as $id) {
|
||||
$r=collect($private['relations'])->firstWhere('id',$id);
|
||||
if (!$r || array_diff($r['evidence_ids'],$d['evidence_ids'])) $this->fail('publication','A relação exige o fundamento público seleccionado; nenhuma referência interna é copiada.');
|
||||
$target=app(OpportunityClassification::class)->targets($r['kind'])->where('id',$r['target_id'])->first(['id',OpportunityClassification::TARGETS[$r['kind']][1].' as name']);
|
||||
if (!$target) $this->fail('publication','Referência pública da relação indisponível.');
|
||||
$relations[]=['kind'=>$r['kind'],'target_id'=>$r['target_id'],'label'=>$target->name,'relationship'=>$r['relation'],'evidence_ids'=>$r['evidence_ids'],'basis'=>$d['basis']];
|
||||
}
|
||||
// Catch literal reuse of private statements, interpretations, references and document identities.
|
||||
$publicText = mb_strtolower(implode(' ', [...array_filter($input, 'is_scalar'), ...array_filter($d, 'is_scalar')]));
|
||||
foreach ($private['evidence'] as $e) {
|
||||
if ($e['access'] === 'public') continue;
|
||||
foreach (['statement','interpretation','source','locator','document_id'] as $key) {
|
||||
$value = trim($e[$key] ?? '');
|
||||
if (mb_strlen($value) >= 10 && str_contains($publicText, mb_strtolower($value))) $this->fail('publication', 'O resumo contém informação de evidência interna. Reveja a síntese e a divulgação indirecta antes de publicar.');
|
||||
}
|
||||
}
|
||||
return [...array_map(fn ($v) => is_string($v) ? trim(strip_tags($v)) : $v, $d),
|
||||
'version' => self::VERSION, 'relations'=>$relations, 'evidence' => $proofs, 'notice' => self::NOTICE,
|
||||
'availability_confirmed' => false, 'economic_validation' => false];
|
||||
}
|
||||
|
||||
public function publicData(Opportunity $record): ?array
|
||||
{
|
||||
$p = data_get($record->workflow_context, 'promotional_summary.projection.proactive');
|
||||
return is_array($p) && Opportunity::published()->whereKey($record->id)->exists() ? $p : null;
|
||||
}
|
||||
|
||||
public function publicationRelations(Opportunity $record): array
|
||||
{
|
||||
return collect(app(OpportunityManagement::class)->values($record)['proactive']['relations'] ?? [])->map(function($r){
|
||||
$label=app(OpportunityClassification::class)->targets($r['kind'])->where('id',$r['target_id'])->value(OpportunityClassification::TARGETS[$r['kind']][1]);
|
||||
return $label?['id'=>$r['id'],'label'=>$label,'relationship'=>$r['relation']]:null;
|
||||
})->filter()->values()->all();
|
||||
}
|
||||
|
||||
public function history(?Opportunity $record): array
|
||||
{
|
||||
if (!$record) return [];
|
||||
return DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $record->id)->orderByDesc('occurred_at')->orderByRaw("(after_data->>'version')::integer DESC")->limit(30)->get()->map(function ($event) {
|
||||
$entry=json_decode($event->after_data,true);$snapshot=json_decode(Crypt::decryptString($entry['snapshot']),true);
|
||||
$draft=json_decode($snapshot['management_draft'] ?? '{}',true);$need=$draft['proactive']['need'] ?? null;
|
||||
return $need ? ['at'=>$event->occurred_at,'version'=>$entry['version'],'state'=>$need['state'],'problem'=>$need['problem'],'confirmation'=>$need['confirmation'],'evidence_ids'=>$need['evidence_ids']] : null;
|
||||
})->filter()->values()->all();
|
||||
}
|
||||
|
||||
public function options(?Opportunity $record = null): array
|
||||
{
|
||||
return ['documents' => $record ? DB::table('opportunity_documents as l')->join('documents as d','d.id','=','l.document_id')->where('l.opportunity_id',$record->id)->whereNull('l.deleted_at')->whereNull('d.deleted_at')->get(['d.id','d.file_name as title'])->all() : [], 'groups' => self::GROUPS, 'references' => collect(['project','cluster','corridor','park','chain'])->mapWithKeys(fn ($kind) => [$kind => app(OpportunityClassification::class)->targets($kind)->orderBy(OpportunityClassification::TARGETS[$kind][1])->limit(300)->get(['id', OpportunityClassification::TARGETS[$kind][1].' as name'])])->all()];
|
||||
}
|
||||
|
||||
private function fail(string $key, string $message): never
|
||||
{
|
||||
throw ValidationException::withMessages(['proactive.'.$key => $message]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Internal observations, never a public business directory or proof of demand. */
|
||||
final class ProactiveSupply
|
||||
{
|
||||
public const LIMITATIONS = 'Informação administrativa histórica e incompleta. Actividade actual, capacidade, procura e compromissos por confirmar. Ausência de registos significa informação insuficiente, nunca ausência de oferta.';
|
||||
|
||||
public function authorize(User $actor, ?Opportunity $record = null): void
|
||||
{
|
||||
$access=app(PortalProfileAccess::class);
|
||||
$internal=collect(OpportunityManagement::CATEGORIES)->contains(fn($type)=>$access->internalAssignment($actor,$type)!==null);
|
||||
abort_unless($access->legacyWriteAllowed($actor)||$internal,403);
|
||||
if ($record?->exists) $access->authorize($actor,'view',$record);
|
||||
}
|
||||
|
||||
private function read(User $actor, callable $callback): mixed
|
||||
{
|
||||
return DB::transaction(function()use($actor,$callback){
|
||||
DB::select("select set_config('app.actor_user_id',?,true),set_config('app.proactive_supply_read','internal',true)",[(string)$actor->id]);
|
||||
return $callback();
|
||||
});
|
||||
}
|
||||
|
||||
public function search(User $actor,array $input,?Opportunity $record=null): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
$v=Validator::make($input,[
|
||||
'territory_id'=>['required','uuid',Rule::exists('geo_locations','id')->whereNull('deleted_at')],
|
||||
'activity'=>'nullable|string|max:150','sector'=>'nullable|string|max:250','page'=>'nullable|integer|min:1|max:100000',
|
||||
])->validate();
|
||||
if(!Schema::hasTable('proactive_supply_observations'))return ['installed'=>false,'rows'=>[],'total'=>null,'limitations'=>self::LIMITATIONS,'status'=>'Base interna ainda não carregada neste ambiente.'];
|
||||
return $this->read($actor,function()use($v){
|
||||
$ids=[$v['territory_id']];
|
||||
// Canonical descendants, not a name-only cross-province match.
|
||||
$front=$ids;
|
||||
for($depth=0;$depth<5&&$front;$depth++){
|
||||
$front=DB::table('geo_locations')->whereIn('parent_id',$front)->whereNull('deleted_at')->pluck('id')->all();
|
||||
$ids=[...$ids,...$front];
|
||||
}
|
||||
$base=DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s','s.sha256','=','o.source_hash')->whereIn('o.territory_id',$ids);
|
||||
$sectors=(clone $base)->where('o.sector','<>','')->distinct()->orderBy('o.sector')->pluck('o.sector')->all();
|
||||
if(!empty($v['sector']))$base->where('o.sector',$v['sector']);
|
||||
if(!empty($v['activity']))$base->where(fn($q)=>$q->where('o.cae','ilike','%'.$v['activity'].'%')->orWhereRaw("translate(lower(o.activity),'áàâãéêíóôõúç','aaaaeeiooouc') LIKE ?",['%'.strtolower(\Illuminate\Support\Str::ascii($v['activity'])).'%']));
|
||||
$page=$v['page']??1;
|
||||
// Exact repeated observations are retained in storage, counted separately.
|
||||
$total=(clone $base)->whereNull('o.duplicate_of')->count();
|
||||
$duplicates=(clone $base)->whereNotNull('o.duplicate_of')->count();
|
||||
$rows=(clone $base)->whereNull('o.duplicate_of')->orderBy('o.name')->orderBy('o.id')->offset(($page-1)*25)->limit(25)->get(['o.id','o.entity_key','o.name','o.province','o.district','o.territory_id','o.territory_resolution','o.cae','o.activity','o.sector','o.source_date','o.sheet','o.row_number','o.source_hash','o.identity_conflict','s.name as source_name','s.period as source_period','s.imported_at']);
|
||||
$coverage=DB::table('proactive_supply_observations')->selectRaw("count(*) FILTER (WHERE territory_id IS NULL) AS unmapped, count(*) FILTER (WHERE territory_resolution='province_only_district_unknown') AS province_only")->first();
|
||||
return ['installed'=>true,'rows'=>$rows,'total'=>$total,'duplicate_sightings'=>$duplicates,'page'=>$page,'per_page'=>25,'sectors'=>$sectors,'territory_coverage'=>$coverage,'limitations'=>self::LIMITATIONS,'status'=>$total?'Registos documentais encontrados; não equivalem a empresas únicas ou oferta actual confirmada.':'Informação insuficiente nesta base e nestes filtros.'];
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve server-side source lineage; a caller cannot fabricate an internal observation. */
|
||||
public function comparisons(User $actor,array $input,?Opportunity $record): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
$v=Validator::make(['rows'=>$input],[
|
||||
'rows'=>'array|max:40','rows.*'=>'array:observation_id,relationship,rationale,limitations',
|
||||
'rows.*.observation_id'=>'required|string|size:64|distinct',
|
||||
'rows.*.relationship'=>'required|in:competition,complementarity,partner,uncertain',
|
||||
'rows.*.rationale'=>'required|string|max:4000','rows.*.limitations'=>'required|string|max:4000',
|
||||
])->validate()['rows'];
|
||||
if(!$v)return [];
|
||||
abort_unless(Schema::hasTable('proactive_supply_observations'),422,'Base interna indisponível.');
|
||||
return $this->read($actor,function()use($v){
|
||||
$fingerprints=[];
|
||||
foreach($v as $row){
|
||||
$o=DB::table('proactive_supply_observations')->where('id',$row['observation_id'])->first();
|
||||
if(!$o)throw \Illuminate\Validation\ValidationException::withMessages(['proactive.supply_comparisons'=>'Registo da oferta indisponível; preserve a referência anterior e confira o ambiente.']);
|
||||
if($o->duplicate_of!==null||isset($fingerprints[$o->fingerprint]))throw \Illuminate\Validation\ValidationException::withMessages(['proactive.supply_comparisons'=>'Esta observação administrativa é repetida. Compare a referência original uma única vez; a repetição e a sua fonte permanecem conservadas na base interna.']);
|
||||
$fingerprints[$o->fingerprint]=true;
|
||||
}
|
||||
return $v;
|
||||
});
|
||||
}
|
||||
|
||||
public function evidence(User $actor,string $id,?Opportunity $record): array
|
||||
{
|
||||
$this->authorize($actor,$record);
|
||||
return $this->read($actor,function()use($id){
|
||||
$o=DB::table('proactive_supply_observations as o')->join('proactive_supply_sources as s','s.sha256','=','o.source_hash')->where('o.id',$id)->first(['o.*','s.name as source_name','s.period as source_period']);
|
||||
if(!$o)throw \Illuminate\Validation\ValidationException::withMessages(['proactive.evidence'=>'Observação interna indisponível neste ambiente.']);
|
||||
return ['observation_id'=>$o->id,'category'=>'supply','purpose'=>'local','access'=>'internal','document_id'=>null,
|
||||
'statement'=>'Registo administrativo: '.$o->name.'; CAE '.$o->cae.'; '.($o->activity?:'actividade por classificar').'; '.$o->district.', '.$o->province.'. Não confirma actividade actual.',
|
||||
'source'=>$o->source_name.'; SHA256 '.$o->source_hash,'locator'=>$o->sheet.'!linha '.$o->row_number,
|
||||
'period'=>$o->source_date.'; '.$o->source_period,'scope'=>$o->district.', '.$o->province,
|
||||
'coverage'=>self::LIMITATIONS.($o->identity_conflict?' Identificador partilhado por denominações divergentes: identidade por conferir.':''),
|
||||
];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Publication of notices; never receives bids or changes the linked investment. */
|
||||
final class Procurement
|
||||
{
|
||||
public const TEXT = ['title', 'reference', 'responsible_unit', 'modality', 'object', 'object_kind', 'quantities', 'financier', 'instrument', 'edition', 'rule_source', 'financing_agreement', 'eligibility', 'requirements', 'proposal_validity', 'guarantee_status', 'guarantees', 'delivery_channel', 'delivery_address', 'delivery_url', 'public_contact', 'dissemination', 'origin_url', 'origin_published_at', 'clarifications_at', 'deadline', 'opening_at', 'timezone', 'minimum_source', 'minimum_edition', 'minimum_modality', 'minimum_day_basis', 'result', 'internal_notes', 'public_reason', 'minimum_working_days', 'minimum_holidays', 'minimum_calendar_source'];
|
||||
|
||||
public function available(): bool
|
||||
{
|
||||
return config('procurement.enabled') && Schema::hasTable('portal_tenders');
|
||||
}
|
||||
|
||||
public function access(?User $actor): bool
|
||||
{
|
||||
if (! $actor || ! $actor->hasVerifiedEmail()) {
|
||||
return false;
|
||||
}
|
||||
$docs = app(DocumentManagementAccess::class);
|
||||
|
||||
return ! app(PortalProfileAccess::class)->has($actor, 'auditor') && ($docs->full($actor) || $docs->editorial($actor));
|
||||
}
|
||||
|
||||
public function guard(?User $actor): void
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
abort_unless($this->access($actor), 403, 'Use a autorização editorial já atribuída.');
|
||||
}
|
||||
|
||||
public function references(User $actor): array
|
||||
{
|
||||
$this->guard($actor);
|
||||
$editable = app(DocumentManagementAccess::class)->documents($actor)->select('id');
|
||||
|
||||
return ['regimes' => config('procurement.regimes'), 'acts' => config('procurement.acts'),
|
||||
'organizations' => DB::table('organizations')->whereNull('deleted_at')->orderBy('name')->get(['id', 'name']),
|
||||
'sectors' => DB::table('sectors')->orderBy('name')->get(['id', 'name']),
|
||||
'territories' => app(InvestmentGeography::class)->references(true)->orderBy('name')->get(['id', 'name', 'location_type']),
|
||||
'opportunities' => app(PortalProfileAccess::class)->scope(Opportunity::query(), $actor)->orderBy('title')->get(['id', 'title']),
|
||||
'projects' => DB::table('projects')->whereNull('deleted_at')->whereIn('data_classification', ['internal', 'public'])->orderBy('name')->get(['id', 'name']),
|
||||
'documents' => DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->whereNull('d.deleted_at')
|
||||
->where(fn ($q) => $q->whereIn('d.id', $editable)->orWhere(fn ($p) => $p->where('r.published', true)->where('d.data_classification', 'public')))
|
||||
->orderBy('r.title')->get(['r.id', 'r.title', 'r.published', 'd.malware_scan_status'])];
|
||||
}
|
||||
|
||||
public function record(string $id): object
|
||||
{
|
||||
abort_unless($this->available(), 404);
|
||||
|
||||
return DB::table('portal_tenders')->where('id', $id)->firstOrFail();
|
||||
}
|
||||
|
||||
public function save(User $actor, ?string $id, array $input): string
|
||||
{
|
||||
$this->guard($actor);
|
||||
$v = Validator::make($input, ['version' => 'required|integer|min:0', 'reason' => 'required|string|min:20|max:1000', 'draft' => 'required|array']);
|
||||
$v->validate();
|
||||
$draft = $this->normalize($actor, $input['draft']);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $input, $draft) {
|
||||
$old = $id ? DB::table('portal_tenders')->where('id', $id)->lockForUpdate()->firstOrFail() : null;
|
||||
abort_unless((int) ($old->version ?? 0) === (int) $input['version'], 409, 'A versão mudou; recupere o concurso antes de guardar.');
|
||||
$id ??= (string) Str::uuid();
|
||||
$version = ($old->version ?? 0) + 1;
|
||||
if ($old) {
|
||||
DB::table('portal_tenders')->where('id', $id)->update(['draft' => json_encode($draft, JSON_THROW_ON_ERROR), 'version' => $version, 'updated_at' => now()]);
|
||||
} else {
|
||||
DB::table('portal_tenders')->insert(['id' => $id, 'draft' => json_encode($draft, JSON_THROW_ON_ERROR), 'version' => $version, 'created_by' => $actor->id, 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
$this->version($actor, $id, $version, 'draft', $draft, $input['reason'], false);
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
|
||||
private function normalize(User $actor, array $input): array
|
||||
{
|
||||
$rules = array_fill_keys(self::TEXT, 'nullable|string|max:12000');
|
||||
$rules = [...$rules, 'regime' => 'nullable|in:state,external,private,other', 'organization_id' => 'nullable|uuid|exists:organizations,id',
|
||||
'opportunity_id' => 'nullable|integer|exists:opportunities,id', 'project_id' => 'nullable|uuid|exists:projects,id', 'sector_id' => 'nullable|integer|exists:sectors,id',
|
||||
'territory_id' => 'nullable|uuid|exists:geo_locations,id', 'contact_authorized' => 'boolean', 'minimum_days' => 'nullable|integer|min:0|max:3650',
|
||||
'lots' => 'array|max:100', 'lots.*' => 'array:code,description,quantities', 'lots.*.code' => 'required|string|max:80|distinct', 'lots.*.description' => 'required|string|max:3000', 'lots.*.quantities' => 'nullable|string|max:1500',
|
||||
'attachments' => 'array|max:100', 'attachments.*' => 'array:resource_id,public,purpose', 'attachments.*.resource_id' => 'required|integer|exists:portal_resources,id', 'attachments.*.public' => 'required|boolean', 'attachments.*.purpose' => 'required|string|max:150'];
|
||||
foreach (['origin_url', 'delivery_url', 'rule_source'] as $url) {
|
||||
$rules[$url] = 'nullable|url:http,https|max:2000';
|
||||
}
|
||||
$data = Validator::make($input, $rules)->validate();
|
||||
if (! empty($data['opportunity_id'])) {
|
||||
abort_unless(app(PortalProfileAccess::class)->scope(Opportunity::query(), $actor)->whereKey($data['opportunity_id'])->exists(), 403);
|
||||
}
|
||||
if (! empty($data['project_id'])) {
|
||||
abort_unless(DB::table('projects')->where('id', $data['project_id'])->whereNull('deleted_at')->whereIn('data_classification', ['internal', 'public'])->exists(), 422);
|
||||
}
|
||||
foreach ($data['attachments'] ?? [] as $attachment) {
|
||||
$resource = DB::table('portal_resources')->where('id', $attachment['resource_id'])->firstOrFail();
|
||||
abort_unless($this->publicDocuments()->where('r.id', $resource->id)->exists() || app(DocumentManagementAccess::class)->documents($actor)->where('id', $resource->document_id)->exists(), 403);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function preview(User $actor, string $id, string $act): array
|
||||
{
|
||||
$this->guard($actor);
|
||||
$record = $this->record($id);
|
||||
abort_unless(array_key_exists($act, config('procurement.acts')), 422);
|
||||
$p = json_decode($record->draft, true, 512, JSON_THROW_ON_ERROR);
|
||||
Validator::make($p, array_fill_keys(['title', 'reference', 'organization_id', 'modality', 'object', 'regime', 'instrument', 'edition', 'rule_source', 'origin_published_at', 'deadline', 'delivery_channel', 'timezone'], 'required'))->validate();
|
||||
Validator::make($p, ['timezone' => 'timezone', 'object_kind' => 'nullable|in:works,goods,services,mixed,other', 'guarantee_status' => 'nullable|in:required,not_required,unknown'])->validate();
|
||||
Validator::make($p, ['public_reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
$dates = [];
|
||||
foreach (['origin_published_at', 'clarifications_at', 'deadline', 'opening_at'] as $field) {
|
||||
if (empty($p[$field])) {
|
||||
continue;
|
||||
}
|
||||
$validator = Validator::make([$field => $p[$field]], [$field => 'date_format:Y-m-d\TH:i']);
|
||||
$validator->validate();
|
||||
$dates[$field] = CarbonImmutable::createFromFormat('!Y-m-d\TH:i', $p[$field], $p['timezone']);
|
||||
}
|
||||
$this->require($dates['deadline']->greaterThan($dates['origin_published_at']), 'deadline', 'Entrega anterior à publicação de origem.');
|
||||
if (isset($dates['clarifications_at'])) {
|
||||
$this->require($dates['clarifications_at']->betweenIncluded($dates['origin_published_at'], $dates['deadline']), 'clarifications_at', 'Esclarecimentos fora do período de publicação/entrega.');
|
||||
}
|
||||
if (isset($dates['opening_at'])) {
|
||||
$this->require($dates['opening_at']->greaterThanOrEqualTo($dates['deadline']), 'opening_at', 'A abertura indicada é anterior à entrega.');
|
||||
}
|
||||
if (($p['guarantee_status'] ?? '') === 'required') {
|
||||
$this->require(! empty($p['guarantees']), 'guarantees', 'Descreva a garantia documentada exigida.');
|
||||
}
|
||||
if (isset($p['minimum_days'])) {
|
||||
foreach (['minimum_source', 'minimum_edition', 'minimum_modality', 'minimum_day_basis'] as $field) {
|
||||
$this->require(! empty($p[$field]), $field, 'Identifique fonte, edição, modalidade e contagem do prazo mínimo.');
|
||||
}
|
||||
$this->require($p['minimum_modality'] === $p['modality'], 'minimum_modality', 'A regra indicada pertence a outra modalidade.');
|
||||
$earliest = $dates['origin_published_at'];
|
||||
if ($p['minimum_day_basis'] === 'business') {
|
||||
$this->require(! empty($p['minimum_calendar_source']), 'minimum_calendar_source', 'Identifique a fonte do calendário de dias úteis e feriados.');
|
||||
$weekdays = array_filter(array_map('trim', explode(',', (string) ($p['minimum_working_days'] ?? ''))));
|
||||
$this->require(count($weekdays) > 0 && ! array_diff($weekdays, ['1', '2', '3', '4', '5', '6', '7']), 'minimum_working_days', 'Indique os dias de trabalho documentados (1=segunda, 7=domingo).');
|
||||
$holidays = array_values(array_filter(preg_split('/[\s,;]+/', (string) ($p['minimum_holidays'] ?? ''))));
|
||||
Validator::make(['dates' => $holidays], ['dates' => 'array|max:1000', 'dates.*' => 'date_format:Y-m-d'])->validate();
|
||||
for ($left = (int) $p['minimum_days'],$iterations = 0; $left > 0; $iterations++) {
|
||||
$this->require($iterations < 36500, 'minimum_days', 'Calendário insuficiente para calcular o prazo indicado.');
|
||||
$earliest = $earliest->addDay();
|
||||
if (in_array((string) $earliest->isoWeekday(), $weekdays, true) && ! in_array($earliest->format('Y-m-d'), $holidays, true)) {
|
||||
$left--;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$this->require($p['minimum_day_basis'] === 'calendar', 'minimum_day_basis', 'Identifique dias corridos ou calendário de dias úteis documentado.');
|
||||
$earliest = $earliest->addDays((int) $p['minimum_days']);
|
||||
}
|
||||
$this->require($dates['deadline']->greaterThanOrEqualTo($earliest), 'deadline', 'Prazo inferior ao mínimo documentado para esta modalidade/edição/calendário.');
|
||||
}
|
||||
$previous = $record->published_version_id ? $this->publishedVersion($record->published_version_id) : null;
|
||||
$this->require($previous ? $act !== 'initial' : $act === 'initial', 'act', $previous ? 'O anúncio inicial já existe; publique um acto associado.' : 'Publique primeiro o anúncio inicial.');
|
||||
if ($previous) {
|
||||
$before = $previous['payload'];
|
||||
if (($before['deadline'] ?? '') !== $p['deadline'] || ($before['timezone'] ?? '') !== $p['timezone']) {
|
||||
$this->require($act === 'extension', 'act', 'Uma mudança do prazo exige acto de prorrogação, com data anterior e nova.');
|
||||
}
|
||||
if ($act === 'extension') {
|
||||
$this->require($dates['deadline']->greaterThan(CarbonImmutable::parse($before['deadline'], $before['timezone'])), 'deadline', 'A prorrogação deve avançar o prazo anterior.');
|
||||
$p['deadline_previous'] = $before['deadline'];
|
||||
$p['timezone_previous'] = $before['timezone'];
|
||||
}
|
||||
$p['extended'] = ($before['extended'] ?? false) || $act === 'extension';
|
||||
$p['procedural_state'] = $before['procedural_state'] ?? null;
|
||||
}
|
||||
if ($act === 'award') {
|
||||
$p['procedural_state'] = 'results';
|
||||
}
|
||||
if ($act === 'cancellation') {
|
||||
$p['procedural_state'] = 'cancelled';
|
||||
}
|
||||
if (in_array($act, ['award', 'cancellation', 'other'], true)) {
|
||||
$this->require(! empty($p['result']), 'result', 'Descreva o acto ou resultado documentado.');
|
||||
}
|
||||
$p['organization_name'] = DB::table('organizations')->where('id', $p['organization_id'])->whereNull('deleted_at')->value('name');
|
||||
$this->require((bool) $p['organization_name'], 'organization_id', 'Entidade eliminada; recupere a referência.');
|
||||
$p['sector_name'] = empty($p['sector_id']) ? null : DB::table('sectors')->where('id', $p['sector_id'])->value('name');
|
||||
$p['territory_name'] = empty($p['territory_id']) ? null : app(InvestmentGeography::class)->references(true)->where('id', $p['territory_id'])->value('name');
|
||||
if (! empty($p['territory_id'])) {
|
||||
$this->require((bool) $p['territory_name'], 'territory_id', 'Referência territorial indisponível.');
|
||||
}
|
||||
unset($p['internal_notes']);
|
||||
if (! ($p['contact_authorized'] ?? false)) {
|
||||
unset($p['public_contact']);
|
||||
}
|
||||
$attachments = [];
|
||||
foreach ($p['attachments'] ?? [] as $item) {
|
||||
if (! $item['public']) {
|
||||
continue;
|
||||
}
|
||||
$doc = $this->publicDocuments()->where('r.id', $item['resource_id'])->first(['r.id', 'r.title', 'd.sha256', 'd.id as document_id']);
|
||||
$this->require((bool) $doc, 'attachments', 'Anexo público exige publicação autorizada, scan limpo e direitos sem restrição na biblioteca.');
|
||||
$attachments[] = [...$item, 'title' => $doc->title, 'sha256' => trim($doc->sha256), 'document_id' => $doc->document_id];
|
||||
}
|
||||
$p['attachments'] = $attachments;
|
||||
if (! empty($p['opportunity_id'])) {
|
||||
$o = Opportunity::published()->whereKey($p['opportunity_id'])->first(['id', 'title', 'slug']);
|
||||
$p['opportunity'] = $o ? ['title' => $o->title, 'url' => '/oportunidades/'.$o->slug] : null;
|
||||
}
|
||||
if (! empty($p['project_id'])) {
|
||||
$p['project_name'] = DB::table('projects')->where('id', $p['project_id'])->whereNull('deleted_at')->where('data_classification', 'public')->value('name');
|
||||
}
|
||||
unset($p['opportunity_id'],$p['project_id']);
|
||||
$plan = ['id' => $id, 'version' => $record->version, 'act' => $act, 'payload' => $p];
|
||||
$plan['hash'] = hash_hmac('sha256', json_encode($plan, JSON_THROW_ON_ERROR), config('app.key'));
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
public function publish(User $actor, string $id, array $input): void
|
||||
{
|
||||
$this->guard($actor);
|
||||
Validator::make($input, ['hash' => 'required|string|size:64', 'act' => 'required|string', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||
DB::transaction(function () use ($actor, $id, $input) {
|
||||
$record = DB::table('portal_tenders')->where('id', $id)->lockForUpdate()->firstOrFail();
|
||||
$plan = $this->preview($actor, $id, $input['act']);
|
||||
abort_unless(hash_equals($plan['hash'], $input['hash']), 409, 'Prévia alterada; reveja o conteúdo antes de publicar.');
|
||||
abort_unless($input['reason'] === $plan['payload']['public_reason'], 409, 'O motivo público deve coincidir com a prévia.');
|
||||
$version = $record->version + 1;
|
||||
$vid = $this->version($actor, $id, $version, $input['act'], $plan['payload'], $input['reason'], true);
|
||||
DB::table('portal_tenders')->where('id', $id)->update(['published_version_id' => $vid, 'version' => $version, 'updated_at' => now()]);
|
||||
});
|
||||
}
|
||||
|
||||
private function version(User $actor, string $id, int $version, string $act, array $payload, string $reason, bool $published): string
|
||||
{
|
||||
$vid = (string) Str::uuid();
|
||||
DB::table('portal_tender_versions')->insert(['id' => $vid, 'tender_id' => $id, 'version' => $version, 'act' => $act, 'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'reason' => $reason, 'actor_id' => $actor->id, 'published_at' => $published ? now() : null, 'created_at' => now()]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'procurement', 'entity_type' => 'portal_tenders', 'entity_id' => $id, 'actor_user_id' => $actor->id, 'action' => $published ? 'notice_published' : 'tender_draft_saved', 'data_classification' => 'internal', 'after_data' => json_encode(['version_id' => $vid, 'act' => $act, 'reason' => $reason], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $vid;
|
||||
}
|
||||
|
||||
public function publicDocuments(): Builder
|
||||
{
|
||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.published', true)->where('r.rights_status', '!=', 'restricted')->where('d.rights_status', '!=', 'restricted')->where('d.data_classification', 'public')->where('d.status', 'active')->whereNull('d.deleted_at')->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')
|
||||
->where(fn ($q) => $q->whereNull('d.source_system')->orWhereNotIn('d.source_system', ['opportunity-resources', 'opportunity-image-derivatives']))
|
||||
->whereNotExists(fn ($q) => $q->selectRaw('1')->from('opportunity_documents as od')->whereColumn('od.document_id', 'd.id')->whereRaw("NOT jsonb_exists(COALESCE(od.payload,'{}'::jsonb),'library_source')"))
|
||||
->whereNotExists(fn ($q) => $q->selectRaw('1')->from('opportunity_images as oi')->whereColumn('oi.document_id', 'd.id')->whereRaw("NOT jsonb_exists(COALESCE(oi.payload,'{}'::jsonb),'library_source')"));
|
||||
}
|
||||
|
||||
public function publishedVersion(string $id): array
|
||||
{
|
||||
$v = DB::table('portal_tender_versions')->where('id', $id)->whereNotNull('published_at')->firstOrFail();
|
||||
$p = json_decode($v->payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach ($p['attachments'] ?? [] as $i => $item) {
|
||||
$p['attachments'][$i]['available'] = $this->publicDocuments()->where('r.id', $item['resource_id'])->where('d.id', $item['document_id'])->where('d.sha256', $item['sha256'])->exists();
|
||||
}
|
||||
|
||||
return ['id' => $v->id, 'version' => $v->version, 'act' => $v->act, 'payload' => $p, 'published_at' => $v->published_at, 'reason' => $v->reason];
|
||||
}
|
||||
|
||||
public function state(array $version): string
|
||||
{
|
||||
$p = $version['payload'];
|
||||
if (in_array($p['procedural_state'] ?? '', ['cancelled', 'results'], true)) {
|
||||
return $p['procedural_state'];
|
||||
}
|
||||
if (CarbonImmutable::parse($p['deadline'], $p['timezone'])->isPast()) {
|
||||
return 'deadline_ended';
|
||||
}
|
||||
|
||||
return ($p['extended'] ?? false) ? 'extended' : 'open';
|
||||
}
|
||||
|
||||
private function require(bool $condition, string $field, string $message): void
|
||||
{
|
||||
if (! $condition) {
|
||||
throw ValidationException::withMessages([$field => $message]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,22 +34,22 @@ final class SectorInvestment
|
||||
return [...$sector->only(['id', 'name', 'slug']), 'href' => SectorOrganization::href($sector->slug)];
|
||||
}
|
||||
|
||||
/** Public detail shared by the catalogue and the individual sector page. */
|
||||
public function page(Sector $sector): array
|
||||
{
|
||||
return [
|
||||
'sector' => $sector->only(['id', 'name', 'slug', 'description', 'short_description']),
|
||||
'sectorEntry' => $this->publicView($sector),
|
||||
'opportunities' => SectorOrganization::opportunities($sector)->latest('published_at')
|
||||
->limit(12)->get(['id', 'title', 'slug', 'province', 'summary']),
|
||||
];
|
||||
}
|
||||
|
||||
public function publicView(Sector $sector): array
|
||||
{
|
||||
$creation = app(ContentManagement::class)->access(request()->user())['opportunities']['create'] ?? null;
|
||||
$query = SectorOrganization::opportunities($sector);
|
||||
$articles = [];
|
||||
if (app(LegacyContent::class)->available()) {
|
||||
foreach (self::CONTENT[$sector->slug] ?? [] as $slug) {
|
||||
try {
|
||||
$a = app(LegacyContent::class)->article($slug);
|
||||
$articles[] = ['title' => $a['title'], 'href' => $a['href'], 'image' => $a['image'], 'sha256' => $a['sha256'], 'scope' => $slug === 'tech-fintech' && $sector->slug !== 'fintech' ? 'Especialização Fintech; não representa todo o setor.' : 'Conteúdo educativo relacionado; não é uma oportunidade concreta.'];
|
||||
} catch (HttpException $e) {
|
||||
if ($e->getStatusCode() !== 404) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$articles = $this->guides($sector);
|
||||
$relations = [];
|
||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $table => $foreign) {
|
||||
$ids = DB::table('opportunity_'.$table)->whereIn('opportunity_id', (clone $query)->select('id'))->pluck($foreign);
|
||||
@@ -68,12 +68,33 @@ final class SectorInvestment
|
||||
return ['articles' => $articles, 'relations' => collect($relations)->unique('id')->values()->all(), 'locations' => $locations,
|
||||
'start_href' => app(InvestorPath::class)->available() ? '/investimentos/a-partir-do-setor/'.$sector->slug : null,
|
||||
'start_notice' => app(InvestorPath::class)->available() ? null : 'O percurso para guardar a ideia está temporariamente indisponível. A consulta e o apoio continuam disponíveis.',
|
||||
'register_href' => app(PortalProfileAccess::class)->available() ? '/minhas-oportunidades/create?sector_id='.$sector->id : null,
|
||||
'register_href' => app(PortalProfileAccess::class)->available() ? ($creation ? $creation.'?sector_id='.$sector->id : '/perfil/promotor') : null,
|
||||
'register_label' => $creation ? 'Cadastrar oportunidade — escolher modalidade' : 'Pedir acesso para cadastrar oportunidades',
|
||||
'register_notice' => app(PortalProfileAccess::class)->available() ? null : 'O cadastro por perfis está temporariamente indisponível; pode preparar a ideia e contactar o apoio.',
|
||||
'specialization_href' => in_array($sector->slug, ['tecnologias-de-informacao', 'mercado-financeiro'], true) ? SectorOrganization::href('fintech') : null,
|
||||
'content_notice' => $sector->slug === 'mercado-financeiro' ? 'O artigo geral de Mercado Financeiro permanece vazio e não foi publicado. A preparação de negócios neste setor está disponível.' : null];
|
||||
}
|
||||
|
||||
/** Published guides for an explicit sector; never inferred from proximity. */
|
||||
public function guides(?Sector $sector): array
|
||||
{
|
||||
if (! $sector) return [];
|
||||
$articles = [];
|
||||
if (app(LegacyContent::class)->available()) {
|
||||
foreach (self::CONTENT[$sector->slug] ?? [] as $slug) {
|
||||
try {
|
||||
$a = app(LegacyContent::class)->article($slug, false);
|
||||
$articles[] = \Illuminate\Support\Arr::only($a, ['title', 'href', 'image', 'sha256', 'summary', 'author', 'opportunities_href', 'opportunities_label', 'has_opportunities']);
|
||||
} catch (HttpException $e) {
|
||||
if ($e->getStatusCode() !== 404) {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $articles;
|
||||
}
|
||||
|
||||
public function attach(User $actor, string $id, array $input): void
|
||||
{
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'sector_slug' => 'required|string|max:150'])->validate();
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Services;
|
||||
|
||||
use App\Jobs\RunSimulation;
|
||||
use App\Models\Simulation;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -17,15 +18,39 @@ final class SimulationExecution
|
||||
*/
|
||||
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'], 'scenario_kind' => 'custom_planning', 'organization_id' => $organizationId];
|
||||
|
||||
return $this->createPayload($payload, $actorId, $organizationId, $token, $key);
|
||||
}
|
||||
|
||||
public function createFiscalQaPreview(array $snapshot, int $actorId, string $key): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
abort_unless(($snapshot['scenario_kind'] ?? null) === 'fiscal_rule_qa_preview'
|
||||
&& in_array($snapshot['result']['status'] ?? null, ['calculated', 'indeterminate'], true)
|
||||
&& ($snapshot['presentation']['rounding_applied'] ?? null) === false, 422);
|
||||
|
||||
return $this->createPayload(['scenario_kind' => 'fiscal_rule_qa_preview', 'fiscal_preview' => $snapshot, 'organization_id' => null],
|
||||
$actorId, null, null, $key);
|
||||
}
|
||||
|
||||
public function createPublishedFiscal(array $input, ?int $actorId, ?string $organizationId, ?string $token, string $key): array
|
||||
{
|
||||
$payload = ['scenario_kind' => 'fiscal_rule_published', 'fiscal_input' => $input, 'organization_id' => $organizationId];
|
||||
|
||||
return $this->createPayload($payload, $actorId, $organizationId, $token, $key,
|
||||
fn (): array => app(SimulationPublishedFiscal::class)->admit($input));
|
||||
}
|
||||
|
||||
private function createPayload(array $payload, ?int $actorId, ?string $organizationId, ?string $token, string $key, ?callable $admit = null): array
|
||||
{
|
||||
$tokenHash = $actorId === null ? hash_hmac('sha256', (string) $token, (string) config('app.key')) : null;
|
||||
$scopeHash = hash('sha256', $actorId !== null ? (string) $actorId : ($tokenHash ?? 'anonymous'));
|
||||
$keyHash = hash('sha256', strtolower($key));
|
||||
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 {
|
||||
return DB::transaction(function () use ($actorId, $organizationId, $token, $tokenHash, $scopeHash, $keyHash, $payloadHash, $payload, $admit): 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();
|
||||
@@ -37,6 +62,10 @@ final class SimulationExecution
|
||||
return ['simulation' => Simulation::with(['scenarios', 'reports'])->whereKey((string) $receipt->simulation_id)->firstOrFail(), 'token' => null, 'replayed' => true];
|
||||
}
|
||||
|
||||
if ($admit !== null) {
|
||||
$payload['fiscal_preview'] = $admit();
|
||||
}
|
||||
|
||||
$plainToken = $actorId === null ? $token : null;
|
||||
$tokenHash = $actorId === null ? hash_hmac('sha256', $plainToken, (string) config('app.key')) : null;
|
||||
$this->setContext($actorId, $tokenHash);
|
||||
@@ -44,7 +73,9 @@ final class SimulationExecution
|
||||
$simulation = Simulation::create([
|
||||
'id' => $id, 'questionnaire_version_id' => '61000100-0000-4000-8000-000000000001', 'owner_user_id' => $actorId, 'organization_id' => $organizationId,
|
||||
'anonymous_token_hash' => $tokenHash, 'status' => 'queued', 'version_no' => 1,
|
||||
'input_snapshot' => $payload, 'calculation_snapshot' => ['engine' => 'portal-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
|
||||
'input_snapshot' => $payload, 'calculation_snapshot' => in_array($payload['scenario_kind'], ['fiscal_rule_qa_preview', 'fiscal_rule_published'], true)
|
||||
? ['engine' => $payload['fiscal_preview']['context']['engine_version'], 'mode' => $payload['fiscal_preview']['fiscal_provenance']['mode'], 'arithmetic' => 'exact_decimal_no_rounding']
|
||||
: ['engine' => 'portal-arithmetic-v1', 'formula' => 'base * rate / 100 * (1 - reduction / 100)', 'legal_rate_source' => null],
|
||||
]);
|
||||
$scenarioId = (string) Str::uuid();
|
||||
DB::table('simulation_scenarios')->insert([
|
||||
@@ -85,6 +116,8 @@ final class SimulationExecution
|
||||
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);
|
||||
abort_if(in_array($simulation->input_snapshot['scenario_kind'] ?? null, ['fiscal_rule_qa_preview', 'fiscal_rule_published'], true), 422,
|
||||
'Crie uma nova pré-visualização fiscal; este snapshot conserva a regra e as entradas originais.');
|
||||
$this->requireMatch($request, $simulation);
|
||||
$scenario = DB::table('simulation_scenarios')->where('simulation_id', $id)->where('id', $scenarioId)->lockForUpdate()->first();
|
||||
abort_if($scenario === null, 404);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\User;
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Exact operation-level IVA calculation against an explicit QA draft; never a payment/return total. */
|
||||
final class SimulationFiscalQaPreview
|
||||
{
|
||||
public function create(User $actor, string $ruleId, array $input, string $key): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
|
||||
return DB::transaction(function () use ($actor, $ruleId, $input, $key): array {
|
||||
$rule = app(SimulationTaxRuleGovernance::class)->show($actor, $ruleId);
|
||||
abort_unless($rule->status === 'draft' && $rule->rule_code === 'IVA-GERAL-BASE-LIQUIDA', 422,
|
||||
'Seleccione o rascunho do primeiro lote fiscal.');
|
||||
abort_if(collect($rule->rule_definition['nodes'] ?? [])->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
|
||||
'Este percurso preserva o valor exacto e não aplica arredondamento automático.');
|
||||
$source = InvestmentLegalSource::findOrFail($rule->legal_source_id);
|
||||
$version = $rule->attributesToArray();
|
||||
$version['source'] = $source->attributesToArray();
|
||||
$date = $input['reference_date'];
|
||||
$context = ['operation' => $input['operation'], 'currency' => $input['currency']];
|
||||
$missing = [];
|
||||
$resolution = [];
|
||||
$evaluation = null;
|
||||
if ($date < '2026-01-01' || $date > '2026-12-31') {
|
||||
$missing[] = 'demonstrated_coverage';
|
||||
} else {
|
||||
$resolution = app(SimulationTaxParameterResolver::class)->resolveDraftForQa([$version], 'IVA', $date, $date, $context);
|
||||
$rate = collect($resolution)->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
|
||||
if (($rate['status'] ?? null) !== 'resolved' || ($rate['unit'] ?? null) !== 'percent') {
|
||||
$missing[] = 'eligible_parameter';
|
||||
} else {
|
||||
$evaluation = app(SimulationTaxRuleExpression::class)->evaluate($rule->rule_definition,
|
||||
['base_tributavel' => $input['base']], ['iva_general_rate' => $rate['value']]);
|
||||
}
|
||||
}
|
||||
$snapshot = app(SimulationFiscalSnapshot::class)->build($version, $input, $resolution, $evaluation, $missing);
|
||||
|
||||
return app(SimulationExecution::class)->createFiscalQaPreview($snapshot, $actor->id, $key);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Brick\Math\BigRational;
|
||||
|
||||
/** Shared snapshot representation; eligibility is resolved by each admission adapter. */
|
||||
final class SimulationFiscalSnapshot
|
||||
{
|
||||
public function build(array $version, array $input, array $resolution, ?array $evaluation, array $missing, bool $published = false): array
|
||||
{
|
||||
$date = $input['reference_date'];
|
||||
$context = ['operation' => $input['operation'], 'currency' => $input['currency']];
|
||||
$exact = ($evaluation['status'] ?? null) === 'determinate'
|
||||
? (string) BigRational::of($evaluation['result'])->toBigDecimal()
|
||||
: null;
|
||||
if ($exact === null && $missing === []) {
|
||||
$missing = $evaluation['missing'] ?? ['eligible_parameter'];
|
||||
}
|
||||
$snapshot = [
|
||||
'contract_version' => 1, 'scenario_kind' => $published ? 'fiscal_rule_published' : 'fiscal_rule_qa_preview',
|
||||
'base' => $input['base'], 'currency' => $input['currency'], 'indicative_total' => $exact,
|
||||
'legal_interpretation' => false, 'formula_version' => 'investmoz.tax.v1',
|
||||
'context' => [
|
||||
'reference_date' => $date, 'currency' => $input['currency'], 'currency_fraction_digits' => 2,
|
||||
'scenario_id' => null, 'scenario_version' => 1, 'engine_version' => $published ? 'fiscal-published-v1' : 'fiscal-draft-preview-v1',
|
||||
'ruleset_version' => $version['rule_code'].':'.$version['rule_version'],
|
||||
],
|
||||
'result' => [
|
||||
'status' => $exact === null ? 'indeterminate' : 'calculated', 'value' => $exact, 'unit' => 'MZN',
|
||||
'explanation' => $exact === null
|
||||
? 'IVA indeterminado: o contexto, a fonte ou o período não permitem resolver o parâmetro deste lote QA.'
|
||||
: 'IVA calculado com precisão decimal exacta, sem arredondamento. Ensaio QA de regra em rascunho; enquadramento declarado, não validado. Não é saldo de declaração nem valor a pagar.',
|
||||
'missing_inputs' => $missing, 'source_ids' => [(string) $version['legal_source_id']],
|
||||
],
|
||||
'presentation' => ['value' => $exact, 'currency' => $input['currency'], 'rounding_applied' => false, 'purpose' => 'operation_tax_not_payment'],
|
||||
// Exact rational steps supplement the decimal result; no float conversion.
|
||||
'intermediate' => $evaluation,
|
||||
'fiscal_provenance' => [
|
||||
'mode' => $published ? 'published_version' : 'qa_draft_only', 'scope_status' => ($input['scope_declared'] ?? true) ? 'user_declared' : 'undetermined', 'context' => $context,
|
||||
'rounding_policy' => $version['rounding_policy'], 'resolution' => $resolution,
|
||||
'rule' => $version, 'source_acceptance' => 'Fonte oficial aceite pela decisão Tempo de 08/10/2026; não constitui aprovação jurídica desta operação ou publicação da regra.',
|
||||
],
|
||||
];
|
||||
|
||||
if ($published) {
|
||||
$snapshot['result']['explanation'] = $exact === null
|
||||
? 'IVA indeterminado: falta contexto, fonte ou parâmetro elegível para esta operação.'
|
||||
: 'IVA calculado pela versão publicada identificada, sem arredondamento. Enquadramento declarado, não validado. Não é saldo de declaração nem valor a pagar.';
|
||||
$snapshot['fiscal_provenance']['admitted_at'] = now()->toISOString();
|
||||
$snapshot['fiscal_provenance']['source_acceptance'] = 'Fonte oficial aceite pela Tempo em 08/10/2026; não constitui validação jurídica desta operação.';
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
final class SimulationFiscalSourceAcceptance
|
||||
{
|
||||
public static function eligible(array $source, ?string $hash = null): bool
|
||||
{
|
||||
if (($source['validation_status'] ?? null) === 'validated') {
|
||||
return true;
|
||||
}
|
||||
$basis = $source['fiscal_acceptance'] ?? null;
|
||||
|
||||
return ($source['validation_status'] ?? null) === 'pending' && is_array($basis)
|
||||
&& ($basis['scope'] ?? null) === 'fiscal_parameters'
|
||||
&& ($basis['basis'] ?? null) === 'Tempo-official-sources-20261008'
|
||||
&& preg_match('/^[a-f0-9]{64}$/D', (string) ($basis['sha256'] ?? '')) === 1
|
||||
&& ($hash === null || $basis['sha256'] === $hash);
|
||||
}
|
||||
}
|
||||
@@ -60,9 +60,11 @@ final class SimulationFormDrafts
|
||||
throw new HttpException(409, 'Já existe um rascunho activo. Carregue-o antes de guardar novas alterações.');
|
||||
}
|
||||
|
||||
if ($case) $data['economic_snapshot'] = $this->landContext($data['economic_snapshot'], $case);
|
||||
$snapshotHash = hash('sha256', json_encode($this->canonical($data), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
$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,
|
||||
'version_no' => 1, 'create_key_hash' => $keyHash, 'create_payload_hash' => $payloadHash, 'snapshot_sha256' => $snapshotHash,
|
||||
'personal_snapshot' => SimulationFormDraft::encryptSnapshot($data['personal_snapshot']),
|
||||
'economic_snapshot' => SimulationFormDraft::encryptSnapshot($data['economic_snapshot']),
|
||||
'expires_at' => $actorId === null ? now()->addDays(30) : null,
|
||||
@@ -89,6 +91,7 @@ final class SimulationFormDrafts
|
||||
$this->checkContext($request, $draft);
|
||||
$this->requireMatch($request, $draft);
|
||||
$previousEconomic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
$data['economic_snapshot'] = $this->preserveInactiveLandStatus($draft, $data['economic_snapshot'], $previousEconomic, $actorId);
|
||||
if (($data['economic_snapshot']['reuse_simulation'] ?? null) === 'no') {
|
||||
unset($data['economic_snapshot']['simulation_sources']);
|
||||
} elseif (is_array($previousEconomic['simulation_sources'] ?? null)) {
|
||||
@@ -456,6 +459,39 @@ final class SimulationFormDrafts
|
||||
return $query;
|
||||
}
|
||||
|
||||
private function preserveInactiveLandStatus(SimulationFormDraft $draft, array $economic, array $previous, ?int $actorId): array
|
||||
{
|
||||
if (! $actorId || ! config('investor-path.enabled') || ! app(VirtualDesk::class)->installed()) return $economic;
|
||||
// Use the real owner-bound dossier even if a request omits its context parameter.
|
||||
$case = DB::table('desk_cases')->where('simulation_id', $draft->id)->where('user_id', $actorId)->first();
|
||||
if (! $case) return $economic;
|
||||
return $this->landContext($economic, $case, $previous);
|
||||
}
|
||||
|
||||
private function landContext(array $economic, \stdClass $case, ?array $previous = null): array
|
||||
{
|
||||
$snapshot = json_decode($economic['context_applicability_snapshot'] ?? $previous['context_applicability_snapshot'] ?? '', true);
|
||||
$key = $economic['context_opportunity'] ?? $snapshot['consumer_opportunity'] ?? null;
|
||||
$key = app(InvestmentConsumerScope::class)->key(app(InvestorContext::class)->state($case), is_string($key) ? $key : null);
|
||||
$decision = app(InvestorContext::class)->landPreparation($case, $key);
|
||||
if ($decision['need'] !== 'yes' && $previous !== null) {
|
||||
if (array_key_exists('land_status', $previous)) $economic['land_status'] = $previous['land_status'];
|
||||
else unset($economic['land_status']);
|
||||
if (isset($previous['selection_labels']['land_status'])) $economic['selection_labels']['land_status'] = $previous['selection_labels']['land_status'];
|
||||
else unset($economic['selection_labels']['land_status']);
|
||||
}
|
||||
$snapshot = json_decode($economic['context_applicability_snapshot'] ?? $previous['context_applicability_snapshot'] ?? '', true);
|
||||
if (! is_array($snapshot) || ($snapshot['version'] ?? null) !== 1) {
|
||||
$snapshot = ['version' => 1, 'context_revision' => app(InvestorContext::class)->state($case)['revision']];
|
||||
}
|
||||
$snapshot['land_preparation'] = $decision;
|
||||
$snapshot['consumer_opportunity'] = $key;
|
||||
if ($key) $economic['context_opportunity'] = $key;
|
||||
$economic['context_applicability_snapshot'] = json_encode($snapshot, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
return $economic;
|
||||
}
|
||||
|
||||
private function checkContext(Request $request, SimulationFormDraft $draft): void
|
||||
{
|
||||
$context = $request->input('context');
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Explains a failed selection; never changes answers, eligibility or calculation. */
|
||||
final class SimulationIvaDiagnostics
|
||||
{
|
||||
public function explain(array $versions, string $start, string $end, array $context): array
|
||||
{
|
||||
$diagnostics = [];
|
||||
foreach ($versions as $version) {
|
||||
$parameter = $version['parameters']['IVA_GENERAL_RATE'] ?? null;
|
||||
if (! is_array($parameter)) {
|
||||
continue;
|
||||
}
|
||||
$issues = [];
|
||||
$add = function (string $category, ?string $field, string $label, mixed $received, string $expected, string $message) use (&$issues): void {
|
||||
$issues[] = compact('category', 'field', 'label', 'received', 'expected', 'message');
|
||||
};
|
||||
if ($start < $version['valid_from'] || ($version['valid_until'] !== null && $end > $version['valid_until'])) {
|
||||
$add('period_unavailable', 'fiscal_period', 'Período', "$start a $end", $version['valid_from'].' a '.($version['valid_until'] ?? 'sem data final indicada'), 'Esta versão da regra não abrange todo o período seleccionado. Não altere a data real da operação para obter um resultado.');
|
||||
}
|
||||
foreach ($parameter['conditions'] ?? [] as $key => $expected) {
|
||||
$received = $context[$key] ?? null;
|
||||
if ($received === $expected) {
|
||||
continue;
|
||||
}
|
||||
if ($key === 'currency') {
|
||||
$category = $received === null || $received === '' ? 'missing_field' : (preg_match('/^[A-Z]{3}$/D', $received) ? 'out_of_scope' : 'invalid_value');
|
||||
$add($category, 'fiscal_currency', 'Moeda', $received, $expected, $category === 'missing_field' ? 'Indique a moeda da operação.' : 'Esta versão aceita apenas '.$expected.'. Reveja a moeda ou utilize um cálculo adequado à operação; a resposta não foi alterada.');
|
||||
} elseif ($key === 'operation' && ! array_key_exists('operation', $context) && $expected === 'internal_general_net' && in_array($context['fiscal_operation'] ?? null, ['import', 'export', 'non_resident', 'refund'], true)) {
|
||||
$add('out_of_scope', 'fiscal_operation', 'Operação', $context['fiscal_operation'], 'Operação interna à taxa geral, sobre base líquida já apurada', 'A operação declarada está excluída desta versão. Utilize um cálculo adequado à operação; não altere a resposta para obter um resultado.');
|
||||
} elseif ($key === 'operation' && ! array_key_exists('operation', $context)) {
|
||||
$add('system_configuration', 'fiscal_operation', 'Operação', $context['fiscal_operation'] ?? null, $expected === 'internal_general_net' ? 'Operação interna à taxa geral, sobre base líquida já apurada' : $expected, 'Limitação de integração do sistema: esta consulta não comunica o enquadramento específico exigido pela versão. A resposta genérica não permite inferi-lo. Utilize o formulário IVA — taxa geral, com declaração explícita do âmbito; não altere respostas para forçar compatibilidade.');
|
||||
} elseif ($key === 'operation') {
|
||||
$add($received === null || $received === '' ? 'missing_field' : 'out_of_scope', 'fiscal_operation', 'Operação', $received, $expected === 'internal_general_net' ? 'Operação interna à taxa geral, sobre base líquida já apurada' : $expected, 'A operação não está abrangida por esta versão; utilize um cálculo adequado à operação declarada.');
|
||||
} else {
|
||||
$add('system_configuration', null, 'Configuração da regra', null, 'Condições publicadas ligadas a campos deste formulário', 'O sistema não consegue relacionar todas as condições desta versão com o formulário. Não é uma falha das suas respostas.');
|
||||
}
|
||||
}
|
||||
if (! SimulationFiscalSourceAcceptance::eligible($version['source'] ?? [], $version['source_sha256'] ?? null)
|
||||
|| ($version['source_version_no'] ?? null) !== ($version['source']['version_no'] ?? null)
|
||||
|| ($version['rule_definition']['language'] ?? null) !== 'investmoz.tax.v1') {
|
||||
$add('system_configuration', null, 'Regra', null, 'Versão publicada com fonte e configuração coerentes', 'A configuração ou a fonte da regra não permite resolver este parâmetro. Não altere as respostas; é necessária correcção do sistema.');
|
||||
}
|
||||
if ($issues !== []) {
|
||||
$source = array_intersect_key($version['source'] ?? [], array_flip(['title', 'diploma', 'article', 'url']));
|
||||
$diagnostics[] = ['label' => 'IVA — taxa geral', 'rule_version' => $version['rule_version'], 'validity' => ['start' => $version['valid_from'], 'end' => $version['valid_until']], 'source' => $source, 'issues' => $issues];
|
||||
}
|
||||
}
|
||||
|
||||
return $diagnostics;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\SimulationTaxRuleVersion;
|
||||
use Brick\Math\BigRational;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Admission freezes eligibility without granting the public consumer governance write access. */
|
||||
final class SimulationPublishedFiscal
|
||||
{
|
||||
public function availability(): array
|
||||
{
|
||||
$enabled = (bool) config('simulation-fiscal-consumer.enabled');
|
||||
$eligible = $enabled && $this->boundRule()->where('status', 'published')->exists();
|
||||
|
||||
return ['enabled' => $eligible, 'coverage_start' => '2026-01-01', 'coverage_end' => '2026-12-31',
|
||||
'message' => $eligible ? 'IVA geral sobre base líquida disponível; enquadramento declarado.'
|
||||
: 'O cálculo de IVA geral sobre base líquida está indisponível para novas execuções. Os históricos mantêm-se acessíveis.'];
|
||||
}
|
||||
|
||||
private function boundRule(): Builder
|
||||
{
|
||||
if (! Str::isUuid((string) config('simulation-fiscal-consumer.rule_id')) || config('simulation-fiscal-consumer.rule_version') < 1) {
|
||||
return SimulationTaxRuleVersion::query()->whereRaw('false');
|
||||
}
|
||||
|
||||
return SimulationTaxRuleVersion::query()->whereKey(config('simulation-fiscal-consumer.rule_id'))
|
||||
->where('rule_version', config('simulation-fiscal-consumer.rule_version'))
|
||||
->where('rule_code', 'IVA-GERAL-BASE-LIQUIDA')->where('component', 'IVA')
|
||||
->where('scope_key', 'mz.internal-general-net.mzn');
|
||||
}
|
||||
|
||||
public function admit(array $input, bool $missingBase = false): array
|
||||
{
|
||||
if (isset($input['monthly_sales'])) {
|
||||
return $this->admitMonthly($input);
|
||||
}
|
||||
// Called inside createPayload, after idempotent replay, never by the worker.
|
||||
abort_unless(DB::transactionLevel() > 0, 500);
|
||||
abort_unless(config('simulation-fiscal-consumer.enabled'), 503,
|
||||
'O cálculo de IVA está temporariamente indisponível. Os dados e históricos foram preservados.');
|
||||
DB::select('select pg_advisory_xact_lock_shared(261021, hashtext(?))', [(string) config('simulation-fiscal-consumer.rule_id')]);
|
||||
$rule = $this->boundRule()->first();
|
||||
abort_unless($rule && $rule->status === 'published', 503,
|
||||
'A versão autorizada de IVA não está disponível para novas execuções. Os históricos foram preservados.');
|
||||
abort_if($input['reference_date'] < '2026-01-01' || $input['reference_date'] > '2026-12-31', 422,
|
||||
'Este cálculo abrange apenas exigibilidade em 2026. As entradas foram preservadas.');
|
||||
abort_if(collect($rule->rule_definition['nodes'] ?? [])->contains(fn (array $node): bool => ($node['op'] ?? null) === 'round'), 422,
|
||||
'A versão seleccionada não é compatível com o cálculo exacto deste consumidor.');
|
||||
DB::select('select pg_advisory_xact_lock_shared(261022, hashtext(?))', [(string) $rule->legal_source_id]);
|
||||
$source = InvestmentLegalSource::whereKey($rule->legal_source_id)->firstOrFail();
|
||||
// Publish calculation provenance, not private governance notes or staff identifiers.
|
||||
$version = array_intersect_key($rule->attributesToArray(), array_flip([
|
||||
'id', 'rule_code', 'rule_version', 'component', 'scope_key', 'status', 'valid_from', 'valid_until',
|
||||
'legal_source_id', 'source_version_no', 'source_sha256', 'rule_definition', 'parameters', 'rounding_policy',
|
||||
]));
|
||||
$version['source'] = array_intersect_key($source->attributesToArray(), array_flip([
|
||||
'id', 'title', 'url', 'diploma', 'article', 'competent_entity', 'valid_from', 'valid_until', 'validation_status', 'version_no',
|
||||
]));
|
||||
$resolution = app(SimulationTaxParameterResolver::class)->resolvePublishedForPeriod('IVA',
|
||||
$input['reference_date'], $input['reference_date'], ['currency' => $input['currency'], 'operation' => $input['operation']]);
|
||||
$rate = collect($resolution)->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
|
||||
$missing = [];
|
||||
if ($missingBase) {
|
||||
$missing[] = 'taxable_sales';
|
||||
}
|
||||
$evaluation = null;
|
||||
if (! ($input['scope_declared'] ?? false)) {
|
||||
$missing[] = 'operation_scope';
|
||||
}
|
||||
if (($rate['status'] ?? null) !== 'resolved' || ($rate['unit'] ?? null) !== 'percent'
|
||||
|| ($rate['rule_id'] ?? null) !== (string) $rule->id
|
||||
|| (int) ($rate['rule_version'] ?? 0) !== (int) $rule->rule_version) {
|
||||
$missing[] = 'eligible_parameter';
|
||||
}
|
||||
if ($missing === []) {
|
||||
$evaluation = app(SimulationTaxRuleExpression::class)->evaluate($rule->rule_definition,
|
||||
['base_tributavel' => $input['base']], ['iva_general_rate' => $rate['value']]);
|
||||
}
|
||||
|
||||
return app(SimulationFiscalSnapshot::class)->build($version, $input, $resolution, $evaluation, $missing, true);
|
||||
}
|
||||
|
||||
private function admitMonthly(array $input): array
|
||||
{
|
||||
$rows = [];
|
||||
$baseTotal = BigRational::zero();
|
||||
$vatTotal = BigRational::zero();
|
||||
$complete = true;
|
||||
$previous = null;
|
||||
foreach ($input['monthly_sales'] as $sale) {
|
||||
abort_unless($previous === null || $sale['date'] === date('Y-m-d', strtotime($previous.' +1 month')), 422, 'A projecção deve conter meses consecutivos, sem duplicações.');
|
||||
$previous = $sale['date'];
|
||||
$known = $sale['amount'] !== null && $sale['amount'] !== '';
|
||||
$net = $input['sales_vat_basis'] === 'net';
|
||||
$month = $this->admit(['base' => $known && $net ? $sale['amount'] : null,
|
||||
'currency' => $input['currency'], 'reference_date' => $sale['date'],
|
||||
'operation' => 'internal_general_net', 'scope_declared' => $input['scope_declared']], ! $known || ! $net);
|
||||
$snapshot ??= $month;
|
||||
$rate = collect($month['fiscal_provenance']['resolution'])->firstWhere('parameter_code', 'IVA_GENERAL_RATE');
|
||||
$vat = $month['result']['value'];
|
||||
$status = ! $known ? 'missing_sales' : (! $net ? 'unsupported_basis' : ($vat === null ? 'indeterminate' : 'calculated'));
|
||||
$rows[] = ['date' => $sale['date'], 'sales_declared' => $sale['amount'],
|
||||
'net_sales' => $known && $net ? $sale['amount'] : null,
|
||||
'rate' => $vat !== null && ($rate['status'] ?? null) === 'resolved' ? $rate['value'] : null,
|
||||
'vat' => $vat, 'gross_sales' => $vat === null ? null : (string) BigRational::of($sale['amount'])->plus($vat)->toBigDecimal(),
|
||||
'status' => $status, 'rule_id' => $month['fiscal_provenance']['rule']['id'],
|
||||
'rule_version' => $month['fiscal_provenance']['rule']['rule_version']];
|
||||
if ($vat === null) {
|
||||
$complete = false;
|
||||
} else {
|
||||
$baseTotal = $baseTotal->plus($sale['amount']);
|
||||
$vatTotal = $vatTotal->plus($vat);
|
||||
}
|
||||
}
|
||||
$value = $complete ? (string) $vatTotal->toBigDecimal() : null;
|
||||
$snapshot['base'] = $complete ? (string) $baseTotal->toBigDecimal() : null;
|
||||
$snapshot['indicative_total'] = $value;
|
||||
$snapshot['result']['value'] = $value;
|
||||
$snapshot['result']['status'] = $complete ? 'calculated' : 'indeterminate';
|
||||
$snapshot['result']['missing_inputs'] = $complete ? [] : ['monthly_sales_or_net_basis_or_scope'];
|
||||
$snapshot['result']['explanation'] = 'IVA mensal sobre vendas declaradas sem IVA, pela versão publicada congelada na admissão. Valores com IVA incluído ou sem informação permanecem indeterminados. Não é imposto final a pagar.';
|
||||
$snapshot['presentation']['value'] = $value;
|
||||
$snapshot['intermediate'] = null;
|
||||
$snapshot['monthly_projection'] = ['input' => $input, 'rows' => $rows,
|
||||
'cash_treatment' => 'Informação separada da tesouraria: os recebimentos declarados não são aumentados pelo IVA nem o IVA é deduzido como custo ou imposto a pagar. Calendário de cobrança e liquidação fiscal não é inferido.'];
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
}
|
||||
@@ -8,15 +8,24 @@ final class SimulationTaxGovernanceAccess
|
||||
{
|
||||
private const ROLES = ['editors', 'reviewers', 'approvers', 'publishers'];
|
||||
|
||||
public static function maintainer(User $user): bool
|
||||
{
|
||||
return $user->hasVerifiedEmail() && ! app(PortalProfileAccess::class)->has($user, 'auditor') && ($user->can('manage-portal')
|
||||
|| app(ScopedPortalAdministration::class)->administrative($user));
|
||||
}
|
||||
|
||||
public static function requireRole(User $user, string $role): void
|
||||
{
|
||||
abort_unless(in_array($role, self::ROLES, true), 500, 'Função de governação desconhecida.');
|
||||
abort_unless(in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true),
|
||||
abort_unless(self::maintainer($user) || in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true),
|
||||
403, 'O utilizador não está designado para esta função de governação fiscal.');
|
||||
}
|
||||
|
||||
public static function requireAnyRole(User $user): void
|
||||
{
|
||||
if (self::maintainer($user)) {
|
||||
return;
|
||||
}
|
||||
foreach (self::ROLES as $role) {
|
||||
if (in_array(strtolower($user->email), config('simulation-tax-governance.'.$role, []), true)) {
|
||||
return;
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Brick\Math\BigRational;
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -16,32 +17,32 @@ final class SimulationTaxParameterResolver
|
||||
public function validateParameters(array $parameters): void
|
||||
{
|
||||
if ($parameters === [] || count($parameters) > 100) {
|
||||
throw new InvalidArgumentException('Provide between 1 and 100 versioned parameters.');
|
||||
throw new InvalidArgumentException('Indique entre 1 e 100 parâmetros versionados.');
|
||||
}
|
||||
foreach ($parameters as $code => $parameter) {
|
||||
if (! is_string($code) || ! preg_match('/^[A-Z][A-Z0-9._-]{1,63}$/', $code) || ! is_array($parameter)
|
||||
|| array_diff(array_keys($parameter), ['value', 'unit', 'conditions']) !== []
|
||||
|| array_diff(['value', 'unit', 'conditions'], array_keys($parameter)) !== []) {
|
||||
throw new InvalidArgumentException('Each parameter requires only value, unit, and conditions.');
|
||||
throw new InvalidArgumentException('Cada parâmetro deve conter apenas valor, unidade e condições.');
|
||||
}
|
||||
if ((! is_string($parameter['value']) && ! is_int($parameter['value'])) || (string) $parameter['value'] === ''
|
||||
|| ! is_string($parameter['unit']) || ! preg_match('/^[a-z][a-z0-9._-]{0,31}$/', $parameter['unit'])
|
||||
|| ! is_array($parameter['conditions'])) {
|
||||
throw new InvalidArgumentException('Invalid parameter value, unit, or conditions.');
|
||||
throw new InvalidArgumentException('Reveja o valor, a unidade e as condições do parâmetro.');
|
||||
}
|
||||
$isNumericValue = preg_match('/^-?\d+(?:\.\d+)?$/', (string) $parameter['value']) === 1;
|
||||
if (in_array($parameter['unit'], ['percent', 'mzn', 'amount', 'days', 'count', 'mzn_per_unit', 'per_unit'], true) && ! $isNumericValue) {
|
||||
throw new InvalidArgumentException('Numeric parameter units require a plain decimal value.');
|
||||
throw new InvalidArgumentException('Esta unidade requer um valor numérico decimal.');
|
||||
}
|
||||
if ($isNumericValue) {
|
||||
$value = BigRational::of((string) $parameter['value']);
|
||||
if ($value->isNegative() || ($parameter['unit'] === 'percent' && $value->compareTo(100) > 0)) {
|
||||
throw new InvalidArgumentException('Numeric parameters cannot be negative; percentages must be between 0 and 100.');
|
||||
throw new InvalidArgumentException('Os valores não podem ser negativos; as percentagens devem estar entre 0 e 100.');
|
||||
}
|
||||
}
|
||||
foreach ($parameter['conditions'] as $condition => $expected) {
|
||||
if (! is_string($condition) || ! is_string($expected)) {
|
||||
throw new InvalidArgumentException('Conditions must be a flat map of string assumptions.');
|
||||
throw new InvalidArgumentException('Indique as condições numa lista simples de nomes e valores em texto.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,32 +53,34 @@ final class SimulationTaxParameterResolver
|
||||
* never executes a tax formula and requires each parameter to declare context.
|
||||
*
|
||||
* @param array<string,string> $context
|
||||
* @return list<array<string,mixed>>
|
||||
* @return list<array<string,mixed>>|array{parameters:list<array<string,mixed>>,diagnostics:list<array<string,mixed>>}
|
||||
*/
|
||||
public function resolvePublishedForPeriod(string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
public function resolvePublishedForPeriod(string $component, string $periodStart, string $periodEnd, array $context, bool $diagnostics = false): array
|
||||
{
|
||||
$start = $this->date($periodStart);
|
||||
$end = $this->date($periodEnd);
|
||||
if ($end < $start || $start->diff($end)->days > 365) {
|
||||
throw new InvalidArgumentException('Invalid effective period.');
|
||||
throw new InvalidArgumentException('Reveja o período de aplicação indicado.');
|
||||
}
|
||||
|
||||
$rows = DB::table('simulation_tax_rule_versions as rule')
|
||||
->join('investment_legal_sources as source', 'source.id', '=', 'rule.legal_source_id')
|
||||
->where('rule.component', $component)
|
||||
->where('rule.status', 'published')
|
||||
->whereDate('rule.valid_from', '<=', $periodEnd)
|
||||
->where(fn ($query) => $query->whereNull('rule.valid_until')->orWhereDate('rule.valid_until', '>=', $periodStart))
|
||||
->where('source.validation_status', 'validated')
|
||||
->when(! $diagnostics, fn ($query) => $query->whereDate('rule.valid_from', '<=', $periodEnd)
|
||||
->where(fn ($query) => $query->whereNull('rule.valid_until')->orWhereDate('rule.valid_until', '>=', $periodStart)))
|
||||
->where(fn ($query) => $query->where('source.validation_status', 'validated')->orWhere(fn ($fiscal) => $fiscal->where('source.validation_status', 'pending')->where('source.fiscal_acceptance->scope', 'fiscal_parameters')
|
||||
->where('source.fiscal_acceptance->basis', 'Tempo-official-sources-20261008')
|
||||
->whereRaw("source.fiscal_acceptance->>'sha256'=rule.source_sha256")))
|
||||
->whereColumn('source.version_no', 'rule.source_version_no')
|
||||
->whereDate('source.valid_from', '<=', $periodStart)
|
||||
->where(fn ($query) => $query->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', $periodEnd))
|
||||
->when(! $diagnostics, fn ($query) => $query->whereDate('source.valid_from', '<=', $periodStart)
|
||||
->where(fn ($query) => $query->whereNull('source.valid_until')->orWhereDate('source.valid_until', '>=', $periodEnd)))
|
||||
->select([
|
||||
'rule.id', 'rule.rule_code', 'rule.rule_version', 'rule.component', 'rule.scope_key',
|
||||
'rule.valid_from', 'rule.valid_until', 'rule.parameters', 'rule.rule_definition',
|
||||
'rule.source_version_no', 'rule.source_sha256',
|
||||
'source.title as source_title', 'source.diploma as source_diploma', 'source.article as source_article',
|
||||
'source.url as source_url', 'source.validation_status as source_validation_status',
|
||||
'source.url as source_url', 'source.validation_status as source_validation_status', 'source.fiscal_acceptance',
|
||||
'source.version_no as source_current_version', 'source.valid_from as source_valid_from',
|
||||
'source.valid_until as source_valid_until',
|
||||
])
|
||||
@@ -110,6 +113,7 @@ final class SimulationTaxParameterResolver
|
||||
'article' => $row->source_article,
|
||||
'url' => $row->source_url,
|
||||
'validation_status' => $row->source_validation_status,
|
||||
'fiscal_acceptance' => is_array($row->fiscal_acceptance) ? $row->fiscal_acceptance : json_decode($row->fiscal_acceptance ?? 'null', true),
|
||||
'version_no' => (int) $row->source_current_version,
|
||||
'valid_from' => (string) $row->source_valid_from,
|
||||
'valid_until' => $row->source_valid_until === null ? null : (string) $row->source_valid_until,
|
||||
@@ -117,7 +121,11 @@ final class SimulationTaxParameterResolver
|
||||
];
|
||||
})->all());
|
||||
|
||||
return $this->resolveAvailableParameters($versions, $component, $periodStart, $periodEnd, $context);
|
||||
$parameters = $this->resolveAvailableParameters($versions, $component, $periodStart, $periodEnd, $context);
|
||||
|
||||
$resolvedIva = array_filter($parameters, fn (array $parameter): bool => $parameter['parameter_code'] === 'IVA_GENERAL_RATE' && $parameter['status'] === 'resolved');
|
||||
|
||||
return $diagnostics ? ['parameters' => $parameters, 'diagnostics' => $resolvedIva !== [] ? [] : (new SimulationIvaDiagnostics)->explain($versions, $periodStart, $periodEnd, $context)] : $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,15 +134,31 @@ final class SimulationTaxParameterResolver
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function resolveAvailableParameters(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
{
|
||||
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'published');
|
||||
}
|
||||
|
||||
/** Explicit draft preview. Never used by the published-parameter API. */
|
||||
public function resolveDraftForQa(array $versions, string $component, string $periodStart, string $periodEnd, array $context): array
|
||||
{
|
||||
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||
|
||||
return $this->resolveWithStatus($versions, $component, $periodStart, $periodEnd, $context, 'draft');
|
||||
}
|
||||
|
||||
private function resolveWithStatus(array $versions, string $component, string $periodStart, string $periodEnd, array $context, string $requiredStatus): array
|
||||
{
|
||||
$start = $this->date($periodStart);
|
||||
$end = $this->date($periodEnd);
|
||||
if ($end < $start || $start->diff($end)->days > 365) {
|
||||
throw new InvalidArgumentException('Reveja o período de aplicação indicado.');
|
||||
}
|
||||
$groups = [];
|
||||
|
||||
foreach ($versions as $version) {
|
||||
if (($version['component'] ?? null) !== $component
|
||||
|| ($version['status'] ?? null) !== 'published'
|
||||
|| ($version['source']['validation_status'] ?? null) !== 'validated'
|
||||
|| ($version['status'] ?? null) !== $requiredStatus
|
||||
|| ! SimulationFiscalSourceAcceptance::eligible($version['source'] ?? [], $version['source_sha256'] ?? null)
|
||||
|| (int) ($version['source_version_no'] ?? 0) !== (int) ($version['source']['version_no'] ?? -1)
|
||||
|| ! $this->overlaps($version, $start, $end)
|
||||
|| ! $this->covers($version['source'], $start) || ! $this->covers($version['source'], $end)
|
||||
@@ -232,7 +256,7 @@ final class SimulationTaxParameterResolver
|
||||
|| ($version['component'] ?? null) !== $component
|
||||
|| ($version['scope_key'] ?? null) !== $scopeKey
|
||||
|| ! $this->covers($version, $date)
|
||||
|| ($version['source']['validation_status'] ?? null) !== 'validated'
|
||||
|| ! SimulationFiscalSourceAcceptance::eligible($version['source'] ?? [], $version['source_sha256'] ?? null)
|
||||
|| (int) ($version['source_version_no'] ?? 0) !== (int) ($version['source']['version_no'] ?? -1)
|
||||
|| ! $this->covers($version['source'], $date)
|
||||
|| ! preg_match('/^[a-f0-9]{64}$/D', (string) ($version['source_sha256'] ?? ''))) {
|
||||
@@ -315,7 +339,7 @@ final class SimulationTaxParameterResolver
|
||||
{
|
||||
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $date);
|
||||
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
|
||||
throw new InvalidArgumentException('Effective date must use YYYY-MM-DD.');
|
||||
throw new InvalidArgumentException('Indique uma data de aplicação válida no formato ano-mês-dia.');
|
||||
}
|
||||
|
||||
return $parsed;
|
||||
|
||||
@@ -95,16 +95,16 @@ final class SimulationTaxRuleExpression
|
||||
private function topologicalOrder(array $definition): array
|
||||
{
|
||||
if (($definition['language'] ?? null) !== self::LANGUAGE || ! is_array($definition['nodes'] ?? null) || ! is_string($definition['result'] ?? null)) {
|
||||
throw new InvalidArgumentException('Unsupported expression definition.');
|
||||
throw new InvalidArgumentException('O formato da expressão não é suportado.');
|
||||
}
|
||||
$nodes = $definition['nodes'];
|
||||
if ($nodes === [] || count($nodes) > 100) {
|
||||
throw new InvalidArgumentException('Expression must contain between 1 and 100 nodes.');
|
||||
throw new InvalidArgumentException('A expressão deve conter entre 1 e 100 elementos.');
|
||||
}
|
||||
|
||||
foreach ($nodes as $id => $node) {
|
||||
if (! is_string($id) || ! preg_match('/^[a-z][a-z0-9_]{0,47}$/', $id) || ! is_array($node) || ! is_string($node['op'] ?? null)) {
|
||||
throw new InvalidArgumentException('Invalid expression node.');
|
||||
throw new InvalidArgumentException('Reveja o elemento indicado na expressão.');
|
||||
}
|
||||
$op = $node['op'];
|
||||
$allowedFields = match ($op) {
|
||||
@@ -112,40 +112,40 @@ final class SimulationTaxRuleExpression
|
||||
'literal' => ['op', 'value'],
|
||||
'add', 'subtract', 'multiply', 'divide', 'min', 'max' => ['op', 'args'],
|
||||
'round' => ['op', 'args', 'scale', 'mode'],
|
||||
default => throw new InvalidArgumentException('Expression operation is not allowed.'),
|
||||
default => throw new InvalidArgumentException('Esta operação não é suportada na expressão.'),
|
||||
};
|
||||
if (array_diff(array_keys($node), $allowedFields) !== [] || array_diff($allowedFields, array_keys($node)) !== []) {
|
||||
throw new InvalidArgumentException('Expression node has missing or unsupported fields.');
|
||||
throw new InvalidArgumentException('Há campos em falta ou não suportados num elemento da expressão.');
|
||||
}
|
||||
if (in_array($op, ['input', 'parameter'], true) && (! is_string($node['key']) || ! preg_match('/^[a-z][a-z0-9_.-]{0,79}$/', $node['key']))) {
|
||||
throw new InvalidArgumentException('Invalid input or parameter key.');
|
||||
throw new InvalidArgumentException('Reveja o identificador da entrada ou do parâmetro.');
|
||||
}
|
||||
if ($op === 'literal') {
|
||||
$this->number($node['value']);
|
||||
}
|
||||
if (isset($node['args'])) {
|
||||
if (! is_array($node['args'])) {
|
||||
throw new InvalidArgumentException('Invalid expression arguments.');
|
||||
throw new InvalidArgumentException('Reveja os argumentos da expressão.');
|
||||
}
|
||||
$count = count($node['args']);
|
||||
$validCount = $op === 'round' ? $count === 1 : ($op === 'subtract' || $op === 'divide' ? $count === 2 : $count >= 2 && $count <= 20);
|
||||
if (! $validCount || count(array_filter($node['args'], 'is_string')) !== $count) {
|
||||
throw new InvalidArgumentException('Invalid expression arguments.');
|
||||
throw new InvalidArgumentException('Reveja os argumentos da expressão.');
|
||||
}
|
||||
}
|
||||
if ($op === 'round' && (! is_int($node['scale']) || $node['scale'] < 0 || $node['scale'] > 12 || ! isset(self::ROUNDING[$node['mode']]))) {
|
||||
throw new InvalidArgumentException('Invalid explicit rounding configuration.');
|
||||
throw new InvalidArgumentException('Reveja a configuração de arredondamento.');
|
||||
}
|
||||
}
|
||||
|
||||
if (! array_key_exists($definition['result'], $nodes)) {
|
||||
throw new InvalidArgumentException('Expression result references an unknown node.');
|
||||
throw new InvalidArgumentException('O resultado da expressão refere um elemento inexistente.');
|
||||
}
|
||||
$state = [];
|
||||
$order = [];
|
||||
$visit = function (string $id) use (&$visit, &$state, &$order, $nodes): void {
|
||||
if (($state[$id] ?? 0) === 1) {
|
||||
throw new InvalidArgumentException('Expression dependency graph contains a cycle.');
|
||||
throw new InvalidArgumentException('A expressão contém uma dependência circular.');
|
||||
}
|
||||
if (($state[$id] ?? 0) === 2) {
|
||||
return;
|
||||
@@ -153,7 +153,7 @@ final class SimulationTaxRuleExpression
|
||||
$state[$id] = 1;
|
||||
foreach ($nodes[$id]['args'] ?? [] as $dependency) {
|
||||
if (! is_string($dependency) || ! array_key_exists($dependency, $nodes)) {
|
||||
throw new InvalidArgumentException('Expression references an unknown node.');
|
||||
throw new InvalidArgumentException('A expressão refere um elemento inexistente.');
|
||||
}
|
||||
$visit($dependency);
|
||||
}
|
||||
@@ -191,13 +191,13 @@ final class SimulationTaxRuleExpression
|
||||
if ($op === 'min' || $op === 'max') {
|
||||
return array_reduce(array_slice($args, 1), static fn (BigRational $carry, BigRational $value): BigRational => ($op === 'min' ? $carry->compareTo($value) <= 0 : $carry->compareTo($value) >= 0) ? $carry : $value, $args[0]);
|
||||
}
|
||||
throw new InvalidArgumentException('Expression operation is not allowed.');
|
||||
throw new InvalidArgumentException('Esta operação não é suportada na expressão.');
|
||||
}
|
||||
|
||||
private function number(mixed $value): BigRational
|
||||
{
|
||||
if ((! is_string($value) && ! is_int($value)) || ! preg_match('/^-?\d+(?:\.\d+)?$/', (string) $value)) {
|
||||
throw new InvalidArgumentException('Numbers must be plain decimal strings or integers.');
|
||||
throw new InvalidArgumentException('Introduza valores numéricos decimais ou inteiros.');
|
||||
}
|
||||
|
||||
return BigRational::of((string) $value);
|
||||
|
||||
@@ -65,6 +65,8 @@ final class SimulationTaxRuleGovernance
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $action, $evidence): SimulationTaxRuleVersion {
|
||||
$this->setContext($actor);
|
||||
// Serialize public admission with publication/suspension, without widening RLS.
|
||||
DB::select('select pg_advisory_xact_lock(261021, hashtext(?))', [$id]);
|
||||
$rule = SimulationTaxRuleVersion::query()->lockForUpdate()->findOrFail($id);
|
||||
$this->matchVersion($rule, $version);
|
||||
$next = ['version_no' => $version + 1];
|
||||
@@ -78,15 +80,12 @@ final class SimulationTaxRuleGovernance
|
||||
break;
|
||||
case 'review':
|
||||
case 'reject':
|
||||
abort_unless((int) $rule->author_id !== $actor->id, 403, 'O autor não pode rever a própria regra.');
|
||||
abort_unless($rule->status === 'submitted', 422, 'A regra tem de estar submetida para revisão.');
|
||||
$this->sourceStillValid($rule);
|
||||
$next += ['status' => $action === 'review' ? 'reviewed' : 'rejected', 'reviewer_id' => $actor->id,
|
||||
'review_evidence' => $evidence, 'reviewed_at' => now()];
|
||||
break;
|
||||
case 'approve':
|
||||
abort_unless((int) $rule->author_id !== $actor->id && (int) $rule->reviewer_id !== $actor->id, 403,
|
||||
'Autor e revisor não podem aprovar a mesma regra.');
|
||||
abort_unless($rule->status === 'reviewed', 422, 'A regra tem de estar revista antes da aprovação.');
|
||||
$this->sourceStillValid($rule);
|
||||
$next += ['status' => 'approved', 'approver_id' => $actor->id,
|
||||
@@ -94,9 +93,6 @@ final class SimulationTaxRuleGovernance
|
||||
break;
|
||||
case 'publish':
|
||||
abort_unless($rule->status === 'approved', 422, 'A regra tem de estar aprovada antes da publicação.');
|
||||
abort_unless((int) $rule->author_id !== $actor->id && (int) $rule->reviewer_id !== $actor->id
|
||||
&& (int) $rule->approver_id !== $actor->id, 403,
|
||||
'Autor, revisor e aprovador não podem publicar a mesma regra.');
|
||||
$this->sourceStillValid($rule);
|
||||
$this->assertNoPublishedOverlap($rule);
|
||||
$next += ['status' => 'published', 'publisher_id' => $actor->id,
|
||||
@@ -155,7 +151,11 @@ final class SimulationTaxRuleGovernance
|
||||
$source = InvestmentLegalSource::query()->whereKey($data['legal_source_id'])->firstOrFail();
|
||||
abort_unless(preg_match('/^[a-f0-9]{64}$/D', (string) $data['source_sha256']) === 1, 422,
|
||||
'Indique o SHA-256 do exemplar oficial efectivamente revisto.');
|
||||
abort_unless($source->validation_status === 'validated', 422, 'A fonte jurídica ainda não foi validada.');
|
||||
abort_unless(SimulationFiscalSourceAcceptance::eligible($source->attributesToArray(), $data['source_sha256']), 422,
|
||||
'A fonte ainda não está aceite para este cadastro fiscal.');
|
||||
abort_if(is_array($source->fiscal_acceptance)
|
||||
&& ($source->fiscal_acceptance['sha256'] ?? null) !== $data['source_sha256'], 422,
|
||||
'O hash da regra deve corresponder ao exemplar registado na aceitação da fonte fiscal.');
|
||||
abort_unless($source->valid_from <= $data['valid_from']
|
||||
&& ($source->valid_until === null || ($data['valid_until'] !== null && $source->valid_until >= $data['valid_until']))
|
||||
&& ($data['valid_until'] !== null || $source->valid_until === null), 422,
|
||||
@@ -167,7 +167,8 @@ final class SimulationTaxRuleGovernance
|
||||
private function sourceStillValid(SimulationTaxRuleVersion $rule): void
|
||||
{
|
||||
$source = InvestmentLegalSource::query()->lockForUpdate()->find($rule->legal_source_id);
|
||||
abort_unless($source !== null && $source->validation_status === 'validated'
|
||||
abort_unless($source !== null && SimulationFiscalSourceAcceptance::eligible($source->attributesToArray(), $rule->source_sha256)
|
||||
&& (! is_array($source->fiscal_acceptance) || ($source->fiscal_acceptance['sha256'] ?? null) === $rule->source_sha256)
|
||||
&& (int) $source->version_no === (int) $rule->source_version_no
|
||||
&& $source->valid_from <= $rule->valid_from->format('Y-m-d')
|
||||
&& ($source->valid_until === null || ($rule->valid_until !== null && $source->valid_until >= $rule->valid_until->format('Y-m-d')))
|
||||
|
||||
@@ -14,16 +14,31 @@ final class TerritoryGeometry
|
||||
abort_unless($geography->references($management)->where('id', $id)->exists(), 404);
|
||||
$path = $geography->path($id, $management);
|
||||
$ids = array_map(fn ($node) => $node->id, $path);
|
||||
$approved = app(ApprovedAdministrativeBoundaries::class);
|
||||
$rows = DB::table('geo_geometries as g')->join('geo_locations as l', 'l.id', '=', 'g.geo_location_id')
|
||||
->whereIn('g.geo_location_id', $ids)->whereNull('g.deleted_at')->whereNull('l.deleted_at')
|
||||
->whereIn('g.data_classification', $management ? ['internal', 'public'] : ['public'])
|
||||
->where(function ($query) use ($management, $approved) {
|
||||
$query->where('g.data_classification', 'public');
|
||||
$query->orWhere(function ($internal) use ($management, $approved) {
|
||||
$internal->where('g.data_classification', 'internal');
|
||||
if (! $management) {
|
||||
$internal->whereIn('g.id', array_keys($approved->snapshots()));
|
||||
}
|
||||
});
|
||||
})
|
||||
->whereRaw("g.properties->>'purpose' = 'administrative_boundary'")
|
||||
->whereIn('g.geometry_type', ['polygon', 'multipolygon'])
|
||||
->whereRaw('ST_IsValid(g.geom) AND NOT ST_IsEmpty(g.geom) AND ST_SRID(g.geom)=4326')
|
||||
->orderBy('g.geo_location_id')->orderBy('g.id')->limit(101)
|
||||
->get(['g.id', 'g.geo_location_id', 'l.name', 'l.location_type', 'g.properties', 'g.data_classification',
|
||||
DB::raw('ST_AsGeoJSON(ST_SimplifyPreserveTopology(g.geom,0.0001),6) as geometry')]);
|
||||
$areas = $rows->take(100)->map(function ($row) use ($id) {
|
||||
DB::raw('ST_AsGeoJSON(ST_SimplifyPreserveTopology(g.geom,0.0001),6) as geometry'),
|
||||
DB::raw("encode(sha256(ST_AsEWKB(g.geom)),'hex') as geometry_sha256"),
|
||||
DB::raw("encode(sha256(convert_to(g.properties::text,'UTF8')),'hex') as properties_sha256")]);
|
||||
if (! $management) {
|
||||
$rows = $rows->filter(fn ($row) => $row->data_classification === 'public'
|
||||
|| $approved->allows($row->id, $row->geo_location_id, $row->geometry_sha256, $row->properties_sha256))->values();
|
||||
}
|
||||
$areas = $rows->take(100)->map(function ($row) use ($id, $management) {
|
||||
$source = json_decode($row->properties, true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
return ['id' => $row->id, 'territory_id' => $row->geo_location_id, 'location_type' => $row->location_type,
|
||||
@@ -31,7 +46,7 @@ final class TerritoryGeometry
|
||||
'title' => 'Limite administrativo: '.$row->name, 'purpose' => 'administrative_boundary',
|
||||
'source_reference' => $source['authority'] ?? null, 'source_date' => $source['source_version'] ?? null,
|
||||
'source_url' => $source['source_url'] ?? null, 'source_sha256' => $source['source_sha256'] ?? null,
|
||||
'data_classification' => $row->data_classification, 'legal_currentness' => $source['legal_currentness'] ?? 'not_determined', 'url' => ''];
|
||||
'data_classification' => $management ? $row->data_classification : 'public', 'legal_currentness' => $source['legal_currentness'] ?? 'not_determined', 'url' => ''];
|
||||
})->all();
|
||||
|
||||
return ['territory_id' => $id, 'territory_registered' => true,
|
||||
|
||||
@@ -20,7 +20,7 @@ class TerritoryGeometryImport
|
||||
|
||||
private function guard(User $actor, bool $write = false): void
|
||||
{
|
||||
abort_unless($actor->can('manage-portal'), 403);
|
||||
abort_unless($actor->can('manage-portal') || app(ScopedPortalAdministration::class)->administrative($actor), 403);
|
||||
abort_unless(config('geometry-import.enabled'), 503, 'Importação cartográfica não disponibilizada.');
|
||||
if (! $write) {
|
||||
return;
|
||||
|
||||
@@ -170,11 +170,11 @@ class VirtualDesk
|
||||
});
|
||||
}
|
||||
|
||||
public function createRequest(User $actor, string $caseId, string $serviceId, string $clientKey): \stdClass
|
||||
public function createRequest(User $actor, string $caseId, string $serviceId, string $clientKey, ?string $opportunity = null): \stdClass
|
||||
{
|
||||
abort_unless(Str::isUuid($serviceId) && Str::isUuid($clientKey), 422);
|
||||
|
||||
return DB::transaction(function () use ($actor, $caseId, $serviceId, $clientKey) {
|
||||
return DB::transaction(function () use ($actor, $caseId, $serviceId, $clientKey, $opportunity) {
|
||||
$case = $this->case($actor, $caseId, true, true);
|
||||
abort_if($case->closed_at, 409, 'Dossier encerrado.');
|
||||
$service = DB::table('desk_service_versions')->where('id', $serviceId)->where('status', 'published')->first();
|
||||
@@ -197,7 +197,10 @@ class VirtualDesk
|
||||
$this->event($case, $actor, 'request_prefill_prepared', ['draft_id' => $draft->id, 'draft_version' => $draft->version_no, 'snapshot_sha256' => $draft->snapshot_sha256, 'fields' => ['title', 'description']]);
|
||||
}
|
||||
$context = app(InvestorContext::class)->state($case);
|
||||
$mapped = app(InvestorContext::class)->prefill($context)['desk'];
|
||||
if (count($context['opportunity_choices'] ?? []) > 1 && !$opportunity) $payload['description'] = '';
|
||||
$mapped = app(InvestorContext::class)->prefill($context, $opportunity)['desk'];
|
||||
if ($opportunity) $payload['context_opportunity'] = $opportunity;
|
||||
$payload = app(InvestmentConsumerScope::class)->bind($actor, $caseId, $payload);
|
||||
$serviceFields = json_decode($service->definition, true)['fields'];
|
||||
foreach (['territory_id' => 'territory_id', 'location_source' => 'location_source', 'title' => 'title', 'description' => 'description', 'sector' => 'sector', 'province_id' => 'province_id', 'district_id' => 'district_id', 'admin_post_id' => 'admin_post_id', 'locality_id' => 'locality_id'] as $field => $source) {
|
||||
if (isset($serviceFields[$field],$mapped[$source]) && (empty($payload[$field]) || in_array($field, ['title', 'description'], true) && $context['revision'] > 0)) {
|
||||
@@ -230,6 +233,12 @@ class VirtualDesk
|
||||
$draft = SimulationFormDraft::query()->whereKey($draft->id)->lockForUpdate()->firstOrFail();
|
||||
}
|
||||
$economic = SimulationFormDraft::decryptSnapshot($draft->economic_snapshot);
|
||||
$contextChoices = app(InvestorContext::class)->state($case)['opportunity_choices'] ?? [];
|
||||
if (count($contextChoices) > 1) {
|
||||
$snapshot = json_decode($economic['context_applicability_snapshot'] ?? '{}', true);
|
||||
$draftChoices = $snapshot['opportunity_choices'] ?? [];
|
||||
if (count($draftChoices) !== 1 || ($draftChoices[0]['opportunity']['key'] ?? null) !== ($payload['context_opportunity'] ?? null)) return null;
|
||||
}
|
||||
$description = (string) ($economic['project_summary'] ?? '');
|
||||
if (trim($description) === '') {
|
||||
return null;
|
||||
@@ -250,7 +259,10 @@ class VirtualDesk
|
||||
* @return array<string,mixed> */
|
||||
public function validateFields(array $payload, array $definition, bool $submitting): array
|
||||
{
|
||||
$rules = ['payload' => ['required', 'array:'.implode(',', [...array_keys($definition['fields']), 'country', 'declared_origin_country_code'])],
|
||||
$rules = ['payload' => ['required', 'array:'.implode(',', [...array_keys($definition['fields']), 'country', 'declared_origin_country_code', 'context_reuse', 'context_opportunity', 'context_opportunity_snapshot'])],
|
||||
'payload.context_opportunity' => ['nullable', 'string', 'max:100'],
|
||||
'payload.context_opportunity_snapshot' => ['nullable', 'string', 'max:200000'],
|
||||
'payload.context_reuse' => ['nullable', 'string', 'max:10000'],
|
||||
'payload.country' => ['nullable', 'string', 'max:100', app(CountryCatalogue::class)->legacyCountryRule()],
|
||||
'payload.declared_origin_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()]];
|
||||
foreach ($definition['fields'] as $key => $field) {
|
||||
@@ -333,6 +345,9 @@ class VirtualDesk
|
||||
}
|
||||
}
|
||||
$payload = $this->validateFields($data['payload'], $this->definition($request), $submit);
|
||||
if ($request->status !== 'returned' || in_array('context_opportunity', json_decode($request->editable_fields ?? '[]', true), true)) {
|
||||
$payload = app(InvestmentConsumerScope::class)->bind($actor, $request->case_id, $payload, $submit);
|
||||
}
|
||||
if ($request->status === 'returned') {
|
||||
$editable = json_decode($request->editable_fields ?? '[]', true);
|
||||
$previous = $this->decode($request->payload);
|
||||
@@ -388,7 +403,7 @@ class VirtualDesk
|
||||
abort_if($this->owns($actor, $case, false), 403, 'O proponente não pode analisar ou decidir o seu próprio pedido.');
|
||||
abort_unless($actor->can('manage-portal') || (int) $request->analyst_id === $actor->id, 403);
|
||||
if (in_array($data['status'], ['accepted', 'rejected', 'closed'], true)) {
|
||||
abort_unless(app(ScopedPortalAdministration::class)->deskDecision($actor,$request), 403);
|
||||
abort_unless(app(ScopedPortalAdministration::class)->deskDecision($actor, $request), 403);
|
||||
}
|
||||
abort_unless(in_array($data['status'], config('virtual-desk.transitions.'.$request->status, []), true), 409, 'Transição inválida.');
|
||||
}
|
||||
@@ -412,13 +427,13 @@ class VirtualDesk
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $data) {
|
||||
$case = $this->case($actor, $id, false, true);
|
||||
abort_unless($this->owns($actor, $case) || app(ScopedPortalAdministration::class)->deskCaseDecision($actor,$case->id), 403);
|
||||
abort_unless($this->owns($actor, $case) || app(ScopedPortalAdministration::class)->deskCaseDecision($actor, $case->id), 403);
|
||||
abort_unless((int) $case->version === (int) $data['version'], 409);
|
||||
$workflow = json_decode($case->workflow, true, 512, JSON_THROW_ON_ERROR);
|
||||
$current = $workflow[$data['stage']];
|
||||
$decision = in_array($data['status'], ['completed', 'not_applicable'], true);
|
||||
if ($decision) {
|
||||
abort_unless(app(ScopedPortalAdministration::class)->deskCaseDecision($actor,$case->id) && ! $this->owns($actor, $case, false), 403, 'Conclusão documental exige revisão interna por outra pessoa autorizada.');
|
||||
abort_unless(app(ScopedPortalAdministration::class)->deskCaseDecision($actor, $case->id) && ! $this->owns($actor, $case, false), 403, 'Conclusão documental exige revisão interna por outra pessoa autorizada.');
|
||||
abort_unless(trim($data['evidence'] ?? '') !== '', 422, 'Identifique a evidência documental.');
|
||||
foreach ($current['dependencies'] as $dependency) {
|
||||
abort_unless(in_array($workflow[$dependency]['status'], ['completed', 'not_applicable'], true) || (($data['exception'] ?? false) && ($data['document_id'] ?? null)), 422, 'Dependência '.$dependency.' pendente; uma exceção exige evidência própria.');
|
||||
|
||||
+24
-1
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Middleware\AuditProfileDecision;
|
||||
use App\Http\Middleware\EnsureHomologationAccess;
|
||||
use App\Http\Middleware\EnsureSimulationRecoveryCookie;
|
||||
use App\Http\Middleware\HandleAppearance;
|
||||
use App\Http\Middleware\HandleInertiaRequests;
|
||||
@@ -30,7 +31,7 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
$middleware->encryptCookies(except: ['appearance', 'sidebar_state', EnsureSimulationRecoveryCookie::NAME]);
|
||||
|
||||
$middleware->web(append: [
|
||||
\App\Http\Middleware\EnsureHomologationAccess::class,
|
||||
EnsureHomologationAccess::class,
|
||||
PortalProfileSession::class,
|
||||
ProtectPrivilegedIdentity::class,
|
||||
AuditProfileDecision::class,
|
||||
@@ -68,6 +69,28 @@ return Application::configure(basePath: dirname(__DIR__))
|
||||
fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
|
||||
);
|
||||
$exceptions->respond(function (Response $response, Throwable $exception, Request $request): Response {
|
||||
if (($request->is('api/*') || $request->expectsJson()) && $response->getStatusCode() >= 400) {
|
||||
$body = json_decode((string) $response->getContent(), true);
|
||||
$genericMessages = [
|
||||
'Not Found' => 'O registo não foi encontrado ou não está acessível nesta conta.',
|
||||
'Not found.' => 'O registo não foi encontrado ou não está acessível nesta conta.',
|
||||
'Forbidden' => 'Esta conta não tem acesso a esta operação.',
|
||||
'Forbidden.' => 'Esta conta não tem acesso a esta operação.',
|
||||
'Unauthenticated.' => 'Entre na sua conta para continuar esta operação.',
|
||||
'CSRF token mismatch.' => 'A sessão expirou. Entre novamente antes de repetir a operação.',
|
||||
'Too Many Attempts.' => 'Foram feitas várias tentativas. Aguarde um pouco e tente novamente.',
|
||||
'Server Error' => 'Não foi possível concluir a operação. Tente novamente.',
|
||||
];
|
||||
if (is_array($body) && is_string($body['message'] ?? null) && isset($genericMessages[$body['message']])) {
|
||||
$body['message'] = $genericMessages[$body['message']];
|
||||
$response->setContent(json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
} elseif (is_array($body) && is_string($body['message'] ?? null)
|
||||
&& $response->getStatusCode() === 404 && str_starts_with($body['message'], 'The route ')
|
||||
&& str_ends_with($body['message'], ' could not be found.')) {
|
||||
$body['message'] = $genericMessages['Not Found'];
|
||||
$response->setContent(json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
if ($request->is('api/*')) {
|
||||
$response->headers->set(
|
||||
'X-Correlation-ID',
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ return [
|
||||
|
|
||||
*/
|
||||
|
||||
'locale' => env('APP_LOCALE', 'en'),
|
||||
'locale' => env('APP_LOCALE', 'pt'),
|
||||
|
||||
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
// Functional configuration expressly defined by Tempo, 23/10/2026.
|
||||
// Codes identify the existing national territorial registry; no geometry is inferred.
|
||||
return [
|
||||
'pemba-lichinga' => ['name' => 'Corredor de Pemba–Lichinga', 'provinces' => ['02', '01']],
|
||||
'nacala' => ['name' => 'Corredor de Nacala', 'provinces' => ['03']],
|
||||
'vale-zambeze' => ['name' => 'Corredor do Vale do Zambeze', 'provinces' => ['05', '04']],
|
||||
'beira' => ['name' => 'Corredor da Beira', 'provinces' => ['07', '06']],
|
||||
'limpopo' => ['name' => 'Corredor do Limpopo', 'provinces' => ['09']],
|
||||
// Tempo's final clarification: both Maputo Province and Maputo City.
|
||||
'maputo' => ['name' => 'Corredor de Maputo', 'provinces' => ['10', '11']],
|
||||
];
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
return [
|
||||
// Explicit opt-in after authenticated installation; never infer activation from schema/ready.
|
||||
'private_preparation' => env('PRIVATE_INVESTMENT_PREPARATION_ENABLED', false),
|
||||
'enabled' => env('INVESTOR_PATH_ENABLED', false),
|
||||
'definition_id' => '61000919-0000-4000-8000-000000000001',
|
||||
];
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
[
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62413-20170626",
|
||||
"sha256": "b471c1afd7235f359acdcc16a93088f77e1f988706c8d3c4d4f11c5d560aea47",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-73945-20170731",
|
||||
"sha256": "2aa0ce0eb305bfdf93e390a978d3694d0fbc0129034077b68cebce418f878415",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-76474-20170808",
|
||||
"sha256": "8f769aec4715449d056c8c25294060b2ff290ec0893c28e9bdcc4e8092fc75f5",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62414-20170626",
|
||||
"sha256": "a040c0b7cb95dd7f053f4d13662dd58b2b06453b6fa61a2d531d0257a8db8c17",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62418-20170626",
|
||||
"sha256": "e8ccafa68f0d1aa80f2e41d9e09f7b13e7c653a8472a731798cfd5e04ce2963e",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-75002-20170804",
|
||||
"sha256": "7b6fbd998be2b47b96e9a4724560c192c502709fa308d6590c0797ddcdb10544",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-73246-20170728",
|
||||
"sha256": "430ee8674c71104fc126bed2911d676f150ac623857a1ada75662987fd9ac390",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-77232-20170811",
|
||||
"sha256": "27544d3127803b7495bef9fd633147d0225d8c31816c4d59ed05a2edd59de070",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62416-20170626",
|
||||
"sha256": "ac575ce340571192552c89b63f0bd62a84dbc47828e6930133af5ff70e249319",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62929-20170627",
|
||||
"sha256": "488017b062c6760659d9147b7f12aea4afd8d824121adb9462e2c7a2ae58437b",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62649-20170626",
|
||||
"sha256": "38a858713472759a2d20a308bdd9d8afa9cfb76dcaf8d11ca709e89261573e42",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62739-20170626",
|
||||
"sha256": "5870fc0fad9bb7af537b7b1468151cde138b1b886ce846c7be25647b630245dd",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62854-20170627",
|
||||
"sha256": "44b1ba9d593bb625cf53de8909e78eb0b3129742c3ec9d58ec68c984e8930bce",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-63128-20170627",
|
||||
"sha256": "74be8f29e5053f53ab1a39a2f63208145c30f23357ca6d78b637dd02bf9c1fb4",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-63181-20170627",
|
||||
"sha256": "3d0f9ac14d36156d8178e33f8616d6406f31ea4cd69c8308cbf4227586d7ccb3",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-63146-20170627",
|
||||
"sha256": "542353466cc6d82b651619c495f138b0576a4be41d21aad194ae2005050cb1bc",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-62688-20170626",
|
||||
"sha256": "a210a789b06d425822f4124f74226a2b27246c086c5ec5f041f1b2237d7c2b65",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-63248-20170628",
|
||||
"sha256": "6c30e61197b8568332af6d9b19bbba7ad8665b3873bb031a8c8aedd41536b060",
|
||||
"kind": "historico_noticioso",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173220-20260616",
|
||||
"sha256": "5b76c3d84dcf7f9a489686d90e3857ae6536705c918e841310bb42b354e80976",
|
||||
"kind": "setorial",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173222-20260616",
|
||||
"sha256": "e64d7063d1ac4dda028c97e1ba64938d2a9e426a0b630c57ee5df52a41312cc7",
|
||||
"kind": "setorial",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173482-20260915",
|
||||
"sha256": "6f888e133a779c719073246f89bcae150198e5897c0e7d9b7ba75f54c54a7830",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173484-20260915",
|
||||
"sha256": "297df455a9c6fd1f0ab7ca7bbe124ce483c86fe55be26baa695f03089b3ac049",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173478-20260915",
|
||||
"sha256": "d4e320ed99dd9d53d205e47932f73651976d43081d5d39f2bfc2996901408644",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173480-20260915",
|
||||
"sha256": "c3ee6401eda5b582c61969b5e3b74fdf26ef34ca481b1aca8c4c309d845147ae",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173476-20260915",
|
||||
"sha256": "72fbf28391db4804e0637b64e7f59e9fa597812a2681b4562dc3d6dfb4093a30",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173470-20260915",
|
||||
"sha256": "26feeae6b8d04972c7a64ee360583cccdcaeb4b0d8795fd7bc2fd3c38866cc19",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173474-20260915",
|
||||
"sha256": "9fa741a17b746bfa2f3ce7b6ce1d2bb34d3a35d3b58330b0554f9e0a6844f049",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
},
|
||||
{
|
||||
"external_id": "legacy-tempo-post-173463-20260915",
|
||||
"sha256": "4f34b7bac4b3030c0614844d379f6e3cfad1b7f6ea3db575a58c33ae033b0e73",
|
||||
"kind": "trabalho_domestico",
|
||||
"original_image_sha256": "28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa"
|
||||
}
|
||||
]
|
||||
+1
-1
@@ -23,7 +23,7 @@ return [
|
||||
'opportunity_other_qa_subtypes' => [],
|
||||
'operator_name' => env('PORTAL_OPERATOR_NAME'),
|
||||
// Tempo, 19/10/2026: institutional contact; commercial department remains separate.
|
||||
'institutional_contact_email' => env('PORTAL_INSTITUTIONAL_CONTACT_EMAIL', 'info@tempo.co.mz'),
|
||||
'institutional_contact_email' => env('PORTAL_INSTITUTIONAL_CONTACT_EMAIL', 'comercial@tempo.co.mz'),
|
||||
'support' => [
|
||||
'email' => env('PORTAL_SUPPORT_EMAIL'),
|
||||
'phone' => env('PORTAL_SUPPORT_PHONE'),
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'enabled' => (bool) env('PROCUREMENT_ENABLED', false),
|
||||
'regimes' => ['state' => 'Contratação pública do Estado', 'external' => 'Financiamento externo', 'private' => 'Concurso privado', 'other' => 'Outro regime documentado'],
|
||||
'acts' => ['initial' => 'Anúncio inicial', 'clarification' => 'Esclarecimento', 'correction' => 'Rectificação', 'extension' => 'Prorrogação', 'award' => 'Resultado / adjudicação', 'cancellation' => 'Cancelamento', 'other' => 'Outro acto'],
|
||||
];
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// Publication and consumer exposure are separate Tempo decisions.
|
||||
'enabled' => env('INVESTMOZ_IVA_CONSUMER_ENABLED', false),
|
||||
'rule_id' => env('INVESTMOZ_IVA_CONSUMER_RULE_ID'),
|
||||
'rule_version' => (int) env('INVESTMOZ_IVA_CONSUMER_RULE_VERSION', 0),
|
||||
];
|
||||
@@ -1,8 +1,9 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
// These lists are deliberately empty by default. A portal manager and MFA are
|
||||
// also required; governance roles never activate rules in the calculation engine.
|
||||
// Optional specific assignments. Existing authorised administration can maintain
|
||||
// fiscal parameters with MFA, without four people or four email designations.
|
||||
// Rule publication never activates the calculation consumer by itself.
|
||||
'editors' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TAX_RULE_EDITORS', '')))))),
|
||||
'reviewers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TAX_RULE_REVIEWERS', '')))))),
|
||||
'approvers' => array_values(array_filter(array_map('strtolower', array_map('trim', explode(',', (string) env('INVESTMOZ_TAX_RULE_APPROVERS', '')))))),
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
{
|
||||
"source": "investimentos nos corredores.docx",
|
||||
"source_sha256": "1473b06c48aa234e771660e3f2a51b9d2e4e1943bd52d878e0ae854ee6657055",
|
||||
"introduction": "Os corredores de desenvolvimento integram cadeias de valor prioritárias que podem ser apresentadas no portal InvesteMoz como oportunidades concretas de investimento na produção, transformação, logística e comercialização. Para cada corredor, são destacadas abaixo as oportunidades associadas aos produtos com maior potencial.",
|
||||
"segments": [
|
||||
"Produção primária e fornecimento de insumos",
|
||||
"Processamento e transformação agro-industrial",
|
||||
"Armazenagem, cadeia de frio e logística",
|
||||
"Embalagem, distribuição, comercialização e exportação",
|
||||
"Infraestruturas e serviços de apoio às cadeias de valor"
|
||||
],
|
||||
"groups": [
|
||||
{
|
||||
"name": "Corredor de Pemba–Lichinga",
|
||||
"opportunities": [
|
||||
{
|
||||
"chain": "Batata, trigo, feijão, milho e soja",
|
||||
"description": "Produção comercial, armazenamento e processamento de batata, trigo, feijão, milho e soja."
|
||||
},
|
||||
{
|
||||
"chain": "Algodão",
|
||||
"description": "Descaroçamento, fiação e produção de óleo e derivados de algodão."
|
||||
},
|
||||
{
|
||||
"chain": "Sésamo",
|
||||
"description": "Limpeza, prensagem, embalagem e exportação de sésamo."
|
||||
},
|
||||
{
|
||||
"chain": "Florestas",
|
||||
"description": "Viveiros, plantações comerciais, madeira processada e produtos florestais sustentáveis."
|
||||
},
|
||||
{
|
||||
"chain": "Avicultura",
|
||||
"description": "Produção de rações, incubação, criação, abate e cadeia de frio para avicultura."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Corredor de Nacala",
|
||||
"opportunities": [
|
||||
{
|
||||
"chain": "Mandioca",
|
||||
"description": "Produção e transformação de mandioca em farinha, amido e outros derivados."
|
||||
},
|
||||
{
|
||||
"chain": "Milho, amendoim e sésamo",
|
||||
"description": "Produção, armazenagem e processamento de milho, amendoim e sésamo."
|
||||
},
|
||||
{
|
||||
"chain": "Algodão",
|
||||
"description": "Descaroçamento e transformação de algodão."
|
||||
},
|
||||
{
|
||||
"chain": "Frutas e caju",
|
||||
"description": "Pomares, processamento, embalagem e exportação de frutas e caju."
|
||||
},
|
||||
{
|
||||
"chain": "Florestas",
|
||||
"description": "Silvicultura comercial, madeira processada e produtos florestais."
|
||||
},
|
||||
{
|
||||
"chain": "Avicultura",
|
||||
"description": "Produção de rações, criação, abate e distribuição de produtos avícolas."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Corredor do Vale do Zambeze",
|
||||
"opportunities": [
|
||||
{
|
||||
"chain": "Arroz",
|
||||
"description": "Produção irrigada, moagem, embalagem e comercialização de arroz."
|
||||
},
|
||||
{
|
||||
"chain": "Milho e batata",
|
||||
"description": "Produção, secagem, armazenagem e transformação de milho e batata."
|
||||
},
|
||||
{
|
||||
"chain": "Sésamo",
|
||||
"description": "Limpeza, prensagem e exportação de sésamo."
|
||||
},
|
||||
{
|
||||
"chain": "Algodão",
|
||||
"description": "Descaroçamento e transformação de algodão."
|
||||
},
|
||||
{
|
||||
"chain": "Avicultura",
|
||||
"description": "Produção de rações, incubação, criação e abate de aves."
|
||||
},
|
||||
{
|
||||
"chain": "Bovinos e caprinos",
|
||||
"description": "Criação, engorda, abate, processamento de carne e cadeia de frio para bovinos e caprinos."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Corredor da Beira",
|
||||
"opportunities": [
|
||||
{
|
||||
"chain": "Milho, trigo e arroz",
|
||||
"description": "Produção, silos, moagem e processamento de milho, trigo e arroz."
|
||||
},
|
||||
{
|
||||
"chain": "Soja",
|
||||
"description": "Esmagamento de soja, produção de óleo vegetal e fabrico de rações."
|
||||
},
|
||||
{
|
||||
"chain": "Hortícolas",
|
||||
"description": "Produção irrigada, conservação, embalagem e distribuição de hortícolas."
|
||||
},
|
||||
{
|
||||
"chain": "Sésamo",
|
||||
"description": "Limpeza, prensagem e exportação de sésamo."
|
||||
},
|
||||
{
|
||||
"chain": "Açúcar",
|
||||
"description": "Produção e refinação de açúcar e aproveitamento de subprodutos."
|
||||
},
|
||||
{
|
||||
"chain": "Florestas",
|
||||
"description": "Plantações comerciais, processamento de madeira e produtos florestais."
|
||||
},
|
||||
{
|
||||
"chain": "Carne bovina",
|
||||
"description": "Criação, engorda, abate, processamento e cadeia de frio para carne bovina."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Corredor do Limpopo",
|
||||
"opportunities": [
|
||||
{
|
||||
"chain": "Arroz",
|
||||
"description": "Produção irrigada, moagem, embalagem e comercialização de arroz."
|
||||
},
|
||||
{
|
||||
"chain": "Hortícolas",
|
||||
"description": "Produção em estufas e campo aberto, conservação, embalagem e distribuição de hortícolas."
|
||||
},
|
||||
{
|
||||
"chain": "Carne vermelha",
|
||||
"description": "Criação, engorda, abate, processamento e cadeia de frio para carne vermelha."
|
||||
},
|
||||
{
|
||||
"chain": "Avicultura",
|
||||
"description": "Produção de rações, incubação, criação, abate e distribuição de produtos avícolas."
|
||||
},
|
||||
{
|
||||
"chain": "Infraestruturas e serviços de apoio",
|
||||
"description": "Infraestruturas de irrigação, armazenagem, transporte refrigerado e centros de comercialização."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Corredor de Maputo",
|
||||
"opportunities": [
|
||||
{
|
||||
"chain": "Arroz",
|
||||
"description": "Produção irrigada, moagem, embalagem e fornecimento de arroz aos mercados urbanos e regionais."
|
||||
},
|
||||
{
|
||||
"chain": "Hortícolas",
|
||||
"description": "Produção, conservação, embalagem, transformação e distribuição de hortícolas."
|
||||
},
|
||||
{
|
||||
"chain": "Carne vermelha",
|
||||
"description": "Criação, engorda, abate, processamento, distribuição e exportação regional de carne vermelha."
|
||||
},
|
||||
{
|
||||
"chain": "Avicultura",
|
||||
"description": "Produção de rações, incubação, criação, abate e comercialização de produtos avícolas."
|
||||
},
|
||||
{
|
||||
"chain": "Infraestruturas e serviços de apoio",
|
||||
"description": "Plataformas logísticas, centros de distribuição, cadeia de frio e serviços de exportação."
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sector": "Agronegócio"
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
use App\Support\IsolatedQaDatabase;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
|
||||
throw new LogicException('Ensaie esta correcção apenas numa base QA isolada. A aplicação no destino exige decisão, backup/restauro e acção autenticada.');
|
||||
}
|
||||
|
||||
// Only fiscal rule maintenance changes. Opportunity/zone workflow checks remain intact.
|
||||
DB::statement('ALTER TABLE simulation_tax_rule_versions DROP CONSTRAINT tax_rule_stage_evidence_check, DROP CONSTRAINT tax_rule_approval_check, DROP CONSTRAINT tax_rule_publication_check');
|
||||
DB::statement("ALTER TABLE simulation_tax_rule_versions
|
||||
ADD CONSTRAINT tax_rule_stage_evidence_check CHECK(status NOT IN ('reviewed','rejected','approved','published','suspended','archived') OR (reviewer_id IS NOT NULL AND submitted_at IS NOT NULL AND reviewed_at IS NOT NULL AND length(trim(review_evidence))>=20)),
|
||||
ADD CONSTRAINT tax_rule_approval_check CHECK(status NOT IN ('approved','published','suspended','archived') OR (approver_id IS NOT NULL AND approved_at IS NOT NULL AND length(trim(approval_evidence))>=20)),
|
||||
ADD CONSTRAINT tax_rule_publication_check CHECK(status NOT IN ('published','suspended','archived') OR (publisher_id IS NOT NULL AND published_at IS NOT NULL AND length(trim(publication_evidence))>=20))");
|
||||
|
||||
DB::statement('ALTER TABLE investment_legal_sources ADD COLUMN fiscal_acceptance jsonb NULL');
|
||||
DB::statement("ALTER TABLE investment_legal_sources ADD CONSTRAINT investment_legal_source_fiscal_acceptance_check CHECK (
|
||||
fiscal_acceptance IS NULL OR COALESCE((
|
||||
fiscal_acceptance->>'scope'='fiscal_parameters' AND
|
||||
fiscal_acceptance->>'basis'='Tempo-official-sources-20261008' AND
|
||||
fiscal_acceptance->>'responsible_user_id'=owner_id::text AND
|
||||
fiscal_acceptance->>'sha256' ~ '^[a-f0-9]{64}$' AND
|
||||
fiscal_acceptance->>'legal_opinion'='false' AND fiscal_acceptance->>'independent_review'='false' AND
|
||||
length(trim(fiscal_acceptance->>'citation'))>=10 AND
|
||||
length(trim(fiscal_acceptance->>'official_origin'))>=10
|
||||
), false))");
|
||||
DB::statement('DROP POLICY simulation_tax_rule_versions_public_read ON simulation_tax_rule_versions');
|
||||
DB::statement("CREATE POLICY simulation_tax_rule_versions_public_read ON simulation_tax_rule_versions FOR SELECT USING (
|
||||
status='published' AND EXISTS (SELECT 1 FROM investment_legal_sources source
|
||||
WHERE source.id=simulation_tax_rule_versions.legal_source_id
|
||||
AND (source.validation_status='validated' OR (source.validation_status='pending'
|
||||
AND source.fiscal_acceptance->>'scope'='fiscal_parameters'
|
||||
AND source.fiscal_acceptance->>'basis'='Tempo-official-sources-20261008'
|
||||
AND source.fiscal_acceptance->>'sha256'=simulation_tax_rule_versions.source_sha256))
|
||||
AND source.version_no=simulation_tax_rule_versions.source_version_no
|
||||
AND source.valid_from<=simulation_tax_rule_versions.valid_from
|
||||
AND (source.valid_until IS NULL OR (simulation_tax_rule_versions.valid_until IS NOT NULL AND source.valid_until>=simulation_tax_rule_versions.valid_until))
|
||||
AND (simulation_tax_rule_versions.valid_until IS NOT NULL OR source.valid_until IS NULL)))");
|
||||
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
|
||||
throw new LogicException('Reversão permitida apenas em QA isolado.');
|
||||
}
|
||||
$used = DB::table('investment_legal_sources')->whereNotNull('fiscal_acceptance')->exists()
|
||||
|| DB::table('simulation_tax_rule_versions')->whereRaw('reviewer_id=author_id OR approver_id=author_id OR approver_id=reviewer_id OR publisher_id=author_id OR publisher_id=reviewer_id OR publisher_id=approver_id')->exists();
|
||||
if ($used) {
|
||||
throw new LogicException('Reversão recusada: conservar os cadastros e históricos legítimos; desactivar novas execuções em vez de apagar registos.');
|
||||
}
|
||||
DB::statement('ALTER TABLE simulation_tax_rule_versions DROP CONSTRAINT tax_rule_stage_evidence_check, DROP CONSTRAINT tax_rule_approval_check, DROP CONSTRAINT tax_rule_publication_check');
|
||||
DB::statement("ALTER TABLE simulation_tax_rule_versions
|
||||
ADD CONSTRAINT tax_rule_stage_evidence_check CHECK(status NOT IN ('reviewed','rejected','approved','published','suspended','archived') OR (reviewer_id IS NOT NULL AND reviewer_id<>author_id AND submitted_at IS NOT NULL AND reviewed_at IS NOT NULL AND length(trim(review_evidence))>=20)),
|
||||
ADD CONSTRAINT tax_rule_approval_check CHECK(status NOT IN ('approved','published','suspended','archived') OR (approver_id IS NOT NULL AND approver_id<>author_id AND approver_id<>reviewer_id AND approved_at IS NOT NULL AND length(trim(approval_evidence))>=20)),
|
||||
ADD CONSTRAINT tax_rule_publication_check CHECK(status NOT IN ('published','suspended','archived') OR (publisher_id IS NOT NULL AND publisher_id<>author_id AND publisher_id<>reviewer_id AND publisher_id<>approver_id AND published_at IS NOT NULL AND length(trim(publication_evidence))>=20))");
|
||||
DB::statement('DROP POLICY simulation_tax_rule_versions_public_read ON simulation_tax_rule_versions');
|
||||
(require __DIR__.'/2026_10_03_190000_allow_public_read_of_published_tax_parameters.php')->up();
|
||||
DB::statement('ALTER TABLE investment_legal_sources DROP CONSTRAINT investment_legal_source_fiscal_acceptance_check');
|
||||
DB::statement('ALTER TABLE investment_legal_sources DROP COLUMN fiscal_acceptance');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
<?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::create('portal_tenders', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->jsonb('draft');
|
||||
$t->unsignedInteger('version')->default(1);
|
||||
$t->uuid('published_version_id')->nullable();
|
||||
$t->foreignId('created_by')->constrained('users')->restrictOnDelete();
|
||||
$t->timestampsTz();
|
||||
});
|
||||
Schema::create('portal_tender_versions', function (Blueprint $t) {
|
||||
$t->uuid('id')->primary();
|
||||
$t->foreignUuid('tender_id')->constrained('portal_tenders')->restrictOnDelete();
|
||||
$t->unsignedInteger('version');
|
||||
$t->string('act', 24);
|
||||
$t->jsonb('payload');
|
||||
$t->text('reason');
|
||||
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
|
||||
$t->timestampTz('published_at')->nullable();
|
||||
$t->timestampTz('created_at')->useCurrent();
|
||||
$t->unique(['tender_id', 'version']);
|
||||
});
|
||||
Schema::create('portal_tender_watches', function (Blueprint $t) {
|
||||
$t->foreignUuid('tender_id')->constrained('portal_tenders')->restrictOnDelete();
|
||||
$t->foreignId('user_id')->constrained('users')->restrictOnDelete();
|
||||
$t->uuid('seen_version_id')->nullable();
|
||||
$t->timestampsTz();
|
||||
$t->primary(['tender_id', 'user_id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::table('portal_tenders')->exists()) {
|
||||
throw new RuntimeException('Preserve procedures, acts and history; use a reviewed data reversal.');
|
||||
}
|
||||
Schema::dropIfExists('portal_tender_watches');
|
||||
Schema::dropIfExists('portal_tender_versions');
|
||||
Schema::dropIfExists('portal_tenders');
|
||||
}
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user