Compare commits
554
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52faf89a2c | ||
|
|
daf8623441 | ||
|
|
63147312e2 | ||
|
|
fde7343894 | ||
|
|
e0987afb0e | ||
|
|
bad05eb092 | ||
|
|
b2812e5925 | ||
|
|
fdadc8ace7 | ||
|
|
979f3f850e | ||
|
|
b81f477bf2 | ||
|
|
568a488ae7 | ||
|
|
d96f9c6bf5 | ||
|
|
4875c4beb9 | ||
|
|
3f7082a3e6 | ||
|
|
23ecccfaad | ||
|
|
fde644af79 | ||
|
|
ed87593a01 | ||
|
|
332c16ebb5 | ||
|
|
17444aaaa5 | ||
|
|
a1af1f60cd | ||
|
|
fcac2d5ebd | ||
|
|
789fffd098 | ||
|
|
26c55ffab0 | ||
|
|
502e3ec4d5 | ||
|
|
0bbb02b7ec | ||
|
|
54d1b2a543 | ||
|
|
7f110f3c8b | ||
|
|
6520d303f7 | ||
|
|
4b3578acbf | ||
|
|
47dae1b77e | ||
|
|
2c8eb95e10 | ||
|
|
5f202fe5b5 | ||
|
|
1b2ede41e2 | ||
|
|
9bfd95083f | ||
|
|
d7a9284d5f | ||
|
|
f94007acfc | ||
|
|
6e8de43ae7 | ||
|
|
77d133ef0e | ||
|
|
63b654ba1b | ||
|
|
dc34894bde | ||
|
|
930013f920 | ||
|
|
6d14769369 | ||
|
|
3c293dbee0 | ||
|
|
a022ed9848 | ||
|
|
2f58b7d438 | ||
|
|
70c71739b2 | ||
|
|
324a20ea73 | ||
|
|
150bef4b89 | ||
|
|
a4dc45db5d | ||
|
|
569a1cd750 | ||
|
|
aae67c169d | ||
|
|
daf0465489 | ||
|
|
6ededb597a | ||
|
|
d134a92d16 | ||
|
|
974139a710 | ||
|
|
cf4e0638c1 | ||
|
|
bbdac0821a | ||
|
|
838ad941a2 | ||
|
|
6f363df462 | ||
|
|
814fe0a9b7 | ||
|
|
e182d1d79d | ||
|
|
9a093046e5 | ||
|
|
5fdcc98d05 | ||
|
|
4ee427bad4 | ||
|
|
669cb8979b | ||
|
|
a8026f346e | ||
|
|
7fdb6b424b | ||
|
|
56c9788928 | ||
|
|
dc14f01e14 | ||
|
|
fa9c5a5be8 | ||
|
|
1ee0c6d21d | ||
|
|
9fda6d6e12 | ||
|
|
289877d6a4 | ||
|
|
56c0c6a7ca | ||
|
|
74f7f93a75 | ||
|
|
18fefc5a09 | ||
|
|
0ff402a11d | ||
|
|
51d536b7ba | ||
|
|
c64ecea04e | ||
|
|
403c444a3e | ||
|
|
03cd76ae28 | ||
|
|
a78abf06d0 | ||
|
|
d3b3cb6cb2 | ||
|
|
52f54655d2 | ||
|
|
11fcf48156 | ||
|
|
4f9450a71d | ||
|
|
4f1be49d39 | ||
|
|
1afab4a2a7 | ||
|
|
3439f35038 | ||
|
|
1244fc8b7a | ||
|
|
c85e772d2f | ||
|
|
109e0cef51 | ||
|
|
1436074819 | ||
|
|
11a6cee981 | ||
|
|
717370e537 | ||
|
|
d5f11462e9 | ||
|
|
f8d57bddf9 | ||
|
|
d7a76ab17a | ||
|
|
ea2bceb5ce | ||
|
|
3eda84ef79 | ||
|
|
245549f9e8 | ||
|
|
a7434cd27c | ||
|
|
71551deb73 | ||
|
|
b68936290c | ||
|
|
f33d99b4d5 | ||
|
|
7b2f368642 | ||
|
|
632dc06930 | ||
|
|
ff84ab648f | ||
|
|
992c97ad4e | ||
|
|
ae0d74bb3a | ||
|
|
894ca4ec69 | ||
|
|
d77c51f291 | ||
|
|
ba83afe7d8 | ||
|
|
4da7a16a50 | ||
|
|
57d4bc1cf4 | ||
|
|
eccd95f9e7 | ||
|
|
e4e67e8228 | ||
|
|
0bd5d49550 | ||
|
|
46ab0abcb0 | ||
|
|
aed020d19e | ||
|
|
56b94011ba | ||
|
|
1649710cf7 | ||
|
|
e07f89da3d | ||
|
|
97171c5e1e | ||
|
|
ab2ff2fdbc | ||
|
|
a2122dc34c | ||
|
|
07dd6dd221 | ||
|
|
d37fffb2d2 | ||
|
|
31651a76b1 | ||
|
|
45fd591c7f | ||
|
|
17d633c99c | ||
|
|
5aaf1a56f9 | ||
|
|
823d6b3559 | ||
|
|
2116f66b2b | ||
|
|
8f1ab24b22 | ||
|
|
56475acb2f | ||
|
|
f2f6ffca88 | ||
|
|
0effdc9fcb | ||
|
|
e9fe102259 | ||
|
|
0b0dbc5214 | ||
|
|
44d0858cee | ||
|
|
043dd35d8e | ||
|
|
75bb95f2b4 | ||
|
|
f400e56a5b | ||
|
|
a2de725901 | ||
|
|
cd65e41e84 | ||
|
|
82d0d05887 | ||
|
|
744bfccb69 | ||
|
|
2f684e5984 | ||
|
|
b8435c1a0e | ||
|
|
b8d45796dd | ||
|
|
dc1c85bf8e | ||
|
|
5e02c23af8 | ||
|
|
40b76278d5 | ||
|
|
664c88c8f7 | ||
|
|
f6c3c28ac6 | ||
|
|
7a11c4ef8f | ||
|
|
c42b36db62 | ||
|
|
acf8ec3cb5 | ||
|
|
ec6d951e31 | ||
|
|
321901cec5 | ||
|
|
5fa64bc0f4 | ||
|
|
d3cdddde96 | ||
|
|
85e3cd5c7b | ||
|
|
abc050f14d | ||
|
|
ce746d889d | ||
|
|
cccead8a3c | ||
|
|
2b33a1c343 | ||
|
|
dbd8bac5aa | ||
|
|
4d6f828230 | ||
|
|
aa79180b47 | ||
|
|
da0d8abb47 | ||
|
|
359ee45f57 | ||
|
|
3d88e3e92e | ||
|
|
5c0cb25cea | ||
|
|
3dda7130ee | ||
|
|
0ce373670f | ||
|
|
aa03d346ba | ||
|
|
fb7b5c35b3 | ||
|
|
6af7092e83 | ||
|
|
49b448eb47 | ||
|
|
fa32a2b9e1 | ||
|
|
1b7ccfee23 | ||
|
|
479b66815c | ||
|
|
525d0ab672 | ||
|
|
0f4df8a4d1 | ||
|
|
08ade21bab | ||
|
|
bf866f9862 | ||
|
|
d1551dab08 | ||
|
|
4dce666134 | ||
|
|
bee96fc9fd | ||
|
|
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 |
@@ -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_DEBUG=true
|
||||||
APP_URL=http://localhost:8000
|
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_LOCALE=en
|
||||||
APP_FALLBACK_LOCALE=en
|
APP_FALLBACK_LOCALE=en
|
||||||
APP_FAKER_LOCALE=en_US
|
APP_FAKER_LOCALE=en_US
|
||||||
|
|||||||
@@ -12,3 +12,6 @@ database/data/economic-references-lot-01.json text eol=crlf
|
|||||||
CHANGELOG.md export-ignore
|
CHANGELOG.md export-ignore
|
||||||
README.md export-ignore
|
README.md export-ignore
|
||||||
.github/workflows/browser-tests.yml 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
|
# 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
|
## Regras permanentes do InvesteMoz — decisão da Tempo, 12/10/2026
|
||||||
|
|
||||||
1. O portal InvesteMoz é propriedade da Tempo, Lda.
|
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.
|
- 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.
|
- 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.
|
- 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.
@@ -4,6 +4,7 @@ namespace App\Console\Commands;
|
|||||||
|
|
||||||
use App\Jobs\ScanDocumentForMalware;
|
use App\Jobs\ScanDocumentForMalware;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Support\CheckedFile;
|
||||||
use Illuminate\Console\Command;
|
use Illuminate\Console\Command;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
@@ -53,7 +54,9 @@ class ImportDocumentBatch extends Command
|
|||||||
];
|
];
|
||||||
|
|
||||||
private const TRIO_MANIFEST_SHA256 = '9210ad7e1bea557349c440fd8295b321a10c2ddd34cc170f3dad18b5517751f8';
|
private const TRIO_MANIFEST_SHA256 = '9210ad7e1bea557349c440fd8295b321a10c2ddd34cc170f3dad18b5517751f8';
|
||||||
|
|
||||||
private const TRIO_REUSED_IMAGE_SHA256 = '28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa';
|
private const TRIO_REUSED_IMAGE_SHA256 = '28f41f12e10ab34545d8e432f6e8c74f86960e17e0c4a9956f514bcde4881eaa';
|
||||||
|
|
||||||
private const TRIO_HASHES = [
|
private const TRIO_HASHES = [
|
||||||
'legacy-tempo-post-173209-20260623' => '926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941',
|
'legacy-tempo-post-173209-20260623' => '926f5e4096737c936c9d5002ebdc64be9e63b0c0822023d17ce618111a65c941',
|
||||||
'legacy-tempo-post-173218-20260616' => '43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5',
|
'legacy-tempo-post-173218-20260616' => '43612c358c7573475cea24ef4825c5b7c7925306fa5861051220eed3f4e333b5',
|
||||||
@@ -276,7 +279,9 @@ class ImportDocumentBatch extends Command
|
|||||||
return $failures > 0 ? self::FAILURE : self::SUCCESS;
|
return $failures > 0 ? self::FAILURE : self::SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The extra CLI path is a named, byte-bound pilot; it is not a general active import gate. */
|
/** The extra CLI path is a named, byte-bound pilot; it is not a general active import gate.
|
||||||
|
* @param array<array-key, mixed> $manifest
|
||||||
|
*/
|
||||||
private function validatePilot(string $manifestPath, string $manifestBytes, array $manifest, string $staging, bool $apply, mixed $actorId, bool $sectors = false, bool $trio = false): void
|
private function validatePilot(string $manifestPath, string $manifestBytes, array $manifest, string $staging, bool $apply, mixed $actorId, bool $sectors = false, bool $trio = false): void
|
||||||
{
|
{
|
||||||
$allowed = $trio ? self::TRIO_HASHES : ($sectors ? self::SECTORS_HASHES : self::PILOT_HASHES);
|
$allowed = $trio ? self::TRIO_HASHES : ($sectors ? self::SECTORS_HASHES : self::PILOT_HASHES);
|
||||||
@@ -310,7 +315,7 @@ class ImportDocumentBatch extends Command
|
|||||||
->where('d.rights_status', 'authorized')->where('r.rights_status', 'authorized')->where('r.published', true)
|
->where('d.rights_status', 'authorized')->where('r.rights_status', 'authorized')->where('r.published', true)
|
||||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')->get(['d.storage_key']);
|
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')->get(['d.storage_key']);
|
||||||
if ($images->count() !== 1 || ! Storage::disk('local')->exists($images[0]->storage_key)
|
if ($images->count() !== 1 || ! Storage::disk('local')->exists($images[0]->storage_key)
|
||||||
|| ! hash_equals(self::TRIO_REUSED_IMAGE_SHA256, hash_file('sha256', Storage::disk('local')->path($images[0]->storage_key)))) {
|
|| ! hash_equals(self::TRIO_REUSED_IMAGE_SHA256, CheckedFile::sha256(Storage::disk('local')->path($images[0]->storage_key)))) {
|
||||||
throw new RuntimeException('The shared image must already exist once, published, authorized and clean with the exact original bytes; no image is imported.');
|
throw new RuntimeException('The shared image must already exist once, published, authorized and clean with the exact original bytes; no image is imported.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -344,8 +349,8 @@ class ImportDocumentBatch extends Command
|
|||||||
|| ! str_ends_with($proof['restore_target']['database'] ?? '', '_test') || (int) ($proof['restore_target']['port'] ?? 0) !== 55441
|
|| ! str_ends_with($proof['restore_target']['database'] ?? '', '_test') || (int) ($proof['restore_target']['port'] ?? 0) !== 55441
|
||||||
|| $verified === false || $verified > time() || $verified < time() - 86400
|
|| $verified === false || $verified > time() || $verified < time() - 86400
|
||||||
|| ! is_file($proof['dump_path'] ?? '') || ! is_file($proof['files_path'] ?? '')
|
|| ! is_file($proof['dump_path'] ?? '') || ! is_file($proof['files_path'] ?? '')
|
||||||
|| ! hash_equals($proof['sha256'] ?? '', hash_file('sha256', $proof['dump_path']))
|
|| ! hash_equals($proof['sha256'] ?? '', CheckedFile::sha256($proof['dump_path']))
|
||||||
|| ! hash_equals($proof['files_sha256'] ?? '', hash_file('sha256', $proof['files_path']))) {
|
|| ! hash_equals($proof['files_sha256'] ?? '', CheckedFile::sha256($proof['files_path']))) {
|
||||||
throw new RuntimeException('Backup/restoration identity, freshness or integrity does not match the active pilot.');
|
throw new RuntimeException('Backup/restoration identity, freshness or integrity does not match the active pilot.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<?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\CheckedFile;
|
||||||
|
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(CheckedFile::read(database_path('qa/iva-general-net-v1.json')), true, flags: JSON_THROW_ON_ERROR);
|
||||||
|
$actualHash = CheckedFile::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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ namespace App\Http\Controllers\Api\V1;
|
|||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
use App\Models\Sector;
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Facades\Cache;
|
||||||
@@ -21,7 +21,7 @@ class HomeController extends Controller
|
|||||||
$locale = $validated['locale'] ?? 'pt';
|
$locale = $validated['locale'] ?? 'pt';
|
||||||
|
|
||||||
$data = Cache::remember("portal_home_sector_organization_v1_{$locale}", now()->addMinutes(10), function () {
|
$data = Cache::remember("portal_home_sector_organization_v1_{$locale}", now()->addMinutes(10), function () {
|
||||||
$sectors = \App\Services\SectorOrganization::catalog();
|
$sectors = SectorOrganization::catalog();
|
||||||
|
|
||||||
$featured = Opportunity::with('sector:id,name,slug')
|
$featured = Opportunity::with('sector:id,name,slug')
|
||||||
->published()->where('is_featured', true)
|
->published()->where('is_featured', true)
|
||||||
|
|||||||
@@ -8,11 +8,13 @@ use App\Http\Requests\StoreInterestRequestRequest;
|
|||||||
use App\Jobs\NotifyInterestReceived;
|
use App\Jobs\NotifyInterestReceived;
|
||||||
use App\Models\ExistingBusiness;
|
use App\Models\ExistingBusiness;
|
||||||
use App\Models\InterestRequest;
|
use App\Models\InterestRequest;
|
||||||
|
use App\Models\InvestmentSubmission;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
use App\Services\IdempotencyConflict;
|
use App\Services\IdempotencyConflict;
|
||||||
use App\Services\InterestSubmission;
|
use App\Services\InterestSubmission;
|
||||||
use Illuminate\Database\QueryException;
|
use Illuminate\Database\QueryException;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Log;
|
use Illuminate\Support\Facades\Log;
|
||||||
use Illuminate\Support\Facades\Queue;
|
use Illuminate\Support\Facades\Queue;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
@@ -26,7 +28,7 @@ class InterestRequestController extends Controller
|
|||||||
$validated = [...$request->validated(), '_actor_id' => $request->user()->id];
|
$validated = [...$request->validated(), '_actor_id' => $request->user()->id];
|
||||||
$key = $request->header('Idempotency-Key');
|
$key = $request->header('Idempotency-Key');
|
||||||
abort_unless(is_string($key), 422, 'Identificador do envio em falta.');
|
abort_unless(is_string($key), 422, 'Identificador do envio em falta.');
|
||||||
Validator::make(['idempotency_key' => $key], ['idempotency_key' => [$key === null ? 'nullable' : 'required', 'uuid']])->validate();
|
Validator::make(['idempotency_key' => $key], ['idempotency_key' => ['required', 'uuid']])->validate();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$interestRequest = $submission->receive($validated, $key, function () use ($request, $validated) {
|
$interestRequest = $submission->receive($validated, $key, function () use ($request, $validated) {
|
||||||
@@ -78,19 +80,20 @@ class InterestRequestController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$row = \App\Models\InvestmentSubmission::create([
|
$row = InvestmentSubmission::create([
|
||||||
'user_id' => $request->user()->id, 'opportunity_id' => $opportunity?->id,
|
'user_id' => $request->user()->id, 'opportunity_id' => $opportunity?->id,
|
||||||
'interest_request_id' => $interest->id, 'status' => 'submitted', 'version' => 1,
|
'interest_request_id' => $interest->id, 'status' => 'submitted', 'version' => 1,
|
||||||
'payload' => ['simple_participation' => true, 'opportunity_title' => $opportunity?->title ?? $business?->title, 'opportunity_reference' => $opportunity?->reference, 'phone' => $validated['phone'] ?? null, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null, 'full_name' => $validated['fullName'], 'email' => $validated['email'],
|
'payload' => ['simple_participation' => true, 'opportunity_title' => $opportunity->title ?? $business?->public_title, 'opportunity_reference' => $opportunity?->reference, 'phone' => $validated['phone'] ?? null, 'declared_origin_country_code' => $validated['declared_origin_country_code'] ?? null, 'full_name' => $validated['fullName'], 'email' => $validated['email'],
|
||||||
'objective' => $validated['message'], 'sector' => $validated['sectorInterest'],
|
'objective' => $validated['message'], 'sector' => $validated['sectorInterest'],
|
||||||
'country' => $validated['country'], 'existing_business_id' => $business?->id,
|
'country' => $validated['country'], 'existing_business_id' => $business?->id,
|
||||||
'modality' => $validated['modality'] ?? null],
|
'modality' => $validated['modality'] ?? null],
|
||||||
]);
|
]);
|
||||||
\Illuminate\Support\Facades\DB::table('investment_submission_events')->insert([
|
DB::table('investment_submission_events')->insert([
|
||||||
'submission_id' => $row->id, 'actor_id' => $request->user()->id,
|
'submission_id' => $row->id, 'actor_id' => $request->user()->id,
|
||||||
'action' => 'submitted', 'version' => 1, 'created_at' => now(),
|
'action' => 'submitted', 'version' => 1, 'created_at' => now(),
|
||||||
]);
|
]);
|
||||||
$interest->forceFill(['metadata' => [...$interest->metadata, 'submission_id' => $row->id]])->save();
|
$interest->forceFill(['metadata' => [...$interest->metadata, 'submission_id' => $row->id]])->save();
|
||||||
|
|
||||||
return $interest;
|
return $interest;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -99,7 +102,8 @@ class InterestRequestController extends Controller
|
|||||||
'message' => 'Manifestação de interesse registada com sucesso.',
|
'message' => 'Manifestação de interesse registada com sucesso.',
|
||||||
'data' => [
|
'data' => [
|
||||||
'reference' => $interestRequest->reference,
|
'reference' => $interestRequest->reference,
|
||||||
'status' => $interestRequest->status,
|
// The POST acknowledgement is stable on replay; current workflow state is in tracking.
|
||||||
|
'status' => InterestStatus::Received,
|
||||||
'tracking_url' => '/investidor/manifestacoes',
|
'tracking_url' => '/investidor/manifestacoes',
|
||||||
],
|
],
|
||||||
], 201);
|
], 201);
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ namespace App\Http\Controllers\Api\V1;
|
|||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
|
use App\Services\InvestmentCatalogue;
|
||||||
|
use App\Services\OpportunityMaturity;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
@@ -15,6 +18,11 @@ class OpportunityController extends Controller
|
|||||||
'q' => ['nullable', 'string', 'max:120'],
|
'q' => ['nullable', 'string', 'max:120'],
|
||||||
'sector' => ['nullable', 'string', 'max:80'],
|
'sector' => ['nullable', 'string', 'max:80'],
|
||||||
'province' => ['nullable', 'string', 'max:80'],
|
'province' => ['nullable', 'string', 'max:80'],
|
||||||
|
'province_id' => ['nullable', 'uuid'],
|
||||||
|
'district_id' => ['nullable', 'uuid'],
|
||||||
|
'admin_post_id' => ['nullable', 'uuid'],
|
||||||
|
'locality_id' => ['nullable', 'uuid'],
|
||||||
|
'geo_location_id' => ['nullable', 'uuid'],
|
||||||
'maturity_level' => ['nullable', 'integer', 'between:1,6'],
|
'maturity_level' => ['nullable', 'integer', 'between:1,6'],
|
||||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||||
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
||||||
@@ -47,22 +55,24 @@ class OpportunityController extends Controller
|
|||||||
|
|
||||||
if (! empty($validated['sector'])) {
|
if (! empty($validated['sector'])) {
|
||||||
$sector = $validated['sector'];
|
$sector = $validated['sector'];
|
||||||
\App\Services\SectorOrganization::constrain($query, $sector);
|
SectorOrganization::constrain($query, $sector);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! empty($validated['province'])) {
|
$territory = array_intersect_key($validated, array_flip(['province', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'geo_location_id']));
|
||||||
$query->where('province', $validated['province']);
|
if (array_filter($territory, fn ($value) => $value !== null && $value !== '') !== []) {
|
||||||
|
// Keep the legacy search's sorting and non-territorial filters while sharing the public territorial contract.
|
||||||
|
$query->whereIn('opportunities.id', app(InvestmentCatalogue::class)->query($territory)->reorder()->select('opportunities.id'));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! empty($validated['maturity_level'])) {
|
if (! empty($validated['maturity_level'])) {
|
||||||
\App\Services\OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
|
OpportunityMaturity::constrainSearch($query, 'historical:'.$validated['maturity_level']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$results = $query->orderByDesc('is_featured')
|
$results = $query->orderByDesc('is_featured')
|
||||||
->orderByDesc('published_at')
|
->orderByDesc('published_at')
|
||||||
->paginate($validated['per_page'] ?? 12);
|
->paginate($validated['per_page'] ?? 12);
|
||||||
|
|
||||||
return response()->json($results);
|
return response()->json($results->withQueryString()->through(fn ($record) => app(InvestmentCatalogue::class)->presentLocation($record)));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(string $slug): JsonResponse
|
public function show(string $slug): JsonResponse
|
||||||
|
|||||||
@@ -3,7 +3,10 @@
|
|||||||
namespace App\Http\Controllers\Api\V1;
|
namespace App\Http\Controllers\Api\V1;
|
||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Models\Sector;
|
||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
|
use App\Services\EconomicReferenceCatalog;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Database\Query\Builder;
|
use Illuminate\Database\Query\Builder;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -44,7 +47,9 @@ class ReferenceCatalogController extends Controller
|
|||||||
|
|
||||||
$cae = $catalog === 'economic-activities' && ($data['origin'] ?? 'portal') === 'cae';
|
$cae = $catalog === 'economic-activities' && ($data['origin'] ?? 'portal') === 'cae';
|
||||||
$versionQuery = DB::table('reference_catalog_versions')->where('catalog_code', $cae ? 'economic-activities-cae' : $catalog)->where('locale', 'pt-MZ');
|
$versionQuery = DB::table('reference_catalog_versions')->where('catalog_code', $cae ? 'economic-activities-cae' : $catalog)->where('locale', 'pt-MZ');
|
||||||
if ($cae && ! app(\App\Services\EconomicReferenceCatalog::class)->available()) { $versionQuery->whereRaw('false'); }
|
if ($cae && ! app(EconomicReferenceCatalog::class)->available()) {
|
||||||
|
$versionQuery->whereRaw('false');
|
||||||
|
}
|
||||||
if (isset($data['version'])) {
|
if (isset($data['version'])) {
|
||||||
$versionQuery->where('version_no', $data['version'])->whereIn('status', ['published', 'retired']);
|
$versionQuery->where('version_no', $data['version'])->whereIn('status', ['published', 'retired']);
|
||||||
} else {
|
} else {
|
||||||
@@ -82,7 +87,7 @@ class ReferenceCatalogController extends Controller
|
|||||||
$page = $query->orderBy('code')->orderBy('id')->paginate($data['per_page'] ?? 20)->withQueryString();
|
$page = $query->orderBy('code')->orderBy('id')->paginate($data['per_page'] ?? 20)->withQueryString();
|
||||||
$items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, (array) $row))->values();
|
$items = collect($page->items())->map(fn (object $row): array => $this->present($catalog, (array) $row))->values();
|
||||||
if ($cae) {
|
if ($cae) {
|
||||||
$paths = app(\App\Services\EconomicReferenceCatalog::class)->activities()->keyBy('id');
|
$paths = app(EconomicReferenceCatalog::class)->activities()->keyBy('id');
|
||||||
$items = $items->map(fn ($row) => [...$row, 'level' => $paths[$row['id']]->level, 'path' => $paths[$row['id']]->path, 'source_version' => $paths[$row['id']]->source_version, 'edition' => 'not_determined', 'divergence' => '600/579 documentalmente aberta']);
|
$items = $items->map(fn ($row) => [...$row, 'level' => $paths[$row['id']]->level, 'path' => $paths[$row['id']]->path, 'source_version' => $paths[$row['id']]->source_version, 'edition' => 'not_determined', 'divergence' => '600/579 documentalmente aberta']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,15 +174,17 @@ class ReferenceCatalogController extends Controller
|
|||||||
->where('valid_from', '<=', today()->toDateString())
|
->where('valid_from', '<=', today()->toDateString())
|
||||||
->where(fn (Builder $builder) => $builder->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString()))
|
->where(fn (Builder $builder) => $builder->whereNull('valid_to')->orWhere('valid_to', '>', today()->toDateString()))
|
||||||
->select(['id', 'code', 'label_pt_mz as name', 'parent_id', 'sector_id', 'version_no']);
|
->select(['id', 'code', 'label_pt_mz as name', 'parent_id', 'sector_id', 'version_no']);
|
||||||
if (empty($data['version'])) $query->where('id', '!=', \App\Services\SectorOrganization::LEGACY_ACTIVITY_ID);
|
if (empty($data['version'])) {
|
||||||
|
$query->where('id', '!=', SectorOrganization::LEGACY_ACTIVITY_ID);
|
||||||
|
}
|
||||||
if (array_key_exists('parent_id', $data) && $data['parent_id'] !== null) {
|
if (array_key_exists('parent_id', $data) && $data['parent_id'] !== null) {
|
||||||
$query->where('parent_id', $data['parent_id']);
|
$query->where('parent_id', $data['parent_id']);
|
||||||
} else {
|
} else {
|
||||||
$query->whereNull('parent_id');
|
$query->whereNull('parent_id');
|
||||||
}
|
}
|
||||||
if (! empty($data['sector_id'])) {
|
if (! empty($data['sector_id'])) {
|
||||||
$sector = \App\Models\Sector::find($data['sector_id']);
|
$sector = Sector::whereKey($data['sector_id'])->first();
|
||||||
$query->whereIn('sector_id', $sector ? \App\Models\Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
$query->whereIn('sector_id', $sector ? Sector::whereIn('slug', SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
||||||
}
|
}
|
||||||
if (! empty($data['q'])) {
|
if (! empty($data['q'])) {
|
||||||
$this->search($query, $data['q'], ['code', 'label_pt_mz']);
|
$this->search($query, $data['q'], ['code', 'label_pt_mz']);
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ namespace App\Http\Controllers\Api\V1;
|
|||||||
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use App\Models\Sector;
|
use App\Models\Sector;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
|
|
||||||
class SectorController extends Controller
|
class SectorController extends Controller
|
||||||
{
|
{
|
||||||
public function index(): JsonResponse
|
public function index(): JsonResponse
|
||||||
{
|
{
|
||||||
$sectors = \App\Services\SectorOrganization::catalog()->map(fn ($s) => [
|
$sectors = SectorOrganization::catalog()->map(fn ($s) => [
|
||||||
'id' => $s->id, 'name' => $s->name, 'slug' => $s->slug,
|
'id' => $s->id, 'name' => $s->name, 'slug' => $s->slug,
|
||||||
'shortDescription' => $s->short_description, 'description' => $s->description,
|
'shortDescription' => $s->short_description, 'description' => $s->description,
|
||||||
'icon' => $s->icon, 'opportunitiesCount' => $s->opportunities_count,
|
'icon' => $s->icon, 'opportunitiesCount' => $s->opportunities_count,
|
||||||
@@ -25,7 +26,8 @@ class SectorController extends Controller
|
|||||||
$sector = Sector::with(['opportunities' => fn ($q) => $q->published()])
|
$sector = Sector::with(['opportunities' => fn ($q) => $q->published()])
|
||||||
->where('slug', $slug)->firstOrFail();
|
->where('slug', $slug)->firstOrFail();
|
||||||
|
|
||||||
$sector->setRelation('opportunities', \App\Services\SectorOrganization::opportunities($sector)->get());
|
$sector->setRelation('opportunities', SectorOrganization::opportunities($sector)->get());
|
||||||
return response()->json(['success' => true, 'data' => $sector, 'canonical_url' => \App\Services\SectorOrganization::href($slug), 'specialization_of' => $slug === 'fintech' ? 'mercado-financeiro' : null]);
|
|
||||||
|
return response()->json(['success' => true, 'data' => $sector, 'canonical_url' => SectorOrganization::href($slug), 'specialization_of' => $slug === 'fintech' ? 'mercado-financeiro' : null]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,11 +37,17 @@ class SimulationController extends Controller
|
|||||||
$token = $actorId === null ? $request->header('X-Simulation-Token') : null;
|
$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.');
|
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();
|
$validated = $request->validated();
|
||||||
$data = ['base' => (string) $validated['base'], 'rate' => (string) $validated['rate'],
|
$organizationId = $validated['organization_id'] ?? null;
|
||||||
'reduction' => (string) ($validated['reduction'] ?? '0'), 'organization_id' => $validated['organization_id'] ?? null];
|
|
||||||
$organizationId = $data['organization_id'] ?? null;
|
|
||||||
$execution->authorizeOrganization($actorId, $organizationId);
|
$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'];
|
$simulation = $result['simulation'];
|
||||||
$body = ['data' => $simulation, 'replayed' => $result['replayed']];
|
$body = ['data' => $simulation, 'replayed' => $result['replayed']];
|
||||||
if ($actorId === null) {
|
if ($actorId === null) {
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers\Api\V1;
|
||||||
|
|
||||||
|
use App\Http\Controllers\Controller;
|
||||||
|
use App\Jobs\ScanDocumentForMalware;
|
||||||
|
use App\Services\SimulationFormDrafts;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use stdClass;
|
||||||
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
|
|
||||||
|
class SimulationOfferDocumentController extends Controller
|
||||||
|
{
|
||||||
|
public function store(Request $request, string $id, SimulationFormDrafts $drafts): JsonResponse
|
||||||
|
{
|
||||||
|
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());
|
||||||
|
abort_unless(is_string($hash), 422, 'Não foi possível verificar o conteúdo do anexo.');
|
||||||
|
$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): JsonResponse
|
||||||
|
{
|
||||||
|
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): BinaryFileResponse
|
||||||
|
{
|
||||||
|
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 !== null, 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);
|
||||||
|
$hash = hash_file('sha256', $path);
|
||||||
|
abort_unless(is_string($hash) && hash_equals(trim($doc->sha256), $hash), 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']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array{id: string, draftId: string, name: string, sha256: string, scan: string, url: string} */
|
||||||
|
private function metadata(string $id, stdClass $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_start'],
|
||||||
$input['period_end'],
|
$input['period_end'],
|
||||||
$input['context'] ?? [],
|
$input['context'] ?? [],
|
||||||
|
$input['component'] === 'IVA',
|
||||||
);
|
);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'component' => $input['component'],
|
'component' => $input['component'],
|
||||||
'period' => ['start' => $input['period_start'], 'end' => $input['period_end']],
|
'period' => ['start' => $input['period_start'], 'end' => $input['period_end']],
|
||||||
'assumptions' => $input['context'] ?? [],
|
'assumptions' => $input['context'] ?? [],
|
||||||
'parameters' => $data,
|
'parameters' => $input['component'] === 'IVA' ? $data['parameters'] : $data,
|
||||||
|
'diagnostics' => $input['component'] === 'IVA' ? $data['diagnostics'] : [],
|
||||||
])->header('Cache-Control', 'no-store');
|
])->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,86 @@
|
|||||||
|
<?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\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
|
||||||
|
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): Response
|
||||||
|
{
|
||||||
|
$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): JsonResponse
|
||||||
|
{
|
||||||
|
$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): JsonResponse
|
||||||
|
{
|
||||||
|
$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): JsonResponse
|
||||||
|
{
|
||||||
|
$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];
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Jobs\ScanDocumentForMalware;
|
use App\Jobs\ScanDocumentForMalware;
|
||||||
|
use App\Services\DocumentManagementAccess;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -12,7 +13,7 @@ class DocumentMalwareController extends Controller
|
|||||||
public function retry(Request $request, string $id): RedirectResponse
|
public function retry(Request $request, string $id): RedirectResponse
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($id, $request): void {
|
DB::transaction(function () use ($id, $request): void {
|
||||||
$document = app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->lockForUpdate()->first();
|
$document = app(DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->lockForUpdate()->first();
|
||||||
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404);
|
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404);
|
||||||
abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422,
|
abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422,
|
||||||
'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.');
|
'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.');
|
||||||
|
|||||||
@@ -2,63 +2,79 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Services\VerifiedDocumentBinary;
|
use App\Services\DocumentManagementAccess;
|
||||||
|
use App\Services\EditorialInstallation;
|
||||||
|
use App\Services\EditorialReading;
|
||||||
|
use App\Services\PortalProfileAccess;
|
||||||
|
use Illuminate\Contracts\Encryption\DecryptException;
|
||||||
|
use Illuminate\Database\Query\Builder;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
|
use Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider;
|
||||||
|
use Laravel\Fortify\Events\TwoFactorAuthenticationFailed;
|
||||||
|
use Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided;
|
||||||
|
use Laravel\Fortify\Fortify;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class EditorialArticleController extends Controller
|
class EditorialArticleController extends Controller
|
||||||
{
|
{
|
||||||
public function installation(Request $request, \App\Services\EditorialInstallation $installation)
|
public function installation(Request $request, EditorialInstallation $installation): Response
|
||||||
{
|
{
|
||||||
$plan = $installation->preview($request->user());
|
$plan = $installation->preview($request->user());
|
||||||
|
|
||||||
return $request->expectsJson() ? response()->json(['plan' => $plan])->header('Cache-Control', 'private, no-store')
|
return $request->expectsJson() ? response()->json(['plan' => $plan])->header('Cache-Control', 'private, no-store')
|
||||||
: response()->view('management.editorial-installation', ['plan' => $plan, 'operationKey' => (string) \Illuminate\Support\Str::uuid(), 'receipt' => null])->header('Cache-Control', 'private, no-store');
|
: response()->view('management.editorial-installation', ['plan' => $plan, 'operationKey' => (string) Str::uuid(), 'receipt' => null])->header('Cache-Control', 'private, no-store');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function install(Request $request, \App\Services\EditorialInstallation $installation)
|
public function install(Request $request, EditorialInstallation $installation): Response
|
||||||
{
|
{
|
||||||
$receipt = $installation->apply($request->user(), $request->all());
|
$receipt = $installation->apply($request->user(), $request->all());
|
||||||
|
|
||||||
return $request->expectsJson() ? response()->json(['receipt' => $receipt])->header('Cache-Control', 'private, no-store')
|
return $request->expectsJson() ? response()->json(['receipt' => $receipt])->header('Cache-Control', 'private, no-store')
|
||||||
: response()->view('management.editorial-installation', ['plan' => $installation->preview($request->user()), 'operationKey' => (string) \Illuminate\Support\Str::uuid(), 'receipt' => $receipt])->header('Cache-Control', 'private, no-store');
|
: response()->view('management.editorial-installation', ['plan' => $installation->preview($request->user()), 'operationKey' => (string) Str::uuid(), 'receipt' => $receipt])->header('Cache-Control', 'private, no-store');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function showMfa(Request $request)
|
public function showMfa(Request $request): Response
|
||||||
{
|
{
|
||||||
return $this->confirmMfa($request);
|
return $this->confirmMfa($request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function confirmMfa(Request $request)
|
public function confirmMfa(Request $request): Response
|
||||||
{
|
{
|
||||||
$actor = $request->user();
|
$actor = $request->user();
|
||||||
abort_unless($actor->two_factor_secret !== null && $actor->two_factor_confirmed_at !== null, 403, 'MFA configurado e confirmado necessário.');
|
abort_unless($actor->two_factor_secret !== null && $actor->two_factor_confirmed_at !== null, 403, 'MFA configurado e confirmado necessário.');
|
||||||
if (app(\App\Services\PortalProfileAccess::class)->mfa($actor)) {
|
if (app(PortalProfileAccess::class)->mfa($actor)) {
|
||||||
return redirect()->route('editorial.installation');
|
return redirect()->route('editorial.installation');
|
||||||
}
|
}
|
||||||
if ($request->isMethod('get')) {
|
if ($request->isMethod('get')) {
|
||||||
return response()->view('management.editorial-mfa')->header('Cache-Control', 'private, no-store');
|
return response()->view('management.editorial-mfa')->header('Cache-Control', 'private, no-store');
|
||||||
}
|
}
|
||||||
abort_if(array_diff(array_keys($request->all()), ['code', 'recovery_code', '_token']), 422, 'A conta e o destino são obtidos da sessão e do servidor.');
|
abort_if(array_diff(array_keys($request->all()), ['code', 'recovery_code', '_token']) !== [], 422, 'A conta e o destino são obtidos da sessão e do servidor.');
|
||||||
$data = $request->validate(['code' => 'nullable|string|max:32', 'recovery_code' => 'nullable|string|max:255']);
|
$data = $request->validate(['code' => 'nullable|string|max:32', 'recovery_code' => 'nullable|string|max:255']);
|
||||||
try {
|
try {
|
||||||
$recovery = collect($actor->recoveryCodes())->first(fn ($code) => isset($data['recovery_code']) && hash_equals($code, $data['recovery_code']));
|
$recovery = collect($actor->recoveryCodes())->first(fn ($code) => isset($data['recovery_code']) && hash_equals($code, $data['recovery_code']));
|
||||||
$valid = $recovery !== null || (!empty($data['code']) && app(\Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider::class)->verify(
|
$valid = $recovery !== null || (! empty($data['code']) && app(TwoFactorAuthenticationProvider::class)->verify(
|
||||||
\Laravel\Fortify\Fortify::currentEncrypter()->decrypt($actor->two_factor_secret), $data['code']
|
Fortify::currentEncrypter()->decrypt($actor->two_factor_secret), $data['code']
|
||||||
));
|
));
|
||||||
} catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
|
} catch (DecryptException $e) {
|
||||||
$valid = false;
|
$valid = false;
|
||||||
}
|
}
|
||||||
if (!$valid) {
|
if (! $valid) {
|
||||||
event(new \Laravel\Fortify\Events\TwoFactorAuthenticationFailed($actor));
|
event(new TwoFactorAuthenticationFailed($actor));
|
||||||
throw ValidationException::withMessages(['code' => 'Não foi possível confirmar o código MFA.']);
|
throw ValidationException::withMessages(['code' => 'Não foi possível confirmar o código MFA.']);
|
||||||
}
|
}
|
||||||
if ($recovery !== null) {
|
if ($recovery !== null) {
|
||||||
$actor->replaceRecoveryCode($recovery);
|
$actor->replaceRecoveryCode($recovery);
|
||||||
}
|
}
|
||||||
event(new \Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided($actor));
|
event(new ValidTwoFactorAuthenticationCodeProvided($actor));
|
||||||
$request->session()->regenerate();
|
$request->session()->regenerate();
|
||||||
|
|
||||||
return redirect()->route('editorial.installation')->header('Cache-Control', 'private, no-store');
|
return redirect()->route('editorial.installation')->header('Cache-Control', 'private, no-store');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,7 +83,7 @@ class EditorialArticleController extends Controller
|
|||||||
abort_unless(Schema::hasColumn('portal_resources', 'editorial_content'), 503, 'Editor editorial ainda não instalado.');
|
abort_unless(Schema::hasColumn('portal_resources', 'editorial_content'), 503, 'Editor editorial ainda não instalado.');
|
||||||
}
|
}
|
||||||
|
|
||||||
private function publicResources()
|
private function publicResources(): Builder
|
||||||
{
|
{
|
||||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
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('r.published', true)->where('r.rights_status', 'authorized')->where('d.rights_status', 'authorized')
|
||||||
@@ -75,41 +91,29 @@ class EditorialArticleController extends Controller
|
|||||||
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256');
|
->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function edit(int $id)
|
public function edit(int $id): Response
|
||||||
{
|
{
|
||||||
$this->installed();
|
$this->installed();
|
||||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource(request()->user(), $id);
|
app(DocumentManagementAccess::class)->assertEditableResource(request()->user(), $id);
|
||||||
$r = DB::table('portal_resources')->find($id);
|
$r = DB::table('portal_resources')->where('id', $id)->first();
|
||||||
abort_unless($r, 404);
|
abort_unless($r instanceof \stdClass, 404);
|
||||||
$content = $r->editorial_content ? json_decode($r->editorial_content, true) : null;
|
$reading = app(EditorialReading::class);
|
||||||
if ($content === null) {
|
$original = $reading->original($r);
|
||||||
$document = DB::table('documents')->find($r->document_id);
|
$content = $reading->content($r, $original);
|
||||||
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],
|
return tap(Inertia::render('portal/article-editor', ['resource' => ['id' => $r->id, 'title' => $r->title, 'metadata_version' => $r->metadata_version, 'published' => (bool) $r->published],
|
||||||
'content' => $content, 'images' => $this->publicResources()->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->get(['r.id', 'r.title']),
|
'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'])]);
|
'revisions' => DB::table('portal_resource_revisions')->where('resource_id', $id)->orderByDesc('revision_no')->get(['revision_no', 'change_type', 'created_at'])])->toResponse(request()), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function save(Request $request, int $id)
|
public function save(Request $request, int $id): RedirectResponse
|
||||||
{
|
{
|
||||||
$this->installed();
|
$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) {
|
DB::transaction(function () use ($request, $id, $data) {
|
||||||
$r = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
|
$r = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
|
||||||
abort_unless($r, 404);
|
abort_unless($r !== null, 404);
|
||||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||||
abort_unless((int) $r->metadata_version === (int) $data['metadata_version'], 409, 'O artigo foi alterado noutra sessão. Recarregue antes de editar.');
|
abort_unless((int) $r->metadata_version === (int) $data['metadata_version'], 409, 'O artigo foi alterado noutra sessão. Recarregue antes de editar.');
|
||||||
if (! empty($data['image_resource_id'])) {
|
if (! empty($data['image_resource_id'])) {
|
||||||
abort_unless($this->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.');
|
abort_unless($this->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.');
|
||||||
@@ -118,10 +122,10 @@ class EditorialArticleController extends Controller
|
|||||||
if ($body === '') {
|
if ($body === '') {
|
||||||
throw ValidationException::withMessages(['body' => 'Escreva o corpo do artigo.']);
|
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;
|
$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()]);
|
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);
|
$resource = DB::table('portal_resources')->where('id', $id)->first();
|
||||||
$links = DB::table('portal_resource_links')->where('resource_id', $id)->orderBy('id')->get();
|
$links = DB::table('portal_resource_links')->where('resource_id', $id)->orderBy('id')->get();
|
||||||
DB::table('portal_resource_revisions')->insert(['resource_id' => $id, 'revision_no' => $revision, 'change_type' => 'metadata_updated', 'snapshot' => json_encode(['resource' => $resource, 'associations' => $links], JSON_THROW_ON_ERROR), 'actor_user_id' => $request->user()->id, 'created_at' => now()]);
|
DB::table('portal_resource_revisions')->insert(['resource_id' => $id, 'revision_no' => $revision, 'change_type' => 'metadata_updated', 'snapshot' => json_encode(['resource' => $resource, 'associations' => $links], JSON_THROW_ON_ERROR), 'actor_user_id' => $request->user()->id, 'created_at' => now()]);
|
||||||
DB::table('audit_events')->insert(['source_system' => 'portal-management', 'actor_user_id' => $request->user()->id, 'entity_type' => 'portal_resources', 'entity_id' => null, 'action' => 'editorial_updated', 'before_data' => json_encode(['record_id' => $id, 'metadata_version' => $r->metadata_version]), 'after_data' => json_encode(['record_id' => $id, 'metadata_version' => $revision, 'published' => false])]);
|
DB::table('audit_events')->insert(['source_system' => 'portal-management', 'actor_user_id' => $request->user()->id, 'entity_type' => 'portal_resources', 'entity_id' => null, 'action' => 'editorial_updated', 'before_data' => json_encode(['record_id' => $id, 'metadata_version' => $r->metadata_version]), 'after_data' => json_encode(['record_id' => $id, 'metadata_version' => $revision, 'published' => false])]);
|
||||||
@@ -130,16 +134,64 @@ 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.');
|
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)
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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']]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $data
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
private function edition(\stdClass $resource, array $data): array
|
||||||
|
{
|
||||||
|
$reading = app(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): Response
|
||||||
{
|
{
|
||||||
$this->installed();
|
$this->installed();
|
||||||
$r = $this->publicResources()->where('r.id', $id)->first(['r.id', 'r.title', 'r.description', 'r.editorial_content', 'r.document_id', 'd.issuer']);
|
app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||||
abort_unless($r && $r->editorial_content, 404);
|
$resource = DB::table('portal_resources')->where('id', $id)->first();
|
||||||
$content = json_decode($r->editorial_content, true);
|
abort_unless($resource instanceof \stdClass, 404);
|
||||||
// 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;
|
|
||||||
|
|
||||||
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]]);
|
return tap(Inertia::render('portal/article', ['article' => app(EditorialReading::class)->reading($resource, null, true)])
|
||||||
|
->toResponse($request), static function (Response $response): void {
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store');
|
||||||
|
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function previewContent(Request $request, int $id): JsonResponse
|
||||||
|
{
|
||||||
|
$this->installed();
|
||||||
|
app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||||
|
$resource = DB::table('portal_resources')->where('id', $id)->first();
|
||||||
|
abort_unless($resource instanceof \stdClass, 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(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): Response
|
||||||
|
{
|
||||||
|
$this->installed();
|
||||||
|
$resource = app(EditorialReading::class)->publicResources()->where('r.id', $id)->first(['r.*']);
|
||||||
|
abort_unless($resource !== null, 404);
|
||||||
|
|
||||||
|
return tap(Inertia::render('portal/article', ['article' => app(EditorialReading::class)->reading($resource)])->toResponse($request), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ use App\Services\CountryCatalogue;
|
|||||||
use App\Services\ExistingBusinessDrafts;
|
use App\Services\ExistingBusinessDrafts;
|
||||||
use App\Services\ExistingBusinessIntake;
|
use App\Services\ExistingBusinessIntake;
|
||||||
use App\Services\ExistingBusinessObjects;
|
use App\Services\ExistingBusinessObjects;
|
||||||
|
use App\Services\ExistingBusinessProfileCategory;
|
||||||
use App\Services\ExistingBusinessVerification;
|
use App\Services\ExistingBusinessVerification;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\Mne\BusinessRepository;
|
use App\Services\Mne\BusinessRepository;
|
||||||
@@ -67,7 +68,7 @@ class ExistingBusinessController extends Controller
|
|||||||
$business = app(BusinessRepository::class)->find($id);
|
$business = app(BusinessRepository::class)->find($id);
|
||||||
Gate::authorize('view', $business);
|
Gate::authorize('view', $business);
|
||||||
app(CompatibilityShadow::class)->schedule($id);
|
app(CompatibilityShadow::class)->schedule($id);
|
||||||
$props = ['countries' => app(CountryCatalogue::class)->all(), 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'formSchema' => BusinessFormSchema::fields(), 'modalityFormType' => \App\Services\ExistingBusinessProfileCategory::formType($business->modality), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
$props = ['countries' => app(CountryCatalogue::class)->all(), 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']), 'formSchema' => BusinessFormSchema::fields(), 'modalityFormType' => ExistingBusinessProfileCategory::formType($business->modality), 'record' => $this->record($business), 'canEdit' => $request->user()->can('update', $business),
|
||||||
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
'owner' => $request->user()->can('owns', $business), 'canReview' => $request->user()->can('review', $business),
|
||||||
'canTriage' => $request->user()->can('triage', $business),
|
'canTriage' => $request->user()->can('triage', $business),
|
||||||
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
|
'canApproveLevelOne' => $request->user()->can('approveLevelOne', $business),
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Services\InvestmentComplements;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
final class InvestmentComplementController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, InvestmentComplements $service): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate(['origin' => [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 (ModelNotFoundException|HttpException $e) {
|
||||||
|
$status = $e instanceof 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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,14 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\InvestmentDossier;
|
use App\Models\InvestmentDossier;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
|
use App\Models\Sector;
|
||||||
|
use App\Services\CorridorAgribusinessOpportunities;
|
||||||
use App\Services\InvestmentCatalogue;
|
use App\Services\InvestmentCatalogue;
|
||||||
|
use App\Services\InvestmentComplements;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\InvestmentZones;
|
use App\Services\InvestmentZones;
|
||||||
|
use App\Services\OpportunityCorridorExplorer;
|
||||||
|
use App\Services\SectorInvestment;
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -26,9 +31,10 @@ class InvestmentDiscoveryController extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(false, $filters),
|
return Inertia::render('investment/catalogue', ['filters' => $filters, 'catalogueUrl' => $request->routeIs('investment.education') ? '/educacao' : '/oportunidades', 'references' => $catalogue->references(false, $filters),
|
||||||
|
'corridorGroups' => ($filters['view'] ?? '') === 'corridors' ? app(OpportunityCorridorExplorer::class)->groups($filters) : [],
|
||||||
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
|
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
|
||||||
'guides' => app(\App\Services\SectorInvestment::class)->guides(\App\Models\Sector::where('slug', $filters['sector'] ?? '')->where('is_active', true)->whereNotNull('published_at')->first()),
|
'guides' => app(SectorInvestment::class)->guides(Sector::where('slug', $filters['sector'] ?? '')->where('is_active', true)->whereNotNull('published_at')->first()),
|
||||||
'results' => $catalogue->query($filters)->paginate(12)->withQueryString(),
|
'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') : [],
|
'favourites' => $request->user() ? DB::table('opportunity_favourites')->where('user_id', $request->user()->id)->pluck('opportunity_id') : [],
|
||||||
'territorial' => $this->territorial($filters)]);
|
'territorial' => $this->territorial($filters)]);
|
||||||
}
|
}
|
||||||
@@ -73,7 +79,7 @@ class InvestmentDiscoveryController extends Controller
|
|||||||
|
|
||||||
public function search(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
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
|
public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
|
||||||
@@ -88,7 +94,7 @@ class InvestmentDiscoveryController extends Controller
|
|||||||
$data = $request->validate(['zone_id' => ['nullable', 'uuid'], 'from_dossier' => ['nullable', 'uuid']]);
|
$data = $request->validate(['zone_id' => ['nullable', 'uuid'], 'from_dossier' => ['nullable', 'uuid']]);
|
||||||
$dossierOrigin = isset($data['from_dossier']) ? InvestmentPortfolioController::visible()->whereKey($data['from_dossier'])->firstOrFail() : null;
|
$dossierOrigin = isset($data['from_dossier']) ? InvestmentPortfolioController::visible()->whereKey($data['from_dossier'])->firstOrFail() : null;
|
||||||
if ($dossierOrigin) {
|
if ($dossierOrigin) {
|
||||||
$linked = false;
|
$linked = in_array($record->id, app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($dossierOrigin), true);
|
||||||
foreach (['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'] as $relation => $foreign) {
|
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()) {
|
if ($dossierOrigin->$foreign && DB::table('opportunity_'.$relation)->where('opportunity_id', $record->id)->where($foreign, $dossierOrigin->$foreign)->exists()) {
|
||||||
$linked = true;
|
$linked = true;
|
||||||
@@ -106,8 +112,8 @@ class InvestmentDiscoveryController extends Controller
|
|||||||
$returnFilters = $request->query();
|
$returnFilters = $request->query();
|
||||||
unset($returnFilters['zone_id'], $returnFilters['from_dossier']);
|
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(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),
|
'guides' => app(SectorInvestment::class)->guides($record->sector),
|
||||||
'dossierOrigin' => $dossierOrigin ? ['id' => $dossierOrigin->id, 'title' => $dossierOrigin->title] : null,
|
'dossierOrigin' => $dossierOrigin ? ['id' => $dossierOrigin->id, 'title' => $dossierOrigin->title] : null,
|
||||||
'returnUrl' => $returnFilters === [] ? '/oportunidades' : '/oportunidades?'.http_build_query($returnFilters)]);
|
'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']]);
|
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
|
||||||
|
|
||||||
return DB::transaction(function () use ($request, $id, $action, $data) {
|
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();
|
$source = InvestmentLegalSource::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||||
abort_if((int) $source->version_no !== (int) $data['version_no'], 409, 'Versão alterada.');
|
abort_if((int) $source->version_no !== (int) $data['version_no'], 409, 'Versão alterada.');
|
||||||
if ($action === 'validate') {
|
if ($action === 'validate') {
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ use App\Models\InvestmentDossier;
|
|||||||
use App\Models\InvestmentSubmission;
|
use App\Models\InvestmentSubmission;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
use App\Models\Project;
|
use App\Models\Project;
|
||||||
|
use App\Services\ClusterCompetitiveness;
|
||||||
|
use App\Services\CorridorAgribusinessOpportunities;
|
||||||
|
use App\Services\InvestmentComplements;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\InvestmentRelations;
|
use App\Services\InvestmentRelations;
|
||||||
use App\Services\InvestmentZones;
|
use App\Services\InvestmentZones;
|
||||||
@@ -61,8 +64,15 @@ class InvestmentPortfolioController extends Controller
|
|||||||
{
|
{
|
||||||
$management = $request->routeIs('management.portfolio*');
|
$management = $request->routeIs('management.portfolio*');
|
||||||
$filters = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'kind' => ['nullable', 'in:corridor,cluster,project'],
|
$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']]);
|
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid']]);
|
||||||
$query = $management ? InvestmentDossier::query() : self::visible();
|
$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'])) {
|
if (! empty($filters['kind'])) {
|
||||||
$query->whereNotNull($filters['kind'].'_id');
|
$query->whereNotNull($filters['kind'].'_id');
|
||||||
}
|
}
|
||||||
@@ -76,7 +86,7 @@ class InvestmentPortfolioController extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('portfolio/index', ['records' => $query->orderBy('title')->paginate(30)->withQueryString(),
|
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
|
public function show(Request $request, string $id): Response
|
||||||
@@ -105,6 +115,7 @@ class InvestmentPortfolioController extends Controller
|
|||||||
|
|
||||||
$opportunities = Opportunity::published()->where(function ($query) use ($record) {
|
$opportunities = Opportunity::published()->where(function ($query) use ($record) {
|
||||||
$query->whereRaw('false');
|
$query->whereRaw('false');
|
||||||
|
$query->orWhereIn('id', app(CorridorAgribusinessOpportunities::class)->portfolioOpportunityIds($record));
|
||||||
foreach (['clusters' => 'cluster_id', 'corridors' => 'corridor_id', 'projects' => 'project_id'] as $relation => $foreign) {
|
foreach (['clusters' => 'cluster_id', 'corridors' => 'corridor_id', 'projects' => 'project_id'] as $relation => $foreign) {
|
||||||
if ($record->$foreign) {
|
if ($record->$foreign) {
|
||||||
$query->orWhereIn('id', DB::table('opportunity_'.$relation)->where($foreign, $record->$foreign)->select('opportunity_id'));
|
$query->orWhereIn('id', DB::table('opportunity_'.$relation)->where($foreign, $record->$foreign)->select('opportunity_id'));
|
||||||
@@ -130,12 +141,21 @@ class InvestmentPortfolioController extends Controller
|
|||||||
->orderByDesc('updated_at')->limit(10)->get(['id', 'version', 'updated_at'])
|
->orderByDesc('updated_at')->limit(10)->get(['id', 'version', 'updated_at'])
|
||||||
: collect();
|
: collect();
|
||||||
|
|
||||||
return Inertia::render('portfolio/show', ['record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones,
|
return Inertia::render('portfolio/show', ['complements' => $management ? [] : app(InvestmentComplements::class)->options('portfolio:'.$record->id), 'record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones,
|
||||||
'anchorProject' => $anchorProject, 'existingSubmissions' => $existingSubmissions,
|
'anchorProject' => $anchorProject, 'existingSubmissions' => $existingSubmissions,
|
||||||
|
'competitiveness' => $record->cluster_id ? app(ClusterCompetitiveness::class)->publicData($record->cluster_id) : null,
|
||||||
'geography' => app(InvestmentRelations::class)->dossier($record, $management),
|
'geography' => app(InvestmentRelations::class)->dossier($record, $management),
|
||||||
'origin' => $origin ? ['id' => $origin->id, 'title' => $origin->title] : null, 'opportunities' => $opportunities, 'chains' => $chains]);
|
'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
|
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'],
|
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'title' => ['required', 'string', 'max:255'], 'source' => ['required', 'string', 'max:2000'],
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ use App\Models\EconomicCluster;
|
|||||||
use App\Models\InvestmentGap;
|
use App\Models\InvestmentGap;
|
||||||
use App\Models\Project;
|
use App\Models\Project;
|
||||||
use App\Models\ValueChain;
|
use App\Models\ValueChain;
|
||||||
|
use App\Services\ClusterCompetitiveness;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\PortalAudit;
|
use App\Services\PortalAudit;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
@@ -50,6 +51,7 @@ class InvestmentStructureController extends Controller
|
|||||||
->whereNull('origins.deleted_at')->whereNull('destinations.deleted_at')->whereNull('value_chain_links.deleted_at')
|
->whereNull('origins.deleted_at')->whereNull('destinations.deleted_at')->whereNull('value_chain_links.deleted_at')
|
||||||
->orderBy('origins.code')->orderBy('destinations.code')
|
->orderBy('origins.code')->orderBy('destinations.code')
|
||||||
->get(['value_chain_links.id', 'origins.name as origin', 'destinations.name as destination', 'link_type']) : [],
|
->get(['value_chain_links.id', 'origins.name as origin', 'destinations.name as destination', 'link_type']) : [],
|
||||||
|
'competitiveness' => $structure === 'clusters' && $id ? app(ClusterCompetitiveness::class)->management($id) : null,
|
||||||
'viewerId' => $request->user()->id,
|
'viewerId' => $request->user()->id,
|
||||||
'memberships' => $structure === 'clusters' && $id ? DB::table('cluster_projects')
|
'memberships' => $structure === 'clusters' && $id ? DB::table('cluster_projects')
|
||||||
->join('projects', 'projects.id', '=', 'cluster_projects.project_id')
|
->join('projects', 'projects.id', '=', 'cluster_projects.project_id')
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use App\Models\Opportunity;
|
|||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
use App\Services\InterestSubmission;
|
use App\Services\InterestSubmission;
|
||||||
use App\Services\InvestmentCatalogue;
|
use App\Services\InvestmentCatalogue;
|
||||||
|
use App\Services\InvestmentConsumerScope;
|
||||||
use App\Services\InvestmentWorkspace;
|
use App\Services\InvestmentWorkspace;
|
||||||
use App\Services\InvestmentZones;
|
use App\Services\InvestmentZones;
|
||||||
use App\Services\InvestorContextConsumers;
|
use App\Services\InvestorContextConsumers;
|
||||||
@@ -151,7 +152,7 @@ class InvestmentSubmissionController extends Controller
|
|||||||
public function bindContext(Request $request, string $id): JsonResponse
|
public function bindContext(Request $request, string $id): JsonResponse
|
||||||
{
|
{
|
||||||
abort_unless(app(VirtualDesk::class)->installed(), 422, 'O vínculo ao percurso do investimento não está disponível neste destino. A manifestação e a sua origem permanecem guardadas.');
|
abort_unless(app(VirtualDesk::class)->installed(), 422, 'O vínculo ao percurso do investimento não está disponível neste destino. A manifestação e a sua origem permanecem guardadas.');
|
||||||
abort_if(array_diff(array_keys($request->all()), ['case_id', 'case_version', 'version', '_token']), 422, 'Parâmetros de associação inválidos.');
|
abort_if(array_diff(array_keys($request->all()), ['case_id', 'case_version', 'version', '_token']) !== [], 422, 'Parâmetros de associação inválidos.');
|
||||||
$data = $request->validate(['case_id' => 'required|uuid', 'case_version' => 'required|integer|min:1', 'version' => 'required|integer|min:1']);
|
$data = $request->validate(['case_id' => 'required|uuid', 'case_version' => 'required|integer|min:1', 'version' => 'required|integer|min:1']);
|
||||||
$result = DB::transaction(function () use ($request, $id, $data) {
|
$result = DB::transaction(function () use ($request, $id, $data) {
|
||||||
// Serialize all links for this submission before locking the selected case.
|
// Serialize all links for this submission before locking the selected case.
|
||||||
@@ -170,8 +171,10 @@ class InvestmentSubmissionController extends Controller
|
|||||||
// Binding does not save form edits or assert that the context has been reviewed.
|
// Binding does not save form edits or assert that the context has been reviewed.
|
||||||
$this->event($row, $request, 'context_bound');
|
$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]);
|
$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];
|
return ['case_id' => $case->id, 'version' => $row->version, 'case_version' => (int) $case->version + 1, 'replayed' => false];
|
||||||
}, 3);
|
}, 3);
|
||||||
|
|
||||||
return response()->json($result);
|
return response()->json($result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,11 +193,14 @@ class InvestmentSubmissionController extends Controller
|
|||||||
{
|
{
|
||||||
$required = $submitting ? 'required' : 'nullable';
|
$required = $submitting ? 'required' : 'nullable';
|
||||||
$data = $request->validate(['version' => ['required', 'integer', 'min:1'],
|
$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.organization_country_snapshot' => ['sometimes', 'array', 'max:10'],
|
||||||
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
|
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
|
||||||
'payload.incorporation_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.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.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.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'],
|
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => [$submitting ? 'required_without:payload.declared_origin_country_code' : 'nullable', 'nullable', 'string', 'max:100'],
|
||||||
@@ -244,6 +250,13 @@ 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(InvestmentConsumerScope::class)->bind($request->user(), $bound->id, $data['payload'], $submitting);
|
||||||
|
} else {
|
||||||
|
unset($data['payload']['context_opportunity'], $data['payload']['context_opportunity_snapshot']);
|
||||||
|
}
|
||||||
|
|
||||||
return $data;
|
return $data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -263,7 +276,7 @@ class InvestmentSubmissionController extends Controller
|
|||||||
$version = DB::transaction(function () use ($request, $id, $data) {
|
$version = DB::transaction(function () use ($request, $id, $data) {
|
||||||
$row = $this->owned($request, $id, true, true);
|
$row = $this->owned($request, $id, true, true);
|
||||||
abort_unless($row->status === 'draft' && $row->version === (int) $data['version'], 409, 'Rascunho alterado. Recarregue antes de guardar.');
|
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();
|
InvestmentSpecificNeed::where('submission_id', $id)->delete();
|
||||||
foreach ($data['needs'] ?? [] as $need) {
|
foreach ($data['needs'] ?? [] as $need) {
|
||||||
InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]);
|
InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]);
|
||||||
@@ -307,7 +320,8 @@ class InvestmentSubmissionController extends Controller
|
|||||||
return InterestRequest::findOrFail($row->interest_request_id)->reference;
|
return InterestRequest::findOrFail($row->interest_request_id)->reference;
|
||||||
}
|
}
|
||||||
abort_unless($row->version === (int) $data['version'], 409, 'Rascunho alterado. Recarregue.');
|
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) {
|
if ($row->dossier_id) {
|
||||||
InvestmentPortfolioController::visible()->findOrFail($row->dossier_id);
|
InvestmentPortfolioController::visible()->findOrFail($row->dossier_id);
|
||||||
}
|
}
|
||||||
@@ -328,12 +342,14 @@ class InvestmentSubmissionController extends Controller
|
|||||||
'sector_interest' => $p['sector'], 'message' => $p['objective'], 'privacy_consent' => true, 'consented_at' => now(),
|
'sector_interest' => $p['sector'], 'message' => $p['objective'], 'privacy_consent' => true, 'consented_at' => now(),
|
||||||
'status' => 'received', 'source_page' => '/investidor/manifestacoes/'.$id,
|
'status' => 'received', 'source_page' => '/investidor/manifestacoes/'.$id,
|
||||||
'metadata' => ['submission_id' => $id, 'portal_user_id' => $request->user()->id, 'dossier_id' => $row->dossier_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,
|
'declared_origin_country_code' => $p['declared_origin_country_code'] ?? null,
|
||||||
'residence_country_code' => $p['residence_country_code'] ?? null,
|
'residence_country_code' => $p['residence_country_code'] ?? null,
|
||||||
'incorporation_country_code' => $p['incorporation_country_code'] ?? null,
|
'incorporation_country_code' => $p['incorporation_country_code'] ?? null,
|
||||||
...(isset($p['organization_country_snapshot']) ? ['organization_country_snapshot' => $p['organization_country_snapshot']] : []),
|
...(isset($p['organization_country_snapshot']) ? ['organization_country_snapshot' => $p['organization_country_snapshot']] : []),
|
||||||
...($zoneOrigin ? ['zone_origin' => (array) $zoneOrigin] : [])]]));
|
...($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();
|
InvestmentSpecificNeed::where('submission_id', $id)->delete();
|
||||||
foreach ($data['needs'] ?? [] as $need) {
|
foreach ($data['needs'] ?? [] as $need) {
|
||||||
InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]);
|
InvestmentSpecificNeed::create([...$need, 'submission_id' => $id]);
|
||||||
|
|||||||
@@ -19,12 +19,21 @@ class InvestmentTerritoryController extends Controller
|
|||||||
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
|
$data = $request->validate(['territory_id' => ['required', 'uuid']]);
|
||||||
$profile = $request->is('minhas-oportunidades/*');
|
$profile = $request->is('minhas-oportunidades/*');
|
||||||
$management = $request->is('management/*') || $profile;
|
$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) {
|
if ($management) {
|
||||||
$access = app(PortalProfileAccess::class);
|
abort_unless($profile ? $profileAccess : $internal, 403);
|
||||||
abort_unless($profile ? ($access->grants($request->user()) !== [] || $access->superuser($request->user())) : $request->user()?->can('manage-portal'), 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'];
|
private const TABLES = ['opportunities' => 'opportunities', 'projects' => 'projects', 'clusters' => 'economic_clusters', 'corridors' => 'development_corridors', 'zones' => 'investment_zones'];
|
||||||
|
|||||||
@@ -5,14 +5,17 @@ namespace App\Http\Controllers;
|
|||||||
use App\Models\InvestmentDossier;
|
use App\Models\InvestmentDossier;
|
||||||
use App\Models\InvestmentZone;
|
use App\Models\InvestmentZone;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
|
use App\Services\EconomicReferenceCatalog;
|
||||||
use App\Services\InvestmentCatalogue;
|
use App\Services\InvestmentCatalogue;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\InvestmentTerritorialTraceability;
|
use App\Services\InvestmentTerritorialTraceability;
|
||||||
use App\Services\InvestmentZoneAccess;
|
use App\Services\InvestmentZoneAccess;
|
||||||
use App\Services\InvestmentZones;
|
use App\Services\InvestmentZoneOperationalDetails;
|
||||||
|
use App\Services\InvestmentZoneOperationalDetailsInstallation;
|
||||||
use App\Services\InvestmentZoneOperationalProfile;
|
use App\Services\InvestmentZoneOperationalProfile;
|
||||||
use App\Services\InvestmentZonePathContext;
|
use App\Services\InvestmentZonePathContext;
|
||||||
use App\Services\InvestmentZoneProfileInstallation;
|
use App\Services\InvestmentZoneProfileInstallation;
|
||||||
|
use App\Services\InvestmentZones;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -33,7 +36,7 @@ class InvestmentZoneController extends Controller
|
|||||||
$zone->setAttribute('province', collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province);
|
$zone->setAttribute('province', collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province);
|
||||||
$zone->setAttribute('district', collect($territoryPath)->firstWhere('location_type', 'district')->name ?? $zone->district);
|
$zone->setAttribute('district', collect($territoryPath)->firstWhere('location_type', 'district')->name ?? $zone->district);
|
||||||
$zone->setAttribute('territory_path', $territoryPath);
|
$zone->setAttribute('territory_path', $territoryPath);
|
||||||
$zone->setAttribute('operational_details_public',app(\App\Services\InvestmentZoneOperationalDetails::class)->publicData($zone));
|
$zone->setAttribute('operational_details_public', app(InvestmentZoneOperationalDetails::class)->publicData($zone));
|
||||||
$publicFields = ['operational_details_public', 'version_no', 'published_at', 'id', 'code', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'historical_territory', 'data_as_of', 'sources_consulted_at', 'name', 'name_en', 'description', 'description_en', 'province', 'district', 'territory_path', 'validation_status', 'updated_at'];
|
$publicFields = ['operational_details_public', 'version_no', 'published_at', 'id', 'code', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'historical_territory', 'data_as_of', 'sources_consulted_at', 'name', 'name_en', 'description', 'description_en', 'province', 'district', 'territory_path', 'validation_status', 'updated_at'];
|
||||||
$locations = DB::table('investment_zone_locations as zl')->join('geo_locations as g', 'g.id', '=', 'zl.geo_location_id')
|
$locations = DB::table('investment_zone_locations as zl')->join('geo_locations as g', 'g.id', '=', 'zl.geo_location_id')
|
||||||
->where('zl.zone_id', $id)->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public'))
|
->where('zl.zone_id', $id)->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public'))
|
||||||
@@ -68,7 +71,7 @@ class InvestmentZoneController extends Controller
|
|||||||
});
|
});
|
||||||
$props = ['record' => $management ? app(InvestmentZoneOperationalProfile::class)->management($zone) : app(InvestmentZoneOperationalProfile::class)->publicDetails($zone->only($publicFields)), 'source' => $source, 'operator' => $operator, 'management' => $management,
|
$props = ['record' => $management ? app(InvestmentZoneOperationalProfile::class)->management($zone) : app(InvestmentZoneOperationalProfile::class)->publicDetails($zone->only($publicFields)), 'source' => $source, 'operator' => $operator, 'management' => $management,
|
||||||
'profileAvailable' => $management && app(InvestmentZoneOperationalProfile::class)->installed(),
|
'profileAvailable' => $management && app(InvestmentZoneOperationalProfile::class)->installed(),
|
||||||
'zoneContext' => !$management && $zone->category === 'industrial_park' ? app(InvestmentZonePathContext::class)->context($id,(int)$zone->version_no) : null,
|
'zoneContext' => ! $management && $zone->category === 'industrial_park' ? app(InvestmentZonePathContext::class)->context($id, (int) $zone->version_no) : null,
|
||||||
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence'),
|
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence'),
|
||||||
'related' => $related->unique('id')->values(),
|
'related' => $related->unique('id')->values(),
|
||||||
'relations' => $management ? DB::table('investment_zone_relations')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
|
'relations' => $management ? DB::table('investment_zone_relations')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
|
||||||
@@ -77,7 +80,7 @@ class InvestmentZoneController extends Controller
|
|||||||
'dossiers' => InvestmentDossier::orderBy('title')->limit(200)->get(['id', 'title', 'project_id', 'cluster_id', 'corridor_id'])] : null,
|
'dossiers' => InvestmentDossier::orderBy('title')->limit(200)->get(['id', 'title', 'project_id', 'cluster_id', 'corridor_id'])] : null,
|
||||||
'opportunities' => $opportunities,
|
'opportunities' => $opportunities,
|
||||||
'legalSources' => $management ? DB::table('investment_legal_sources')->orderByDesc('created_at')->limit(100)->get() : [],
|
'legalSources' => $management ? DB::table('investment_legal_sources')->orderByDesc('created_at')->limit(100)->get() : [],
|
||||||
'economicActivities' => $management ? app(\App\Services\EconomicReferenceCatalog::class)->activities() : [],
|
'economicActivities' => $management ? app(EconomicReferenceCatalog::class)->activities() : [],
|
||||||
'operators' => $management ? DB::table('organizations')->whereNull('deleted_at')->orderBy('name')->limit(200)->get(['id', 'name']) : [],
|
'operators' => $management ? DB::table('organizations')->whereNull('deleted_at')->orderBy('name')->limit(200)->get(['id', 'name']) : [],
|
||||||
'links' => $management ? DB::table('investment_zone_links')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
|
'links' => $management ? DB::table('investment_zone_links')->where('zone_id', $id)->orderByDesc('created_at')->limit(100)->get() : [],
|
||||||
'locations' => $locations,
|
'locations' => $locations,
|
||||||
@@ -99,7 +102,9 @@ class InvestmentZoneController extends Controller
|
|||||||
'Os filtros de desenvolvimento e disponibilidade estarão disponíveis após a migração do catálogo de zonas.');
|
'Os filtros de desenvolvimento e disponibilidade estarão disponíveis após a migração do catálogo de zonas.');
|
||||||
$path = app(InvestmentGeography::class)->selection($filters);
|
$path = app(InvestmentGeography::class)->selection($filters);
|
||||||
$publicColumns = ['primary_territory_id', 'version_no', 'id', 'code', 'name', 'name_en', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'data_as_of', 'sources_consulted_at', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'];
|
$publicColumns = ['primary_territory_id', 'version_no', 'id', 'code', 'name', 'name_en', 'category', 'physical_category', 'legal_regime', 'operational_status', 'development_status', 'availability_status', 'area_value', 'area_unit', 'area_components', 'source_evidence', 'activities', 'resources', 'aliases', 'data_as_of', 'sources_consulted_at', 'province', 'district', 'description', 'description_en', 'validation_status', 'updated_at'];
|
||||||
if(app(\App\Services\InvestmentZoneOperationalDetails::class)->installed()){$publicColumns[]='operational_details';}
|
if (app(InvestmentZoneOperationalDetails::class)->installed()) {
|
||||||
|
$publicColumns[] = 'operational_details';
|
||||||
|
}
|
||||||
$publicColumns = array_values(array_filter($publicColumns, fn ($column) => Schema::hasColumn('investment_zones', $column)));
|
$publicColumns = array_values(array_filter($publicColumns, fn ($column) => Schema::hasColumn('investment_zones', $column)));
|
||||||
$rows = $zones->search($filters, $management)->orderBy('name')->orderBy('id')
|
$rows = $zones->search($filters, $management)->orderBy('name')->orderBy('id')
|
||||||
->paginate(12, $management ? ['*'] : $publicColumns)->withQueryString();
|
->paginate(12, $management ? ['*'] : $publicColumns)->withQueryString();
|
||||||
@@ -113,11 +118,13 @@ class InvestmentZoneController extends Controller
|
|||||||
->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public'))
|
->when(! $management, fn ($q) => $q->where('zl.validation_status', 'validated')->where('g.data_classification', 'public'))
|
||||||
->orderBy('g.location_type')->orderBy('g.name')->get(['g.id', 'g.name', 'g.location_type', 'zl.scope_type']));
|
->orderBy('g.location_type')->orderBy('g.name')->get(['g.id', 'g.name', 'g.location_type', 'zl.scope_type']));
|
||||||
|
|
||||||
if (! $management) { $zone->makeHidden('primary_territory_id'); }
|
if (! $management) {
|
||||||
|
$zone->makeHidden('primary_territory_id');
|
||||||
|
}
|
||||||
|
|
||||||
return $management ? $zone : [...app(InvestmentZoneOperationalProfile::class)->publicDetails($zone->toArray()),'operational_details_public'=>app(\App\Services\InvestmentZoneOperationalDetails::class)->publicData($zone)];
|
return $management ? $zone : [...app(InvestmentZoneOperationalProfile::class)->publicDetails($zone->toArray()), 'operational_details_public' => app(InvestmentZoneOperationalDetails::class)->publicData($zone)];
|
||||||
});
|
});
|
||||||
$props = ['detailsInstallation'=>$management ? app(\App\Services\InvestmentZoneOperationalDetailsInstallation::class)->preview($request->user()) : null, 'installation' => $management ? app(InvestmentZoneProfileInstallation::class)->preview($request->user()) : null, 'records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path,
|
$props = ['detailsInstallation' => $management ? app(InvestmentZoneOperationalDetailsInstallation::class)->preview($request->user()) : null, 'installation' => $management ? app(InvestmentZoneProfileInstallation::class)->preview($request->user()) : null, 'records' => $rows, 'filters' => $filters, 'management' => $management, 'territorySelection' => $path,
|
||||||
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence')];
|
'zoneExtensionsAvailable' => Schema::hasColumn('investment_zones', 'source_evidence')];
|
||||||
|
|
||||||
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props);
|
return $request->is('api/*') ? response()->json($props) : Inertia::render('investment/zones', $props);
|
||||||
@@ -193,35 +200,35 @@ class InvestmentZoneController extends Controller
|
|||||||
'source_evidence.*.source_date' => ['nullable', 'date_format:Y-m-d'],
|
'source_evidence.*.source_date' => ['nullable', 'date_format:Y-m-d'],
|
||||||
'area_value' => ['nullable', 'numeric', 'min:0'], 'area_unit' => ['nullable', 'string', 'max:24'],
|
'area_value' => ['nullable', 'numeric', 'min:0'], 'area_unit' => ['nullable', 'string', 'max:24'],
|
||||||
'aliases' => ['sometimes', 'array', 'max:20'], 'aliases.*' => ['string', 'max:120'],
|
'aliases' => ['sometimes', 'array', 'max:20'], 'aliases.*' => ['string', 'max:120'],
|
||||||
'operational_details' => ['sometimes','array'],
|
'operational_details' => ['sometimes', 'array'],
|
||||||
'activities' => ['sometimes', 'array', 'max:50'], 'activities.*' => ['array:id,name,status,source_reference,source_date,kind,scope,capacity_type,capacity_value,capacity_unit,focus,economic_activity_id,support_document_ids,private_note'],
|
'activities' => ['sometimes', 'array', 'max:50'], 'activities.*' => ['array:id,name,status,source_reference,source_date,kind,scope,capacity_type,capacity_value,capacity_unit,focus,economic_activity_id,support_document_ids,private_note'],
|
||||||
'activities.*.id' => ['nullable','uuid'],
|
'activities.*.id' => ['nullable', 'uuid'],
|
||||||
'activities.*.source_date' => ['nullable','date_format:Y-m-d'],
|
'activities.*.source_date' => ['nullable', 'date_format:Y-m-d'],
|
||||||
'activities.*.kind' => ['nullable','in:infrastructure,service,access,other'],
|
'activities.*.kind' => ['nullable', 'in:infrastructure,service,access,other'],
|
||||||
'activities.*.scope' => ['nullable','in:inside,regional,unknown'],
|
'activities.*.scope' => ['nullable', 'in:inside,regional,unknown'],
|
||||||
'activities.*.capacity_type' => ['nullable','string','max:120'],
|
'activities.*.capacity_type' => ['nullable', 'string', 'max:120'],
|
||||||
'activities.*.capacity_value' => ['nullable','numeric','min:0'],
|
'activities.*.capacity_value' => ['nullable', 'numeric', 'min:0'],
|
||||||
'activities.*.capacity_unit' => ['nullable','string','max:40'],
|
'activities.*.capacity_unit' => ['nullable', 'string', 'max:40'],
|
||||||
'activities.*.focus' => ['nullable','in:promotional,potential,installed,unknown'],
|
'activities.*.focus' => ['nullable', 'in:promotional,potential,installed,unknown'],
|
||||||
'activities.*.economic_activity_id' => ['nullable','uuid','exists:economic_activities,id'],
|
'activities.*.economic_activity_id' => ['nullable', 'uuid', 'exists:economic_activities,id'],
|
||||||
'activities.*.support_document_ids' => ['sometimes','array','max:10'],
|
'activities.*.support_document_ids' => ['sometimes', 'array', 'max:10'],
|
||||||
'activities.*.support_document_ids.*' => ['uuid'],
|
'activities.*.support_document_ids.*' => ['uuid'],
|
||||||
'activities.*.private_note' => ['nullable','string','max:2000'],
|
'activities.*.private_note' => ['nullable', 'string', 'max:2000'],
|
||||||
'activities.*.name' => ['required', 'string', 'max:300'], 'activities.*.status' => ['required', 'in:proposed,authorized,conditional,excluded,potential'],
|
'activities.*.name' => ['required', 'string', 'max:300'], 'activities.*.status' => ['required', 'in:proposed,authorized,conditional,excluded,potential'],
|
||||||
'activities.*.source_reference' => ['nullable', 'string', 'max:2000'],
|
'activities.*.source_reference' => ['nullable', 'string', 'max:2000'],
|
||||||
'resources' => ['sometimes', 'array', 'max:50'], 'resources.*' => ['array:id,name,status,source_reference,source_date,kind,scope,capacity_type,capacity_value,capacity_unit,focus,economic_activity_id,support_document_ids,private_note'],
|
'resources' => ['sometimes', 'array', 'max:50'], 'resources.*' => ['array:id,name,status,source_reference,source_date,kind,scope,capacity_type,capacity_value,capacity_unit,focus,economic_activity_id,support_document_ids,private_note'],
|
||||||
'resources.*.id' => ['nullable','uuid'],
|
'resources.*.id' => ['nullable', 'uuid'],
|
||||||
'resources.*.source_date' => ['nullable','date_format:Y-m-d'],
|
'resources.*.source_date' => ['nullable', 'date_format:Y-m-d'],
|
||||||
'resources.*.kind' => ['nullable','in:infrastructure,service,access,other'],
|
'resources.*.kind' => ['nullable', 'in:infrastructure,service,access,other'],
|
||||||
'resources.*.scope' => ['nullable','in:inside,regional,unknown'],
|
'resources.*.scope' => ['nullable', 'in:inside,regional,unknown'],
|
||||||
'resources.*.capacity_type' => ['nullable','string','max:120'],
|
'resources.*.capacity_type' => ['nullable', 'string', 'max:120'],
|
||||||
'resources.*.capacity_value' => ['nullable','numeric','min:0'],
|
'resources.*.capacity_value' => ['nullable', 'numeric', 'min:0'],
|
||||||
'resources.*.capacity_unit' => ['nullable','string','max:40'],
|
'resources.*.capacity_unit' => ['nullable', 'string', 'max:40'],
|
||||||
'resources.*.focus' => ['nullable','in:promotional,potential,installed,unknown'],
|
'resources.*.focus' => ['nullable', 'in:promotional,potential,installed,unknown'],
|
||||||
'resources.*.economic_activity_id' => ['nullable','uuid','exists:economic_activities,id'],
|
'resources.*.economic_activity_id' => ['nullable', 'uuid', 'exists:economic_activities,id'],
|
||||||
'resources.*.support_document_ids' => ['sometimes','array','max:10'],
|
'resources.*.support_document_ids' => ['sometimes', 'array', 'max:10'],
|
||||||
'resources.*.support_document_ids.*' => ['uuid'],
|
'resources.*.support_document_ids.*' => ['uuid'],
|
||||||
'resources.*.private_note' => ['nullable','string','max:2000'],
|
'resources.*.private_note' => ['nullable', 'string', 'max:2000'],
|
||||||
'resources.*.name' => ['required', 'string', 'max:120'], 'resources.*.status' => ['required', 'in:existing,planned,unconfirmed'],
|
'resources.*.name' => ['required', 'string', 'max:120'], 'resources.*.status' => ['required', 'in:existing,planned,unconfirmed'],
|
||||||
'resources.*.source_reference' => ['nullable', 'string', 'max:2000'], 'data_as_of' => ['nullable', 'date_format:Y-m-d'],
|
'resources.*.source_reference' => ['nullable', 'string', 'max:2000'], 'data_as_of' => ['nullable', 'date_format:Y-m-d'],
|
||||||
'sources_consulted_at' => ['nullable', 'date_format:Y-m-d'], 'parent_zone_id' => ['nullable', 'uuid', 'exists:investment_zones,id'],
|
'sources_consulted_at' => ['nullable', 'date_format:Y-m-d'], 'parent_zone_id' => ['nullable', 'uuid', 'exists:investment_zones,id'],
|
||||||
@@ -257,17 +264,26 @@ class InvestmentZoneController extends Controller
|
|||||||
$data['district'] = $path[1]->name ?? null;
|
$data['district'] = $path[1]->name ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
$saved=$zones->save($id, $data, $request->user()->id);
|
$saved = $zones->save($id, $data, $request->user()->id);
|
||||||
|
|
||||||
return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved), $id ? 200 : 201);
|
return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved), $id ? 200 : 201);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function transition(Request $request, InvestmentZones $zones, string $id, string $action): JsonResponse
|
public function transition(Request $request, InvestmentZones $zones, string $id, string $action): JsonResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'base_public_version'=>['required_if:action,reconcile','nullable','integer','min:1']]);
|
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'base_public_version' => ['required_if:action,reconcile', 'nullable', 'integer', 'min:1']]);
|
||||||
if($action==='reconcile'){
|
if ($action === 'reconcile') {
|
||||||
$request->validate(['base_public_version'=>'required|integer|min:1']);
|
$request->validate(['base_public_version' => 'required|integer|min:1']);
|
||||||
$saved=DB::transaction(function()use($id,$data,$request){$zone=InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();abort_unless($zone->category==='industrial_park',422);return app(InvestmentZoneOperationalProfile::class)->reconcile($zone,(int)$data['version_no'],(int)$data['base_public_version'],$request->user()->id);});
|
$saved = DB::transaction(function () use ($id, $data, $request) {
|
||||||
}else{$saved=$action === 'publish' ? $zones->publish($id,$data['version_no'],$request->user()->id) : $zones->suspend($id,$data['version_no'],$request->user()->id);}
|
$zone = InvestmentZone::whereKey($id)->lockForUpdate()->firstOrFail();
|
||||||
|
abort_unless($zone->category === 'industrial_park', 422);
|
||||||
|
|
||||||
|
return app(InvestmentZoneOperationalProfile::class)->reconcile($zone, (int) $data['version_no'], (int) $data['base_public_version'], $request->user()->id);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
$saved = $action === 'publish' ? $zones->publish($id, $data['version_no'], $request->user()->id) : $zones->suspend($id, $data['version_no'], $request->user()->id);
|
||||||
|
}
|
||||||
|
|
||||||
return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved));
|
return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,72 +2,191 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\InvestmentSubmission;
|
||||||
|
use App\Services\InvestmentComplements;
|
||||||
|
use App\Services\InvestmentCorridorContext;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
|
use App\Services\InvestmentOpportunityChoices;
|
||||||
use App\Services\InvestorContext;
|
use App\Services\InvestorContext;
|
||||||
use App\Services\InvestorContextInstallation;
|
use App\Services\InvestorContextInstallation;
|
||||||
use App\Services\InvestorPath;
|
use App\Services\InvestorPath;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Config;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
|
||||||
final class InvestorContextController extends Controller
|
final class InvestorContextController extends Controller
|
||||||
{
|
{
|
||||||
public function current(Request $r, InvestorContext $context)
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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(InvestmentComplements::class)->resolve([['origin' => $data['complement_origin'], 'code' => $data['complement_code'],
|
||||||
|
'target' => $data['complement_target'] ?? null, 'territory_id' => $data['complement_territory'] ?? null]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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(InvestmentOpportunityChoices::class)->resolve($input, [], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function current(Request $r, InvestorContext $context): JsonResponse
|
||||||
{
|
{
|
||||||
return response()->json($context->current($r->user()));
|
return response()->json($context->current($r->user()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function focus(Request $r, InvestorContext $context)
|
public function focus(Request $r, InvestorContext $context): JsonResponse
|
||||||
{
|
{
|
||||||
return response()->json($context->focus($r->user(), $r->all()));
|
return response()->json($context->focus($r->user(), $r->all()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Request $r, string $id, InvestorContext $context)
|
public function show(Request $r, string $id, InvestorContext $context): JsonResponse
|
||||||
{
|
{
|
||||||
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)
|
public function options(Request $r, InvestorContext $context): JsonResponse
|
||||||
{
|
{
|
||||||
$d = $r->validate(['q' => 'nullable|string|max:120']);
|
$d = $r->validate(['q' => 'nullable|string|max:120']);
|
||||||
|
|
||||||
return response()->json($context->options($d['q'] ?? ''));
|
return response()->json($context->options($d['q'] ?? ''));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function edit(Request $r, string $id, InvestorContext $context)
|
public function corridorOptions(Request $r): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $r->validate(['corridor' => ['nullable', Rule::in(array_keys(config('investment_corridors')))], 'territory' => 'nullable|uuid']);
|
||||||
|
$service = app(InvestmentCorridorContext::class);
|
||||||
|
|
||||||
|
return response()->json(['corridors' => collect(Config::array('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): JsonResponse
|
||||||
|
{
|
||||||
|
return response()->json($context->saveDraft($r->user(), $id, $r->all()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function edit(Request $r, string $id, InvestorContext $context): Response
|
||||||
{
|
{
|
||||||
$data = $context->view($r->user(), $id);
|
$data = $context->view($r->user(), $id);
|
||||||
abort_unless($data['can_write'], 403);
|
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(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(InvestmentOpportunityChoices::class)->mergeEntries($data['context']['opportunity_choices'] ?? [], $choices);
|
||||||
|
}
|
||||||
|
$draft = $context->draft($r->user(), $id);
|
||||||
|
if ($draft && isset($draft['opportunity_choices'])) {
|
||||||
|
$recovered = app(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(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(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)
|
public function preview(Request $r, string $id, InvestorContext $context): JsonResponse
|
||||||
{
|
{
|
||||||
return response()->json($context->preview($r->user(), $id, $r->all()));
|
return response()->json($context->preview($r->user(), $id, $r->all()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function commit(Request $r, string $id, InvestorContext $context)
|
public function commit(Request $r, string $id, InvestorContext $context): JsonResponse
|
||||||
{
|
{
|
||||||
return response()->json($context->commit($r->user(), $id, $r->all()));
|
return response()->json($context->commit($r->user(), $id, $r->all()));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function start(Request $r, InvestorPath $path, InvestorContext $context)
|
public function start(Request $r, InvestorPath $path, InvestorContext $context): Response
|
||||||
{
|
{
|
||||||
$d = $r->validate(['source' => 'nullable|string|max:100', 'step' => ['nullable', 'regex:/^S(0[1-9]|1[0-9])$/']]);
|
$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;
|
$ref = isset($d['source']) ? $context->reference($d['source']) : null;
|
||||||
|
$submissionId = $r->validate(['submission' => 'nullable|uuid'])['submission'] ?? null;
|
||||||
|
$entrySubmission = null;
|
||||||
|
if ($submissionId) {
|
||||||
|
$submission = 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)
|
public function installation(Request $r, InvestorContextInstallation $install): JsonResponse|Response
|
||||||
{
|
{
|
||||||
$plan = $install->preview($r->user());
|
$plan = $install->preview($r->user());
|
||||||
|
|
||||||
return $r->expectsJson() ? response()->json($plan) : Inertia::render('investor-path/context-installation', ['plan' => $plan]);
|
return $r->expectsJson() ? response()->json($plan) : Inertia::render('investor-path/context-installation', ['plan' => $plan]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function install(Request $r, InvestorContextInstallation $install)
|
public function install(Request $r, InvestorContextInstallation $install): JsonResponse
|
||||||
{
|
{
|
||||||
return response()->json($install->apply($r->user(),$r->all()));
|
return response()->json($install->apply($r->user(), $r->all()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Services\FintechInvestment;
|
use App\Services\FintechInvestment;
|
||||||
use App\Services\InvestorPath;
|
|
||||||
use App\Services\InvestmentZonePathContext;
|
use App\Services\InvestmentZonePathContext;
|
||||||
|
use App\Services\InvestorPath;
|
||||||
use App\Services\LegacyContent;
|
use App\Services\LegacyContent;
|
||||||
use App\Services\SectorInvestment;
|
use App\Services\SectorInvestment;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
@@ -39,24 +39,29 @@ class InvestorPathController extends Controller
|
|||||||
return $request->expectsJson() ? response()->json(['ok' => true]) : redirect('/investimentos/'.$id)->with('success', 'Setor associado ao mesmo dossier.');
|
return $request->expectsJson() ? response()->json(['ok' => true]) : redirect('/investimentos/'.$id)->with('success', 'Setor associado ao mesmo dossier.');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function zoneStart(Request $request,string $zoneId,InvestorPath $path): JsonResponse|Response
|
public function zoneStart(Request $request, string $zoneId, InvestorPath $path): JsonResponse|Response
|
||||||
{
|
{
|
||||||
abort_unless($path->available(),404);
|
abort_unless($path->available(), 404);
|
||||||
$data=$request->validate(['consulted_public_version'=>'required|integer|min:1']);
|
$data = $request->validate(['consulted_public_version' => 'required|integer|min:1']);
|
||||||
$data=['contexts'=>$path->contexts($request->user()),'zoneSource'=>app(InvestmentZonePathContext::class)->context($zoneId,(int)$data['consulted_public_version'])];
|
$data = ['contexts' => $path->contexts($request->user()), 'zoneSource' => app(InvestmentZonePathContext::class)->context($zoneId, (int) $data['consulted_public_version'])];
|
||||||
return $request->expectsJson()?response()->json($data):Inertia::render('investor-path/index',$data);
|
|
||||||
|
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function zoneAttach(Request $request,string $id): JsonResponse|RedirectResponse
|
public function zoneAttach(Request $request, string $id): JsonResponse|RedirectResponse
|
||||||
{
|
{
|
||||||
app(InvestmentZonePathContext::class)->attach($request->user(),$id,$request->all());
|
app(InvestmentZonePathContext::class)->attach($request->user(), $id, $request->all());
|
||||||
return $request->expectsJson()?response()->json(['ok'=>true]):redirect('/investimentos/'.$id)->with('success','Referência do parque guardada; não constitui reserva ou autorização.');
|
|
||||||
|
return $request->expectsJson() ? response()->json(['ok' => true]) : redirect('/investimentos/'.$id)->with('success', 'Referência do parque guardada; não constitui reserva ou autorização.');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse
|
public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse
|
||||||
{
|
{
|
||||||
$zone=$request->has('zone_id') ? app(InvestmentZonePathContext::class)->input($request->all()) : null;
|
$zone = $request->has('zone_id') ? app(InvestmentZonePathContext::class)->input($request->all()) : null;
|
||||||
if($zone){ $request->validate(['confirm'=>'required|accepted']); app(InvestmentZonePathContext::class)->context($zone['zone_id'],(int)$zone['consulted_public_version']); }
|
if ($zone) {
|
||||||
|
$request->validate(['confirm' => 'required|accepted']);
|
||||||
|
app(InvestmentZonePathContext::class)->context($zone['zone_id'], (int) $zone['consulted_public_version']);
|
||||||
|
}
|
||||||
$sector = $request->validate(['sector_slug' => 'nullable|string|max:150'])['sector_slug'] ?? null;
|
$sector = $request->validate(['sector_slug' => 'nullable|string|max:150'])['sector_slug'] ?? null;
|
||||||
if ($sector !== null) {
|
if ($sector !== null) {
|
||||||
app(SectorInvestment::class)->context($sector);
|
app(SectorInvestment::class)->context($sector);
|
||||||
@@ -79,7 +84,11 @@ class InvestorPathController extends Controller
|
|||||||
app(SectorInvestment::class)->attach($request->user(), $id, ['version' => $case['version'], 'sector_slug' => $sector]);
|
app(SectorInvestment::class)->attach($request->user(), $id, ['version' => $case['version'], 'sector_slug' => $sector]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if($zone){$case=$path->view($request->user(),$id)['case']; app(InvestmentZonePathContext::class)->attach($request->user(),$id,[...$zone,'version'=>$case['version'],'confirm'=>true]);}
|
if ($zone) {
|
||||||
|
$case = $path->view($request->user(), $id)['case'];
|
||||||
|
app(InvestmentZonePathContext::class)->attach($request->user(), $id, [...$zone, 'version' => $case['version'], 'confirm' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
return $id;
|
return $id;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -88,7 +97,8 @@ class InvestorPathController extends Controller
|
|||||||
|
|
||||||
public function show(Request $request, string $id, InvestorPath $path): JsonResponse|Response
|
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);
|
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/show', $data);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -377,6 +377,9 @@ class LandAssistanceController extends Controller
|
|||||||
'declaredOrigin' => $countries->describe($payload['declared_origin_country_code'] ?? null), 'territoryPaths' => $paths, 'returnDossier' => $this->dossierContext($case)];
|
'declaredOrigin' => $countries->describe($payload['declared_origin_country_code'] ?? null), 'territoryPaths' => $paths, 'returnDossier' => $this->dossierContext($case)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>|null
|
||||||
|
*/
|
||||||
private function dossierContext(LandAssistanceCase $case): ?array
|
private function dossierContext(LandAssistanceCase $case): ?array
|
||||||
{
|
{
|
||||||
$id = $case->payload['investor_path_case_id'] ?? null;
|
$id = $case->payload['investor_path_case_id'] ?? null;
|
||||||
|
|||||||
@@ -12,9 +12,12 @@ use App\Services\OpportunityManagement;
|
|||||||
use App\Services\OpportunityManagementInstallation;
|
use App\Services\OpportunityManagementInstallation;
|
||||||
use App\Services\OpportunityMaturity;
|
use App\Services\OpportunityMaturity;
|
||||||
use App\Services\OpportunityProfileWorkflow;
|
use App\Services\OpportunityProfileWorkflow;
|
||||||
|
use App\Services\OpportunityPromotion;
|
||||||
use App\Services\OpportunityResources;
|
use App\Services\OpportunityResources;
|
||||||
use App\Services\OpportunityWorkflowTasks;
|
use App\Services\OpportunityWorkflowTasks;
|
||||||
use App\Services\PortalProfileAccess;
|
use App\Services\PortalProfileAccess;
|
||||||
|
use App\Services\ProactiveInvestment;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Database\Eloquent\SoftDeletingScope;
|
use Illuminate\Database\Eloquent\SoftDeletingScope;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
@@ -76,8 +79,8 @@ class OpportunityManagementController extends Controller
|
|||||||
$query->where('opportunity_category', $filters['category']);
|
$query->where('opportunity_category', $filters['category']);
|
||||||
}
|
}
|
||||||
if ($filters['sector_id'] ?? null) {
|
if ($filters['sector_id'] ?? null) {
|
||||||
$sector = Sector::find($filters['sector_id']);
|
$sector = Sector::whereKey($filters['sector_id'])->first();
|
||||||
$query->whereIn('sector_id', $sector ? Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
$query->whereIn('sector_id', $sector ? Sector::whereIn('slug', SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
||||||
}
|
}
|
||||||
if ($filters['geography_scope'] ?? null) {
|
if ($filters['geography_scope'] ?? null) {
|
||||||
$query->where('geography_scope', $filters['geography_scope']);
|
$query->where('geography_scope', $filters['geography_scope']);
|
||||||
@@ -103,6 +106,7 @@ class OpportunityManagementController extends Controller
|
|||||||
$records = $query->orderByDesc('id')->paginate(20)->withQueryString();
|
$records = $query->orderByDesc('id')->paginate(20)->withQueryString();
|
||||||
$records->getCollection()->each(function (Opportunity $r) use ($access, $service, $request) {
|
$records->getCollection()->each(function (Opportunity $r) use ($access, $service, $request) {
|
||||||
$r->setAttribute('can_edit', $access->canEdit($request->user(), $r));
|
$r->setAttribute('can_edit', $access->canEdit($request->user(), $r));
|
||||||
|
$r->setAttribute('can_promote', app(OpportunityPromotion::class)->allowed($request->user(), $r));
|
||||||
$r->setAttribute('working_status', $access->state($r));
|
$r->setAttribute('working_status', $access->state($r));
|
||||||
$r->setAttribute('publication', $r->publicationPresentation());
|
$r->setAttribute('publication', $r->publicationPresentation());
|
||||||
$r->setAttribute('draft_title', $service->values($r)['canonical']['official_title'] ?? $r->title);
|
$r->setAttribute('draft_title', $service->values($r)['canonical']['official_title'] ?? $r->title);
|
||||||
@@ -130,6 +134,7 @@ class OpportunityManagementController extends Controller
|
|||||||
'profileReauthenticationRequired' => $record && $record->owner_user_id !== null
|
'profileReauthenticationRequired' => $record && $record->owner_user_id !== null
|
||||||
? app(OpportunityProfileWorkflow::class)->reauthenticationRequired($request->user(), $record) : false,
|
? app(OpportunityProfileWorkflow::class)->reauthenticationRequired($request->user(), $record) : false,
|
||||||
'publicationState' => $record?->publicationPresentation(),
|
'publicationState' => $record?->publicationPresentation(),
|
||||||
|
'promotionHref' => $record && app(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,
|
'canonicalResponse' => $record?->owner_user_id !== null ? app(OpportunityCanonicalResponse::class)->read($request->user(), $record) : null,
|
||||||
'canEditDraft' => $record ? $access->canEdit($request->user(), $record) : false,
|
'canEditDraft' => $record ? $access->canEdit($request->user(), $record) : false,
|
||||||
'workflowParticipants' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->participants($request->user(), $record) : ['validators' => [], 'publishers' => []],
|
'workflowParticipants' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->participants($request->user(), $record) : ['validators' => [], 'publishers' => []],
|
||||||
@@ -145,7 +150,7 @@ class OpportunityManagementController extends Controller
|
|||||||
Inertia::share('publicationPreview', app(OpportunityCanonicalContract::class)->publicProjection($values['canonical'] ?? []));
|
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;
|
$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(ProactiveInvestment::class)->history($record), 'proactiveOptions' => app(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],
|
'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),
|
'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']) : []]);
|
'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,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Opportunity;
|
||||||
|
use App\Services\OpportunityPromotion;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
|
|
||||||
|
final class OpportunityPromotionController extends Controller
|
||||||
|
{
|
||||||
|
public function show(Request $request, int $id, OpportunityPromotion $service): Response
|
||||||
|
{
|
||||||
|
return Inertia::render('management/opportunity-promotion', $service->editor($request->user(), Opportunity::findOrFail($id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function preview(Request $request, int $id, OpportunityPromotion $service): JsonResponse
|
||||||
|
{
|
||||||
|
return response()->json($service->preview($request->user(), Opportunity::findOrFail($id), $request->all()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function confirm(Request $request, int $id, OpportunityPromotion $service): JsonResponse
|
||||||
|
{
|
||||||
|
return response()->json($service->confirm($request->user(), $id, $request->all()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,9 +6,11 @@ use App\Models\Opportunity;
|
|||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\OpportunityImageProcessor;
|
use App\Services\OpportunityImageProcessor;
|
||||||
|
use App\Services\OpportunityLibrarySupport;
|
||||||
use App\Services\OpportunityManagement;
|
use App\Services\OpportunityManagement;
|
||||||
use App\Services\OpportunityResourceInstallation;
|
use App\Services\OpportunityResourceInstallation;
|
||||||
use App\Services\OpportunityResources;
|
use App\Services\OpportunityResources;
|
||||||
|
use App\Services\OpportunityTerritorialPresentation;
|
||||||
use App\Services\OrganizationCountryInstallation;
|
use App\Services\OrganizationCountryInstallation;
|
||||||
use App\Services\PortalProfileAccess;
|
use App\Services\PortalProfileAccess;
|
||||||
use App\Services\VerifiedDocumentBinary;
|
use App\Services\VerifiedDocumentBinary;
|
||||||
@@ -98,12 +100,13 @@ class OpportunityResourceController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'librarySources' => !app(\App\Services\PortalProfileAccess::class)->canEdit(request()->user(), $opportunity) ? [] : app(\App\Services\OpportunityLibrarySupport::class)->choices(request()->user()), 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'locationReference' => app(\App\Services\OpportunityTerritorialPresentation::class)->describe($opportunity, $resources['locations']), 'assessment' => $this->assessment($resources)]);
|
return Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'librarySources' => ! app(PortalProfileAccess::class)->canEdit(request()->user(), $opportunity) ? [] : app(OpportunityLibrarySupport::class)->choices(request()->user()), 'existingLocations' => DB::table('opportunity_locations as l')->join('geo_locations as g', 'g.id', '=', 'l.geo_location_id')->where('opportunity_id', $id)->get(['g.id', 'g.name', 'g.location_type']), 'locationReference' => app(OpportunityTerritorialPresentation::class)->describe($opportunity, $resources['locations']), 'assessment' => $this->assessment($resources)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function reuseLibrary(Request $request, int $id): JsonResponse
|
public function reuseLibrary(Request $request, int $id): JsonResponse
|
||||||
{
|
{
|
||||||
$row = app(\App\Services\OpportunityLibrarySupport::class)->attach($request->user(), Opportunity::findOrFail($id), $request->all());
|
$row = app(OpportunityLibrarySupport::class)->attach($request->user(), Opportunity::findOrFail($id), $request->all());
|
||||||
|
|
||||||
return response()->json(['id' => $row->id, 'message' => 'Original associado como suporte privado, sem copiar ficheiros ou publicar.']);
|
return response()->json(['id' => $row->id, 'message' => 'Original associado como suporte privado, sem copiar ficheiros ou publicar.']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,15 +153,18 @@ class OpportunityResourceController extends Controller
|
|||||||
{
|
{
|
||||||
abort_unless(in_array($kind, ['documents', 'images'], true), 404);
|
abort_unless(in_array($kind, ['documents', 'images'], true), 404);
|
||||||
$opportunity = Opportunity::findOrFail($id);
|
$opportunity = Opportunity::findOrFail($id);
|
||||||
app(\App\Services\PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
|
app(PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
|
||||||
abort_if($opportunity->status === 'archived', 404);
|
abort_if($opportunity->status === 'archived', 404);
|
||||||
$record = DB::table($service->table($kind).' as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $resourceId)->where('r.opportunity_id', $id)->whereNull('r.deleted_at')->whereNull('d.deleted_at')->first(['d.*']);
|
$record = DB::table($service->table($kind).' as r')->join('documents as d', 'd.id', '=', 'r.document_id')->where('r.id', $resourceId)->where('r.opportunity_id', $id)->whereNull('r.deleted_at')->whereNull('d.deleted_at')->first(['d.*']);
|
||||||
abort_unless($record !== null, 404, 'Recurso indisponível ou excluído logicamente.');
|
abort_unless($record !== null, 404, 'Recurso indisponível ou excluído logicamente.');
|
||||||
abort_unless($record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($record->sha256), (string) $record->malware_scanned_sha256), 423, 'Scan pendente, inconclusivo ou inseguro. O ficheiro permanece em quarentena.');
|
abort_unless($record->status === 'active' && $record->malware_scan_status === 'clean' && hash_equals(trim($record->sha256), (string) $record->malware_scanned_sha256), 423, 'Scan pendente, inconclusivo ou inseguro. O ficheiro permanece em quarentena.');
|
||||||
|
|
||||||
$support = DB::table($service->table($kind))->where('id', $resourceId)->first();
|
$support = DB::table($service->table($kind))->where('id', $resourceId)->first();
|
||||||
app(\App\Services\OpportunityLibrarySupport::class)->assertAvailable($support, $record);
|
app(OpportunityLibrarySupport::class)->assertAvailable($support, $record);
|
||||||
if (request()->filled('source_sha256')) abort_unless(hash_equals(trim($record->sha256), (string)request('source_sha256')), 409, 'O original já não corresponde à versão consultada.');
|
if (request()->filled('source_sha256')) {
|
||||||
|
abort_unless(hash_equals(trim($record->sha256), (string) request('source_sha256')), 409, 'O original já não corresponde à versão consultada.');
|
||||||
|
}
|
||||||
|
|
||||||
return app(VerifiedDocumentBinary::class)->respond($record);
|
return app(VerifiedDocumentBinary::class)->respond($record);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Jobs\ScanDocumentForMalware;
|
use App\Jobs\ScanDocumentForMalware;
|
||||||
use App\Models\ExistingBusiness;
|
use App\Models\ExistingBusiness;
|
||||||
|
use App\Models\Sector;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\InvestmentCatalogue;
|
use App\Services\InvestmentCatalogue;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
@@ -11,6 +12,7 @@ use App\Services\InvestmentRelations;
|
|||||||
use App\Services\PartnershipExchange;
|
use App\Services\PartnershipExchange;
|
||||||
use App\Services\PartnershipMatching;
|
use App\Services\PartnershipMatching;
|
||||||
use App\Services\PartnershipSources;
|
use App\Services\PartnershipSources;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use App\Services\VerifiedDocumentBinary;
|
use App\Services\VerifiedDocumentBinary;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
@@ -45,9 +47,11 @@ class PartnershipExchangeController extends Controller
|
|||||||
foreach (['sector_id', 'partnership_type', 'kind'] as $field) {
|
foreach (['sector_id', 'partnership_type', 'kind'] as $field) {
|
||||||
if (! empty($filters[$field])) {
|
if (! empty($filters[$field])) {
|
||||||
if ($field === 'sector_id') {
|
if ($field === 'sector_id') {
|
||||||
$sector = \App\Models\Sector::find($filters[$field]);
|
$sector = Sector::whereKey($filters[$field])->first();
|
||||||
$query->whereIn('p.sector_id', $sector ? \App\Models\Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
$query->whereIn('p.sector_id', $sector ? Sector::whereIn('slug', SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
||||||
} else { $query->where('p.'.$field, $filters[$field]); }
|
} else {
|
||||||
|
$query->where('p.'.$field, $filters[$field]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (! empty($filters['q'])) {
|
if (! empty($filters['q'])) {
|
||||||
@@ -393,7 +397,7 @@ class PartnershipExchangeController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ['types' => config('partnerships.types'), 'criteria' => config('partnerships.criteria'), 'sources' => $sources, 'sectors' => \App\Models\Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
|
return ['types' => config('partnerships.types'), 'criteria' => config('partnerships.criteria'), 'sources' => $sources, 'sectors' => Sector::choices()->orderBy('name')->get(['id', 'name', 'slug']),
|
||||||
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type', 'parent_id']),
|
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type', 'parent_id']),
|
||||||
'organizations' => $request->user() ? DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')->where('m.user_id', $request->user()->id)
|
'organizations' => $request->user() ? DB::table('memberships as m')->join('organizations as o', 'o.id', '=', 'm.organization_id')->where('m.user_id', $request->user()->id)
|
||||||
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->get(['o.id', 'o.name']) : []];
|
->whereNull('m.deleted_at')->whereNull('o.deleted_at')->whereIn('m.role', ['admin', 'manager', 'officer'])->get(['o.id', 'o.name']) : []];
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ use App\Services\InvestmentWorkspace;
|
|||||||
use App\Services\OpportunityManagement;
|
use App\Services\OpportunityManagement;
|
||||||
use App\Services\PortalAudit;
|
use App\Services\PortalAudit;
|
||||||
use App\Services\PortalProfileAccess;
|
use App\Services\PortalProfileAccess;
|
||||||
|
use App\Services\ScopedPortalAdministration;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
@@ -55,32 +57,38 @@ class PortalManagementController extends Controller
|
|||||||
|
|
||||||
private function interestAssignmentEtag(InterestRequest $interest): string
|
private function interestAssignmentEtag(InterestRequest $interest): string
|
||||||
{
|
{
|
||||||
return hash('sha256',json_encode([$interest->id,$interest->status,$interest->assigned_to,$interest->updated_at?->format('Y-m-d H:i:s.u')],JSON_THROW_ON_ERROR));
|
return hash('sha256', json_encode([$interest->id, $interest->status, $interest->assigned_to, $interest->updated_at?->format('Y-m-d H:i:s.u')], JSON_THROW_ON_ERROR));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function interestAssignments(Request $request): Response|JsonResponse
|
public function interestAssignments(Request $request): Response|JsonResponse
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
|
abort_unless(app(ScopedPortalAdministration::class)->administrative($request->user()), 403);
|
||||||
$rows=InterestRequest::whereNotIn('status',['cancelled','closed','refused','converted'])->orderBy('id')->get(['id','reference','status','assigned_to','updated_at'])
|
$rows = InterestRequest::whereNotIn('status', ['cancelled', 'closed', 'refused', 'converted'])->orderBy('id')->get(['id', 'reference', 'status', 'assigned_to', 'updated_at'])
|
||||||
->map(fn($row)=>['id'=>$row->id,'protocol'=>$row->reference,'status'=>$row->status,'analyst_id'=>$row->assigned_to,'version'=>0,'etag'=>$this->interestAssignmentEtag($row),'due_at'=>null]);
|
->map(fn ($row) => ['id' => $row->id, 'protocol' => $row->reference, 'status' => $row->status, 'analyst_id' => $row->assigned_to, 'version' => 0, 'etag' => $this->interestAssignmentEtag($row), 'due_at' => null]);
|
||||||
$data=['kind'=>'interest','requests'=>$rows,'analysts'=>$this->interestAssignees()->get(['id','name'])];
|
$data = ['kind' => 'interest', 'requests' => $rows, 'analysts' => $this->interestAssignees()->get(['id', 'name'])];
|
||||||
return $request->expectsJson()?response()->json($data):Inertia::render('management/desk-assignments',$data);
|
|
||||||
|
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/desk-assignments', $data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function assignInterest(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
public function assignInterest(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
|
abort_unless(app(ScopedPortalAdministration::class)->administrative($request->user()), 403);
|
||||||
$data=$request->validate(['etag'=>'required|string|size:64','analyst_id'=>['required','integer',Rule::in($this->interestAssignees()->pluck('id'))],'reason'=>'required|string|min:10|max:2000'],['reason.required'=>'Explique o motivo da atribuição.','reason.min'=>'Explique o motivo da atribuição com pelo menos 10 caracteres.','analyst_id.required'=>'Seleccione o responsável.','analyst_id.in'=>'Seleccione um responsável autorizado.']);
|
$data = $request->validate(['etag' => 'required|string|size:64', 'analyst_id' => ['required', 'integer', Rule::in($this->interestAssignees()->pluck('id'))], 'reason' => 'required|string|min:10|max:2000'], ['reason.required' => 'Explique o motivo da atribuição.', 'reason.min' => 'Explique o motivo da atribuição com pelo menos 10 caracteres.', 'analyst_id.required' => 'Seleccione o responsável.', 'analyst_id.in' => 'Seleccione um responsável autorizado.']);
|
||||||
DB::transaction(function()use($request,$interest,$data){
|
DB::transaction(function () use ($request, $interest, $data) {
|
||||||
$row=InterestRequest::whereKey($interest->id)->lockForUpdate()->firstOrFail();
|
$row = InterestRequest::whereKey($interest->id)->lockForUpdate()->firstOrFail();
|
||||||
if (!hash_equals($this->interestAssignmentEtag($row),$data['etag'])) throw ValidationException::withMessages(['etag'=>'A atribuição mudou. Recupere a lista actual e tente novamente.']);
|
if (! hash_equals($this->interestAssignmentEtag($row), $data['etag'])) {
|
||||||
if (in_array($row->status,['cancelled','closed','refused','converted'],true)) throw ValidationException::withMessages(['status'=>'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
|
throw ValidationException::withMessages(['etag' => 'A atribuição mudou. Recupere a lista actual e tente novamente.']);
|
||||||
$owner=(int)($row->metadata['portal_user_id']??0);
|
}
|
||||||
abort_if($owner===(int)$data['analyst_id'] || InvestmentSubmission::where('interest_request_id',$row->id)->where('user_id',$data['analyst_id'])->exists(),422,'O interessado não pode acompanhar o seu próprio pedido como equipa.');
|
if (in_array($row->status, ['cancelled', 'closed', 'refused', 'converted'], true)) {
|
||||||
PortalAudit::save($row,['assigned_to'=>(int)$data['analyst_id']],$request->user()->id);
|
throw ValidationException::withMessages(['status' => 'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
|
||||||
app(\App\Services\PortalProfileAccess::class)->audit($request->user(),'interest_assigned',['interest_id'=>$row->id,'assigned_to'=>(int)$data['analyst_id'],'reason'=>$data['reason']]);
|
}
|
||||||
|
$owner = (int) ($row->metadata['portal_user_id'] ?? 0);
|
||||||
|
abort_if($owner === (int) $data['analyst_id'] || InvestmentSubmission::where('interest_request_id', $row->id)->where('user_id', $data['analyst_id'])->exists(), 422, 'O interessado não pode acompanhar o seu próprio pedido como equipa.');
|
||||||
|
PortalAudit::save($row, ['assigned_to' => (int) $data['analyst_id']], $request->user()->id);
|
||||||
|
app(PortalProfileAccess::class)->audit($request->user(), 'interest_assigned', ['interest_id' => $row->id, 'assigned_to' => (int) $data['analyst_id'], 'reason' => $data['reason']]);
|
||||||
});
|
});
|
||||||
return $request->expectsJson()?response()->json(['ok'=>true]):back()->with('success','Responsável atribuído.');
|
|
||||||
|
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Responsável atribuído.');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function interests(Request $request): Response
|
public function interests(Request $request): Response
|
||||||
@@ -95,7 +103,7 @@ class PortalManagementController extends Controller
|
|||||||
$query = InterestRequest::query()->with('assignee:id,name')->select([
|
$query = InterestRequest::query()->with('assignee:id,name')->select([
|
||||||
'id', 'reference', 'full_name', 'email', 'country', 'metadata', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
|
'id', 'reference', 'full_name', 'email', 'country', 'metadata', 'sector_interest', 'existing_business_id', 'modality', 'status', 'assigned_to', 'next_action', 'next_action_due_at', 'created_at',
|
||||||
]);
|
]);
|
||||||
app(\App\Services\ScopedPortalAdministration::class)->interestQuery($query, $request->user());
|
app(ScopedPortalAdministration::class)->interestQuery($query, $request->user());
|
||||||
if ($country = $filters['country'] ?? null) {
|
if ($country = $filters['country'] ?? null) {
|
||||||
$values = app(CountryCatalogue::class)->filterValues($country);
|
$values = app(CountryCatalogue::class)->filterValues($country);
|
||||||
$query->whereIn(DB::raw('LOWER(BTRIM(country))'), $values);
|
$query->whereIn(DB::raw('LOWER(BTRIM(country))'), $values);
|
||||||
@@ -142,7 +150,7 @@ class PortalManagementController extends Controller
|
|||||||
|
|
||||||
public function interest(InterestRequest $interest): Response
|
public function interest(InterestRequest $interest): Response
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
abort_unless(app(ScopedPortalAdministration::class)->interest(request()->user(), $interest), 403);
|
||||||
$history = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)
|
$history = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)
|
||||||
->orderByDesc('created_at')->limit(50)->get(['from_status', 'to_status', 'actor_id', 'reason', 'created_at'])
|
->orderByDesc('created_at')->limit(50)->get(['from_status', 'to_status', 'actor_id', 'reason', 'created_at'])
|
||||||
->map(function ($row) {
|
->map(function ($row) {
|
||||||
@@ -170,7 +178,7 @@ class PortalManagementController extends Controller
|
|||||||
|
|
||||||
public function review(Request $request, InterestRequest $interest, InterestWorkflow $workflow): RedirectResponse|JsonResponse
|
public function review(Request $request, InterestRequest $interest, InterestWorkflow $workflow): RedirectResponse|JsonResponse
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
abort_unless(app(ScopedPortalAdministration::class)->interest(request()->user(), $interest), 403);
|
||||||
$validated = $request->validate([
|
$validated = $request->validate([
|
||||||
'status' => ['required', Rule::in(self::STATES)],
|
'status' => ['required', Rule::in(self::STATES)],
|
||||||
'note' => ['nullable', 'string', 'min:10', 'max:2000'],
|
'note' => ['nullable', 'string', 'min:10', 'max:2000'],
|
||||||
@@ -198,7 +206,7 @@ class PortalManagementController extends Controller
|
|||||||
|
|
||||||
public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
public function withdrawProponentSharingConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
abort_unless(app(ScopedPortalAdministration::class)->interest(request()->user(), $interest), 403);
|
||||||
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||||
$this->withdrawConsent($request, $interest, $data['reason'], 'share_contact_with_proponent');
|
$this->withdrawConsent($request, $interest, $data['reason'], 'share_contact_with_proponent');
|
||||||
|
|
||||||
@@ -208,7 +216,7 @@ class PortalManagementController extends Controller
|
|||||||
|
|
||||||
public function withdrawContactConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
public function withdrawContactConsent(Request $request, InterestRequest $interest): RedirectResponse|JsonResponse
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->interest(request()->user(), $interest),403);
|
abort_unless(app(ScopedPortalAdministration::class)->interest(request()->user(), $interest), 403);
|
||||||
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
$data = $request->validate(['reason' => ['required', 'string', 'min:10', 'max:2000']]);
|
||||||
$this->withdrawConsent($request, $interest, $data['reason'], 'respond_to_interest');
|
$this->withdrawConsent($request, $interest, $data['reason'], 'respond_to_interest');
|
||||||
|
|
||||||
@@ -301,8 +309,8 @@ class PortalManagementController extends Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($resource === 'opportunities' && ($filters['sector_id'] ?? null)) {
|
if ($resource === 'opportunities' && ($filters['sector_id'] ?? null)) {
|
||||||
$sector = Sector::find($filters['sector_id']);
|
$sector = Sector::whereKey($filters['sector_id'])->first();
|
||||||
$query->whereIn('sector_id', $sector ? Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
$query->whereIn('sector_id', $sector ? Sector::whereIn('slug', SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Inertia::render('management/catalog', [
|
return Inertia::render('management/catalog', [
|
||||||
@@ -319,7 +327,7 @@ class PortalManagementController extends Controller
|
|||||||
public function edit(string $resource, ?int $id = null): Response
|
public function edit(string $resource, ?int $id = null): Response
|
||||||
{
|
{
|
||||||
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
|
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
|
||||||
$record = $id ? $model::findOrFail($id) : null;
|
$record = $id ? $model::whereKey($id)->firstOrFail() : null;
|
||||||
|
|
||||||
return Inertia::render('management/editor', [
|
return Inertia::render('management/editor', [
|
||||||
'resource' => $resource,
|
'resource' => $resource,
|
||||||
@@ -335,7 +343,7 @@ class PortalManagementController extends Controller
|
|||||||
throw ValidationException::withMessages(['status' => 'Use Gestão de Oportunidades para guardar uma versão de rascunho; publicação não é uma edição.']);
|
throw ValidationException::withMessages(['status' => 'Use Gestão de Oportunidades para guardar uma versão de rascunho; publicação não é uma edição.']);
|
||||||
}
|
}
|
||||||
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
|
$model = $resource === 'sectors' ? Sector::class : Opportunity::class;
|
||||||
$record = $id ? $model::findOrFail($id) : new $model;
|
$record = $id ? $model::whereKey($id)->firstOrFail() : new $model;
|
||||||
$rules = $resource === 'sectors' ? [
|
$rules = $resource === 'sectors' ? [
|
||||||
'name' => ['required', 'string', 'max:150'],
|
'name' => ['required', 'string', 'max:150'],
|
||||||
'slug' => ['required', 'alpha_dash:ascii', 'max:180', Rule::unique('sectors')->ignore($record->id)],
|
'slug' => ['required', 'alpha_dash:ascii', 'max:180', Rule::unique('sectors')->ignore($record->id)],
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
|
use App\Models\User;
|
||||||
use App\Services\OpportunityCanonicalContract;
|
use App\Services\OpportunityCanonicalContract;
|
||||||
use App\Services\OpportunityContacts;
|
use App\Services\OpportunityContacts;
|
||||||
use App\Services\OpportunityManagement;
|
use App\Services\OpportunityManagement;
|
||||||
@@ -51,6 +52,10 @@ class PortalProfileController extends Controller
|
|||||||
return Inertia::render('profiles/administration', ['requests' => DB::table('portal_profile_requests')->latest()->get(),
|
return Inertia::render('profiles/administration', ['requests' => DB::table('portal_profile_requests')->latest()->get(),
|
||||||
'assignments' => DB::table('portal_role_assignments')->get(), 'pair' => DB::table('portal_superuser_pair')->first(),
|
'assignments' => DB::table('portal_role_assignments')->get(), 'pair' => DB::table('portal_superuser_pair')->first(),
|
||||||
'operatorOrganizations' => app(PortalInternalDesignation::class)->organizations(),
|
'operatorOrganizations' => app(PortalInternalDesignation::class)->organizations(),
|
||||||
|
'staffAccounts' => User::query()->orderBy('name')->get(['id', 'name', 'email', 'email_verified_at', 'two_factor_confirmed_at'])->map(fn (User $user) => [
|
||||||
|
'id' => $user->id, 'name' => $user->name, 'email' => $user->email,
|
||||||
|
'verified' => $user->email_verified_at !== null, 'mfa' => $user->two_factor_confirmed_at !== null,
|
||||||
|
]),
|
||||||
'internalTypes' => OpportunityCanonicalContract::BASE_CATEGORIES,
|
'internalTypes' => OpportunityCanonicalContract::BASE_CATEGORIES,
|
||||||
'actorId' => $request->user()->id, 'types' => OpportunityManagement::CATEGORIES,
|
'actorId' => $request->user()->id, 'types' => OpportunityManagement::CATEGORIES,
|
||||||
'organizations' => DB::table('organizations')->whereNull('deleted_at')->get(['id', 'name']),
|
'organizations' => DB::table('organizations')->whereNull('deleted_at')->get(['id', 'name']),
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ class PortalProfileInstallationController extends Controller
|
|||||||
public function bootstrapPreview(Request $request, string $id, PortalProfileInstallation $installation): JsonResponse|Response
|
public function bootstrapPreview(Request $request, string $id, PortalProfileInstallation $installation): JsonResponse|Response
|
||||||
{
|
{
|
||||||
$plan = $installation->bootstrapPreview($request->user(), $id);
|
$plan = $installation->bootstrapPreview($request->user(), $id);
|
||||||
|
|
||||||
return $request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/bootstrap-confirmation', $plan);
|
return $request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/bootstrap-confirmation', $plan);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,12 +4,20 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Jobs\ScanDocumentForMalware;
|
use App\Jobs\ScanDocumentForMalware;
|
||||||
use App\Models\InterestRequest;
|
use App\Models\InterestRequest;
|
||||||
|
use App\Models\Opportunity;
|
||||||
use App\Models\Sector;
|
use App\Models\Sector;
|
||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
|
use App\Services\DocumentManagementAccess;
|
||||||
|
use App\Services\EconomicReferenceCatalog;
|
||||||
|
use App\Services\EditorialReading;
|
||||||
use App\Services\IdempotencyConflict;
|
use App\Services\IdempotencyConflict;
|
||||||
use App\Services\InterestSubmission;
|
use App\Services\InterestSubmission;
|
||||||
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\LegacyContent;
|
use App\Services\LegacyContent;
|
||||||
use App\Services\Malware\MalwareScanner;
|
use App\Services\Malware\MalwareScanner;
|
||||||
|
use App\Services\PortalProfileAccess;
|
||||||
|
use App\Services\PublicDocumentPresentation;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use App\Services\VerifiedDocumentBinary;
|
use App\Services\VerifiedDocumentBinary;
|
||||||
use App\Services\VirtualDesk;
|
use App\Services\VirtualDesk;
|
||||||
use Illuminate\Database\Query\Builder;
|
use Illuminate\Database\Query\Builder;
|
||||||
@@ -17,6 +25,7 @@ use Illuminate\Database\QueryException;
|
|||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Config;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
@@ -25,6 +34,7 @@ use Illuminate\Validation\ValidationException;
|
|||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
class PortalServicesController extends Controller
|
class PortalServicesController extends Controller
|
||||||
{
|
{
|
||||||
@@ -69,7 +79,7 @@ class PortalServicesController extends Controller
|
|||||||
]);
|
]);
|
||||||
$props = ['section' => $page, 'filters' => $filters, 'countries' => app(CountryCatalogue::class)->all()];
|
$props = ['section' => $page, 'filters' => $filters, 'countries' => app(CountryCatalogue::class)->all()];
|
||||||
if ($page === 'sectors') {
|
if ($page === 'sectors') {
|
||||||
$props['sectors'] = \App\Services\SectorOrganization::catalog();
|
$props['sectors'] = SectorOrganization::catalog();
|
||||||
}
|
}
|
||||||
if (in_array($page, ['documents', 'legislation'], true)) {
|
if (in_array($page, ['documents', 'legislation'], true)) {
|
||||||
$query = $this->resources();
|
$query = $this->resources();
|
||||||
@@ -115,7 +125,7 @@ class PortalServicesController extends Controller
|
|||||||
'r.source_confirmation', 'r.legal_status', 'r.rights_status', 'r.last_reviewed_at', 'r.last_reviewed_by', 'r.independent_review', 'r.metadata_version', 'r.source_reference', 'r.essential',
|
'r.source_confirmation', 'r.legal_status', 'r.rights_status', 'r.last_reviewed_at', 'r.last_reviewed_by', 'r.independent_review', 'r.metadata_version', 'r.source_reference', 'r.essential',
|
||||||
'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.issued_on', 'd.valid_until', 'd.version_no',
|
'd.file_name', 'd.media_type', 'd.size_bytes', 'd.issuer', 'd.issued_on', 'd.valid_until', 'd.version_no',
|
||||||
])->paginate(20)->withQueryString();
|
])->paginate(20)->withQueryString();
|
||||||
$pageResult->getCollection()->transform(fn ($resource) => app(\App\Services\PublicDocumentPresentation::class)->resource($resource));
|
$pageResult->getCollection()->transform(fn ($resource) => app(PublicDocumentPresentation::class)->resource($resource));
|
||||||
$props['resources'] = $pageResult;
|
$props['resources'] = $pageResult;
|
||||||
$props['documentTypes'] = (clone $this->resources())->distinct()->orderBy('r.document_type')->pluck('r.document_type');
|
$props['documentTypes'] = (clone $this->resources())->distinct()->orderBy('r.document_type')->pluck('r.document_type');
|
||||||
$props['languages'] = (clone $this->resources())->distinct()->orderBy('r.language')->pluck('r.language');
|
$props['languages'] = (clone $this->resources())->distinct()->orderBy('r.language')->pluck('r.language');
|
||||||
@@ -187,7 +197,7 @@ class PortalServicesController extends Controller
|
|||||||
}
|
}
|
||||||
$resources = $query->orderByDesc('r.essential')->orderBy('r.title')->limit(10)
|
$resources = $query->orderByDesc('r.essential')->orderBy('r.title')->limit(10)
|
||||||
->get(['r.id', 'r.title', 'r.description', 'r.document_type', 'r.document_date', 'r.document_number', 'r.applicable_from', 'r.applicable_until', 'r.language', 'r.territorial_scope', 'r.legal_status', 'r.source_confirmation', 'r.source_url', 'd.issuer', 'd.media_type', 'd.size_bytes']);
|
->get(['r.id', 'r.title', 'r.description', 'r.document_type', 'r.document_date', 'r.document_number', 'r.applicable_from', 'r.applicable_until', 'r.language', 'r.territorial_scope', 'r.legal_status', 'r.source_confirmation', 'r.source_url', 'd.issuer', 'd.media_type', 'd.size_bytes']);
|
||||||
$resources->transform(fn ($resource) => app(\App\Services\PublicDocumentPresentation::class)->resource($resource));
|
$resources->transform(fn ($resource) => app(PublicDocumentPresentation::class)->resource($resource));
|
||||||
|
|
||||||
return response()->json(['data' => $resources]);
|
return response()->json(['data' => $resources]);
|
||||||
}
|
}
|
||||||
@@ -265,7 +275,7 @@ class PortalServicesController extends Controller
|
|||||||
abort_unless($resource !== null, 404);
|
abort_unless($resource !== null, 404);
|
||||||
$resource->territory_name = $resource->territory_id
|
$resource->territory_name = $resource->territory_id
|
||||||
? DB::table('geo_locations')->where('id', $resource->territory_id)->value('name') : null;
|
? DB::table('geo_locations')->where('id', $resource->territory_id)->value('name') : null;
|
||||||
$resource = app(\App\Services\PublicDocumentPresentation::class)->resource($resource);
|
$resource = app(PublicDocumentPresentation::class)->resource($resource);
|
||||||
$back = $request->query('back');
|
$back = $request->query('back');
|
||||||
$backUrl = is_string($back) && (str_starts_with($back, '/documentos') || str_starts_with($back, '/legislacao')) && ! str_starts_with($back, '//')
|
$backUrl = is_string($back) && (str_starts_with($back, '/documentos') || str_starts_with($back, '/legislacao')) && ! str_starts_with($back, '//')
|
||||||
? $back : '/documentos';
|
? $back : '/documentos';
|
||||||
@@ -274,7 +284,7 @@ class PortalServicesController extends Controller
|
|||||||
'resource' => $resource,
|
'resource' => $resource,
|
||||||
'backUrl' => $backUrl,
|
'backUrl' => $backUrl,
|
||||||
'downloadUrl' => route('services.download', ['id' => $id]),
|
'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),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,7 +298,7 @@ class PortalServicesController extends Controller
|
|||||||
|
|
||||||
public function downloadForManager(Request $request, string $id): BinaryFileResponse|\Illuminate\Http\Response
|
public function downloadForManager(Request $request, string $id): BinaryFileResponse|\Illuminate\Http\Response
|
||||||
{
|
{
|
||||||
$document = app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->first();
|
$document = app(DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->first();
|
||||||
abort_unless($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
|
abort_unless($document && $document->status === 'active' && $document->malware_scan_status === 'clean'
|
||||||
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
|
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256)), 404);
|
||||||
|
|
||||||
@@ -297,14 +307,15 @@ class PortalServicesController extends Controller
|
|||||||
|
|
||||||
public function manage(Request $request, MalwareScanner $scanner): Response
|
public function manage(Request $request, MalwareScanner $scanner): Response
|
||||||
{
|
{
|
||||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
$managementFilters = $request->validate(['q' => 'nullable|string|max:150', 'state' => 'nullable|in:draft,published,withdrawn', 'intent' => 'nullable|in:document,legislation']);
|
||||||
|
$access = app(DocumentManagementAccess::class);
|
||||||
if (! $access->full($request->user())) {
|
if (! $access->full($request->user())) {
|
||||||
$documents = $access->documents($request->user())->where('status', '!=', 'deleted');
|
$documents = $access->documents($request->user())->where('status', '!=', 'deleted');
|
||||||
$health = $scanner->health();
|
$health = $scanner->health();
|
||||||
$health['signatures_at'] = $health['signatures_at']?->format(DATE_ATOM);
|
$health['signatures_at'] = $health['signatures_at']?->format(DATE_ATOM);
|
||||||
|
|
||||||
$editorial = $access->editorial($request->user());
|
$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();
|
->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');
|
$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');
|
$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');
|
||||||
@@ -312,7 +323,9 @@ class PortalServicesController extends Controller
|
|||||||
$resource->links = $links->get($resource->id, collect())->values();
|
$resource->links = $links->get($resource->id, collect())->values();
|
||||||
$resource->revisions = $revisions->get($resource->id, collect())->values();
|
$resource->revisions = $revisions->get($resource->id, collect())->values();
|
||||||
});
|
});
|
||||||
|
|
||||||
return Inertia::render('portal/manage', [
|
return Inertia::render('portal/manage', [
|
||||||
|
'managementFilters' => $managementFilters, 'associationOptions' => $this->contentAssociations($request),
|
||||||
'documentAccessOnly' => ! $editorial, 'editorialScopeOnly' => $editorial, 'resources' => $resources, 'partnerships' => [], 'territories' => [],
|
'documentAccessOnly' => ! $editorial, 'editorialScopeOnly' => $editorial, 'resources' => $resources, 'partnerships' => [], 'territories' => [],
|
||||||
'requirementCatalogue' => [], 'requirementAssociationsEnabled' => false,
|
'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(),
|
'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 +344,7 @@ class PortalServicesController extends Controller
|
|||||||
->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1')
|
->where('external_id', 'document-repository-disclosure-authorization-2026-10-06-v1')
|
||||||
->where('action', 'public_disclosure_authorized')->first(['external_id', 'occurred_at', 'after_data']);
|
->where('action', 'public_disclosure_authorized')->first(['external_id', 'occurred_at', 'after_data']);
|
||||||
$disclosureAuthorizationData = $disclosureAuthorization ? json_decode($disclosureAuthorization->after_data, true) : null;
|
$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']);
|
->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');
|
$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());
|
$resources->each(fn ($resource) => $resource->links = $links->get($resource->id, collect())->values());
|
||||||
@@ -342,6 +355,7 @@ class PortalServicesController extends Controller
|
|||||||
$malwareHealth['signatures_at'] = $malwareHealth['signatures_at']?->format(DATE_ATOM);
|
$malwareHealth['signatures_at'] = $malwareHealth['signatures_at']?->format(DATE_ATOM);
|
||||||
|
|
||||||
return Inertia::render('portal/manage', ['resources' => $resources,
|
return Inertia::render('portal/manage', ['resources' => $resources,
|
||||||
|
'managementFilters' => $managementFilters, 'associationOptions' => $this->contentAssociations($request),
|
||||||
'requirementCatalogue' => $this->requirementEvidenceEnabled()
|
'requirementCatalogue' => $this->requirementEvidenceEnabled()
|
||||||
? collect(is_array($catalogue = config('document-requirements.catalogue', [])) ? $catalogue : [])->map(fn ($item, $key) => ['key' => $key, ...$item])->values()
|
? collect(is_array($catalogue = config('document-requirements.catalogue', [])) ? $catalogue : [])->map(fn ($item, $key) => ['key' => $key, ...$item])->values()
|
||||||
: collect(),
|
: collect(),
|
||||||
@@ -367,6 +381,47 @@ class PortalServicesController extends Controller
|
|||||||
'possibleDuplicates' => DB::table('portal_resources')->whereNotNull('duplicate_of_resource_id')->count()]);
|
'possibleDuplicates' => DB::table('portal_resources')->whereNotNull('duplicate_of_resource_id')->count()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $filters
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
private function contentAssociations(Request $request): array
|
||||||
|
{
|
||||||
|
$access = app(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' => Sector::choices()->orderBy('name')->get(['id as value', 'name as label']),
|
||||||
|
'territory' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id as value', 'name as label']),
|
||||||
|
'opportunity' => app(PortalProfileAccess::class)->scope(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::array('virtual-desk.steps', []))->map(fn ($step, $key) => ['value' => $key, 'label' => $step['title']])->values(),
|
||||||
|
'activity' => app(EconomicReferenceCatalog::class)->activities()->map(fn ($row) => ['value' => $row->id, 'label' => $row->display_label])->values(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public function upload(Request $request): RedirectResponse
|
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'],
|
$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 +454,7 @@ class PortalServicesController extends Controller
|
|||||||
|
|
||||||
ScanDocumentForMalware::dispatch($id)->afterCommit();
|
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
|
public function resource(Request $request): RedirectResponse
|
||||||
@@ -408,7 +463,7 @@ class PortalServicesController extends Controller
|
|||||||
$id = DB::transaction(function () use ($data, $request): int {
|
$id = DB::transaction(function () use ($data, $request): int {
|
||||||
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
|
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
|
||||||
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
|
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
|
||||||
abort_unless(app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
|
abort_unless(app(DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
|
||||||
$identity = $this->identityKey($data);
|
$identity = $this->identityKey($data);
|
||||||
if ($identity) {
|
if ($identity) {
|
||||||
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
|
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
|
||||||
@@ -437,11 +492,11 @@ class PortalServicesController extends Controller
|
|||||||
DB::transaction(function () use ($data, $request, $id, $expectedVersion): void {
|
DB::transaction(function () use ($data, $request, $id, $expectedVersion): void {
|
||||||
$resource = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
|
$resource = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
|
||||||
abort_unless($resource !== null, 404);
|
abort_unless($resource !== null, 404);
|
||||||
app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||||
abort_if((int) $resource->metadata_version !== $expectedVersion, 409, 'O documento foi alterado por outra sessão. Recarregue a revisão antes de editar.');
|
abort_if((int) $resource->metadata_version !== $expectedVersion, 409, 'O documento foi alterado por outra sessão. Recarregue a revisão antes de editar.');
|
||||||
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
|
$document = DB::table('documents')->where('id', $data['document_id'])->where('status', '!=', 'deleted')->whereNull('deleted_at')->lockForUpdate()->first();
|
||||||
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
|
abort_unless($document !== null, 422, 'Seleccione um documento existente e não eliminado.');
|
||||||
abort_unless(app(\App\Services\DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
|
abort_unless(app(DocumentManagementAccess::class)->documents($request->user())->where('id', $document->id)->exists(), 403);
|
||||||
$identity = $this->identityKey($data);
|
$identity = $this->identityKey($data);
|
||||||
if ($identity) {
|
if ($identity) {
|
||||||
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
|
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['portal-resource-identity:'.$identity]);
|
||||||
@@ -470,7 +525,7 @@ class PortalServicesController extends Controller
|
|||||||
|
|
||||||
public function moderate(Request $request, string $type, int $id): RedirectResponse
|
public function moderate(Request $request, string $type, int $id): RedirectResponse
|
||||||
{
|
{
|
||||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
$access = app(DocumentManagementAccess::class);
|
||||||
if (! $access->full($request->user())) {
|
if (! $access->full($request->user())) {
|
||||||
abort_unless($type === 'resources', 403);
|
abort_unless($type === 'resources', 403);
|
||||||
$access->assertEditableResource($request->user(), $id);
|
$access->assertEditableResource($request->user(), $id);
|
||||||
@@ -482,7 +537,9 @@ class PortalServicesController extends Controller
|
|||||||
$table = $type === 'resources' ? 'portal_resources' : 'portal_partnerships';
|
$table = $type === 'resources' ? 'portal_resources' : 'portal_partnerships';
|
||||||
DB::transaction(function () use ($request, $data, $table, $type, $id) {
|
DB::transaction(function () use ($request, $data, $table, $type, $id) {
|
||||||
abort_unless(DB::table($table)->where('id', $id)->lockForUpdate()->first() !== null, 404);
|
abort_unless(DB::table($table)->where('id', $id)->lockForUpdate()->first() !== null, 404);
|
||||||
if ($type === 'resources') app(\App\Services\DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
if ($type === 'resources') {
|
||||||
|
app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
|
||||||
|
}
|
||||||
if ($type === 'resources' && $data['published']) {
|
if ($type === 'resources' && $data['published']) {
|
||||||
$resource = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
$resource = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||||
->where('r.id', $id)->first(['r.document_type', 'r.legislation', 'r.source_confirmation', 'r.legal_status', 'r.rights_status',
|
->where('r.id', $id)->first(['r.document_type', 'r.legislation', 'r.source_confirmation', 'r.legal_status', 'r.rights_status',
|
||||||
@@ -663,7 +720,7 @@ class PortalServicesController extends Controller
|
|||||||
'data_classification' => ['nullable', 'in:internal,public'],
|
'data_classification' => ['nullable', 'in:internal,public'],
|
||||||
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
|
||||||
'legislation' => ['required', 'boolean'], 'essential' => ['required', 'boolean'],
|
'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.*.target_key' => ['required', 'string', 'max:180'],
|
||||||
'associations.*.review_status' => ['nullable', 'in:pending,confirmed'],
|
'associations.*.review_status' => ['nullable', 'in:pending,confirmed'],
|
||||||
'associations.*.relationship' => ['required', 'in:applies_to,supports,version_of,translation_of,amends,repeals,implements,cites,related_to'],
|
'associations.*.relationship' => ['required', 'in:applies_to,supports,version_of,translation_of,amends,repeals,implements,cites,related_to'],
|
||||||
@@ -795,17 +852,6 @@ class PortalServicesController extends Controller
|
|||||||
&& DB::table('migrations')->where('migration', '2026_10_06_200000_add_document_requirement_evidence_links')->exists();
|
&& DB::table('migrations')->where('migration', '2026_10_06_200000_add_document_requirement_evidence_links')->exists();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return list<string> */
|
|
||||||
private function resourceLinkColumns(): array
|
|
||||||
{
|
|
||||||
$columns = ['target_type', 'target_key', 'relationship', 'applicability', 'condition_text', 'basis_reference'];
|
|
||||||
if (Schema::hasColumn('portal_resource_links', 'review_status')) {
|
|
||||||
$columns[] = 'review_status';
|
|
||||||
}
|
|
||||||
|
|
||||||
return $columns;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @return list<string> */
|
/** @return list<string> */
|
||||||
private function territoryScopeIds(string $id): array
|
private function territoryScopeIds(string $id): array
|
||||||
{
|
{
|
||||||
@@ -829,4 +875,23 @@ SQL, [$id]);
|
|||||||
|
|
||||||
return $ids ?: [$id];
|
return $ids ?: [$id];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function articleUrl(int $id): ?string
|
||||||
|
{
|
||||||
|
if (! Schema::hasColumn('portal_resources', 'editorial_content')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$resource = DB::table('portal_resources')->where('id', $id)->first();
|
||||||
|
if (! $resource) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if ($resource->editorial_content !== null) {
|
||||||
|
return '/artigos/'.$id;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return app(EditorialReading::class)->original($resource) ? '/artigos/'.$resource->id : null;
|
||||||
|
} catch (HttpException) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Opportunity;
|
||||||
|
use App\Services\ProactiveSupply;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
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::whereKey($v['record_id'])->firstOrFail() : null;
|
||||||
|
|
||||||
|
return response()->json($service->search($request->user(), $request->all(), $record))->header('Cache-Control', 'private, no-store');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Services\Procurement;
|
||||||
|
use Illuminate\Database\Query\Builder;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
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): Builder
|
||||||
|
{
|
||||||
|
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): Response
|
||||||
|
{
|
||||||
|
$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 tap(Inertia::render('procurement/index', ['items' => $rows, 'filters' => $filters, 'options' => $options, 'regimes' => config('procurement.regimes'), 'management' => $service->access($request->user())])->toResponse($request), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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): Response
|
||||||
|
{
|
||||||
|
return $this->detail($request, $id, $service, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function print(Request $request, string $id, Procurement $service): Response
|
||||||
|
{
|
||||||
|
return $this->detail($request, $id, $service, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function detail(Request $request, string $id, Procurement $service, bool $print): Response
|
||||||
|
{
|
||||||
|
$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 tap(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), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function manage(Request $request, Procurement $service): Response
|
||||||
|
{
|
||||||
|
$service->guard($request->user());
|
||||||
|
|
||||||
|
return tap(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), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function edit(Request $request, Procurement $service, ?string $id = null): Response
|
||||||
|
{
|
||||||
|
$service->guard($request->user());
|
||||||
|
$r = $id ? $service->record($id) : null;
|
||||||
|
|
||||||
|
return tap(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), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function save(Request $request, Procurement $service, ?string $id = null): RedirectResponse
|
||||||
|
{
|
||||||
|
$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): JsonResponse
|
||||||
|
{
|
||||||
|
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): RedirectResponse
|
||||||
|
{
|
||||||
|
$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): RedirectResponse
|
||||||
|
{
|
||||||
|
$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): RedirectResponse
|
||||||
|
{
|
||||||
|
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): Response
|
||||||
|
{
|
||||||
|
$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 tap(Inertia::render('procurement/manage', ['watched' => true, 'items' => $rows])->toResponse($request), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,11 +4,13 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Http\Resources\PublicBusinessOpportunityResource;
|
use App\Http\Resources\PublicBusinessOpportunityResource;
|
||||||
use App\Models\ExistingBusiness;
|
use App\Models\ExistingBusiness;
|
||||||
|
use App\Models\Sector;
|
||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
use App\Services\ExistingBusinessDrafts;
|
|
||||||
use App\Services\ExistingBusinessClassification;
|
use App\Services\ExistingBusinessClassification;
|
||||||
use App\Services\OpportunityClassification;
|
use App\Services\ExistingBusinessDrafts;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
|
use App\Services\OpportunityClassification;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
@@ -43,8 +45,8 @@ class PublicBusinessOpportunityController extends Controller
|
|||||||
->orWhereLike('existing_businesses.objective', '%'.$term.'%'));
|
->orWhereLike('existing_businesses.objective', '%'.$term.'%'));
|
||||||
}
|
}
|
||||||
if (! empty($filters['sector'])) {
|
if (! empty($filters['sector'])) {
|
||||||
$sector = \App\Models\Sector::find($filters['sector']);
|
$sector = Sector::whereKey($filters['sector'])->first();
|
||||||
$query->whereIn('existing_businesses.sector_id', $sector ? \App\Models\Sector::whereIn('slug', \App\Services\SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
$query->whereIn('existing_businesses.sector_id', $sector ? Sector::whereIn('slug', SectorOrganization::slugs($sector->slug))->pluck('id') : []);
|
||||||
}
|
}
|
||||||
if (! empty($filters['modality'])) {
|
if (! empty($filters['modality'])) {
|
||||||
$query->where('existing_businesses.modality', $filters['modality']);
|
$query->where('existing_businesses.modality', $filters['modality']);
|
||||||
@@ -60,6 +62,9 @@ class PublicBusinessOpportunityController extends Controller
|
|||||||
'authorities' => DB::table('authorities')->where('status', 'published')->orderBy('label_pt_mz')->get(['id', 'label_pt_mz'])]);
|
'authorities' => DB::table('authorities')->where('status', 'published')->orderBy('label_pt_mz')->get(['id', 'label_pt_mz'])]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function filters(Request $request): array
|
private function filters(Request $request): array
|
||||||
{
|
{
|
||||||
return $request->validate([
|
return $request->validate([
|
||||||
|
|||||||
@@ -2,17 +2,27 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Services\InvestmentCorridorContext;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
|
||||||
class PublicGeographyController extends Controller
|
class PublicGeographyController extends Controller
|
||||||
{
|
{
|
||||||
public function options(Request $request, InvestmentGeography $geography): JsonResponse
|
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', 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']);
|
$query = $geography->publicReferences()->where('location_type', $data['type']);
|
||||||
|
if (! empty($data['corridor'])) {
|
||||||
|
$corridors = app(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'])) {
|
if (! empty($data['id'])) {
|
||||||
$query->where('id', $data['id']);
|
$query->where('id', $data['id']);
|
||||||
}
|
}
|
||||||
@@ -29,6 +39,6 @@ class PublicGeographyController extends Controller
|
|||||||
->orWhereRaw('source_code ILIKE ?', [$term]));
|
->orWhereRaw('source_code ILIKE ?', [$term]));
|
||||||
}
|
}
|
||||||
|
|
||||||
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code']));
|
return response()->json($query->orderBy('name')->orderBy('id')->paginate(100, ['id', 'name', 'parent_id', 'location_type', 'source_code'])->withQueryString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ use App\Models\Opportunity;
|
|||||||
use App\Models\Sector;
|
use App\Models\Sector;
|
||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
use App\Services\SectorInvestment;
|
use App\Services\SectorInvestment;
|
||||||
|
use App\Services\SectorOrganization;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
@@ -19,15 +21,17 @@ class PublicPortalController extends Controller
|
|||||||
return Inertia::render('PortalInvestidor', ['initialView' => 'opportunities', 'initialQuery' => $filters['q'] ?? '', 'initialSector' => $filters['sector'] ?? '']);
|
return Inertia::render('PortalInvestidor', ['initialView' => 'opportunities', 'initialQuery' => $filters['q'] ?? '', 'initialSector' => $filters['sector'] ?? '']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function sector(string $slug): Response|\Illuminate\Http\RedirectResponse
|
public function sector(string $slug): Response|RedirectResponse
|
||||||
{
|
{
|
||||||
if (in_array($slug, ['energia', 'fintech'], true)) return redirect(\App\Services\SectorOrganization::href($slug), 301);
|
if (in_array($slug, ['energia', 'fintech'], true)) {
|
||||||
if ($slug === 'mercado-financeiro/fintech') $slug = 'fintech';
|
return redirect(SectorOrganization::href($slug), 301);
|
||||||
|
}
|
||||||
|
if ($slug === 'mercado-financeiro/fintech') {
|
||||||
|
$slug = 'fintech';
|
||||||
|
}
|
||||||
$sector = Sector::where('slug', $slug)->where('is_active', true)->whereNotNull('published_at')->firstOrFail();
|
$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']),
|
return Inertia::render('portal/services', ['section' => 'sector', ...app(SectorInvestment::class)->page($sector)]);
|
||||||
'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'])]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function opportunity(string $slug): Response
|
public function opportunity(string $slug): Response
|
||||||
|
|||||||
@@ -1,20 +1,24 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Services\SectorReconciliationExecution;
|
use App\Services\SectorReconciliationExecution;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Http\Response;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
final class SectorReconciliationController extends Controller
|
final class SectorReconciliationController extends Controller
|
||||||
{
|
{
|
||||||
public function preview(Request $request, SectorReconciliationExecution $execution)
|
public function preview(Request $request, SectorReconciliationExecution $execution): JsonResponse|Response
|
||||||
{
|
{
|
||||||
$plan = $execution->preview($request);
|
$plan = $execution->preview($request);
|
||||||
|
|
||||||
return $request->expectsJson() ? response()->json($plan)->header('Cache-Control', 'private, no-store')
|
return $request->expectsJson() ? response()->json($plan)->header('Cache-Control', 'private, no-store')
|
||||||
: response()->view('management.sector-reconciliation', ['plan' => $plan, 'operationKey' => (string)Str::uuid()])->header('Cache-Control', 'private, no-store');
|
: response()->view('management.sector-reconciliation', ['plan' => $plan, 'operationKey' => (string) Str::uuid()])->header('Cache-Control', 'private, no-store');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function apply(Request $request, SectorReconciliationExecution $execution)
|
public function apply(Request $request, SectorReconciliationExecution $execution): JsonResponse
|
||||||
{
|
{
|
||||||
return response()->json($execution->apply($request))->header('Cache-Control', 'private, no-store');
|
return response()->json($execution->apply($request))->header('Cache-Control', 'private, no-store');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Services\SimulationFiscalQaPreview;
|
||||||
use App\Services\SimulationTaxParameterResolver;
|
use App\Services\SimulationTaxParameterResolver;
|
||||||
use App\Services\SimulationTaxRuleExpression;
|
use App\Services\SimulationTaxRuleExpression;
|
||||||
use App\Services\SimulationTaxRuleGovernance;
|
use App\Services\SimulationTaxRuleGovernance;
|
||||||
|
use App\Support\IsolatedQaDatabase;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Inertia\Response;
|
||||||
use InvalidArgumentException;
|
use InvalidArgumentException;
|
||||||
|
|
||||||
class SimulationTaxRuleGovernanceController extends Controller
|
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
|
public function index(Request $request, SimulationTaxRuleGovernance $governance): JsonResponse
|
||||||
{
|
{
|
||||||
$filters = $request->validate([
|
$filters = $request->validate([
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use App\Services\CountryCatalogue;
|
|||||||
use App\Services\InstitutionalLinkMonitor;
|
use App\Services\InstitutionalLinkMonitor;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use App\Services\InvestorContextConsumers;
|
use App\Services\InvestorContextConsumers;
|
||||||
|
use App\Services\ScopedPortalAdministration;
|
||||||
use App\Services\VerifiedDocumentBinary;
|
use App\Services\VerifiedDocumentBinary;
|
||||||
use App\Services\VirtualDesk;
|
use App\Services\VirtualDesk;
|
||||||
use Illuminate\Http\JsonResponse;
|
use Illuminate\Http\JsonResponse;
|
||||||
@@ -21,6 +22,7 @@ use Illuminate\Support\Facades\Crypt;
|
|||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
use Inertia\Response;
|
use Inertia\Response;
|
||||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||||
@@ -119,8 +121,8 @@ class VirtualDeskController extends Controller
|
|||||||
|
|
||||||
public function createRequest(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
public function createRequest(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||||
{
|
{
|
||||||
$data = $request->validate(['service_version_id' => 'required|uuid', 'client_key' => 'required|uuid']);
|
$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']);
|
$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);
|
return $request->expectsJson() ? response()->json(['id' => $row->id, 'version' => $row->version], 201) : redirect('/balcao-virtual/pedidos/'.$row->id);
|
||||||
}
|
}
|
||||||
@@ -148,7 +150,7 @@ class VirtualDeskController extends Controller
|
|||||||
$data = ['boundContextRevision' => app(InvestorContextConsumers::class)->requestRevision($row), 'countries' => app(CountryCatalogue::class)->all(), 'toolPrefill' => $desk->requestToolPrefill($request->user(), $row), 'request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)],
|
$data = ['boundContextRevision' => app(InvestorContextConsumers::class)->requestRevision($row), 'countries' => app(CountryCatalogue::class)->all(), 'toolPrefill' => $desk->requestToolPrefill($request->user(), $row), 'request' => [...(array) $row, 'payload' => $payload, 'submitted_snapshot' => $desk->decode($row->submitted_snapshot), 'editable_fields' => json_decode($row->editable_fields ?? '[]', true)],
|
||||||
'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $definition, 'territoryPaths' => $territoryPaths,
|
'case' => ['id' => $case->id, 'title' => $case->title], 'caseVersion' => $case->version, 'definition' => $definition, 'territoryPaths' => $territoryPaths,
|
||||||
'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true),
|
'serviceSource' => json_decode(DB::table('desk_service_versions')->where('id', $row->service_version_id)->value('source'), true),
|
||||||
'owner' => $desk->owns($request->user(), $case), 'manager' => app(\App\Services\ScopedPortalAdministration::class)->deskDecision($request->user(),$row), 'analyst' => (int) $row->analyst_id === $request->user()->id,
|
'owner' => $desk->owns($request->user(), $case), 'manager' => app(ScopedPortalAdministration::class)->deskDecision($request->user(), $row), 'analyst' => (int) $row->analyst_id === $request->user()->id,
|
||||||
'fieldsEditable' => in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => config('virtual-desk.transitions.'.$row->status, []),
|
'fieldsEditable' => in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => config('virtual-desk.transitions.'.$row->status, []),
|
||||||
'findings' => $desk->findings($payload), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
|
'findings' => $desk->findings($payload), 'ai' => config('virtual-desk.ai'), 'documents' => $this->documents($case->id, $request->user())->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
|
||||||
'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body),
|
'messages' => DB::table('desk_messages as m')->join('users as u', 'u.id', '=', 'm.actor_id')->where('request_id', $id)->orderBy('m.created_at')->get(['m.id', 'm.actor_id', 'm.body', 'm.created_at', 'u.name'])->map(fn ($m) => [...(array) $m, 'body' => Crypt::decryptString($m->body),
|
||||||
@@ -178,24 +180,29 @@ class VirtualDeskController extends Controller
|
|||||||
|
|
||||||
public function assignments(Request $request): JsonResponse|Response
|
public function assignments(Request $request): JsonResponse|Response
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()),403);
|
abort_unless(app(ScopedPortalAdministration::class)->administrative($request->user()), 403);
|
||||||
// Triage projection deliberately excludes payloads, documents, investor identity and case titles.
|
// Triage projection deliberately excludes payloads, documents, investor identity and case titles.
|
||||||
$data=['requests'=>DB::table('desk_requests')->whereNotIn('status',['draft','cancelled','closed'])->orderBy('created_at')->get(['id','protocol','status','version','analyst_id','due_at']),
|
$data = ['requests' => DB::table('desk_requests')->whereNotIn('status', ['draft', 'cancelled', 'closed'])->orderBy('created_at')->get(['id', 'protocol', 'status', 'version', 'analyst_id', 'due_at']),
|
||||||
'analysts'=>User::whereNotNull('email_verified_at')->orderBy('name')->get(['id','name'])];
|
'analysts' => User::whereNotNull('email_verified_at')->orderBy('name')->get(['id', 'name'])];
|
||||||
return $request->expectsJson()?response()->json($data):Inertia::render('management/desk-assignments',$data);
|
|
||||||
|
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/desk-assignments', $data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function assign(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
public function assign(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
|
||||||
{
|
{
|
||||||
abort_unless(app(\App\Services\ScopedPortalAdministration::class)->administrative($request->user()), 403);
|
abort_unless(app(ScopedPortalAdministration::class)->administrative($request->user()), 403);
|
||||||
$data = $request->validate(['version' => 'required|integer', 'analyst_id' => 'required|integer|exists:users,id', 'reason' => 'required|string|min:3|max:3000', 'due_at' => 'nullable|date'], ['reason.required'=>'Explique o motivo da atribuição.','reason.min'=>'Explique o motivo da atribuição com pelo menos 3 caracteres.','analyst_id.required'=>'Seleccione o responsável.','analyst_id.exists'=>'Seleccione um responsável com conta disponível.']);
|
$data = $request->validate(['version' => 'required|integer', 'analyst_id' => 'required|integer|exists:users,id', 'reason' => 'required|string|min:3|max:3000', 'due_at' => 'nullable|date'], ['reason.required' => 'Explique o motivo da atribuição.', 'reason.min' => 'Explique o motivo da atribuição com pelo menos 3 caracteres.', 'analyst_id.required' => 'Seleccione o responsável.', 'analyst_id.exists' => 'Seleccione um responsável com conta disponível.']);
|
||||||
DB::transaction(function () use ($request, $id, $desk, $data) {
|
DB::transaction(function () use ($request, $id, $desk, $data) {
|
||||||
$row = DB::table('desk_requests')->where('id',$id)->lockForUpdate()->first();
|
$row = DB::table('desk_requests')->where('id', $id)->lockForUpdate()->first();
|
||||||
abort_unless($row,404);
|
abort_unless($row !== null, 404);
|
||||||
$case = DB::table('desk_cases')->where('id',$row->case_id)->first();
|
$case = DB::table('desk_cases')->where('id', $row->case_id)->first();
|
||||||
abort_unless($case,404);
|
abort_unless($case !== null, 404);
|
||||||
if ((int)$row->version !== (int)$data['version']) throw \Illuminate\Validation\ValidationException::withMessages(['version'=>'Este pedido foi actualizado. Recupere a lista e tente novamente.']);
|
if ((int) $row->version !== (int) $data['version']) {
|
||||||
if (in_array($row->status,['draft','cancelled','closed'],true)) throw \Illuminate\Validation\ValidationException::withMessages(['status'=>'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
|
throw ValidationException::withMessages(['version' => 'Este pedido foi actualizado. Recupere a lista e tente novamente.']);
|
||||||
|
}
|
||||||
|
if (in_array($row->status, ['draft', 'cancelled', 'closed'], true)) {
|
||||||
|
throw ValidationException::withMessages(['status' => 'Este pedido já não permite uma nova atribuição. Recupere a lista actual.']);
|
||||||
|
}
|
||||||
$analyst = User::where('id', $data['analyst_id'])->firstOrFail();
|
$analyst = User::where('id', $data['analyst_id'])->firstOrFail();
|
||||||
abort_unless($analyst->hasVerifiedEmail(), 422, 'O responsável deve ter conta verificada.');
|
abort_unless($analyst->hasVerifiedEmail(), 422, 'O responsável deve ter conta verificada.');
|
||||||
abort_if($desk->owns($analyst, $case, false), 422, 'O proponente não pode ser o analista.');
|
abort_if($desk->owns($analyst, $case, false), 422, 'O proponente não pode ser o analista.');
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ class EnsureDocumentManagement
|
|||||||
public function handle(Request $request, Closure $next): Response
|
public function handle(Request $request, Closure $next): Response
|
||||||
{
|
{
|
||||||
$actor = $request->user();
|
$actor = $request->user();
|
||||||
abort_unless($actor, 403);
|
abort_unless($actor !== null, 403);
|
||||||
$access = app(DocumentManagementAccess::class);
|
$access = app(DocumentManagementAccess::class);
|
||||||
if ($access->full($actor)) {
|
if ($access->full($actor)) {
|
||||||
return $next($request); // Preserve existing management controls.
|
return $next($request); // Preserve existing management controls.
|
||||||
|
|||||||
@@ -1,37 +1,50 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
/** Environment reservation is not a portal identity or a business permission. */
|
/** Environment reservation is not a portal identity or a business permission. */
|
||||||
class EnsureHomologationAccess
|
class EnsureHomologationAccess
|
||||||
{
|
{
|
||||||
public function handle(Request $request, Closure $next): Response
|
public function handle(Request $request, Closure $next): Response
|
||||||
{
|
{
|
||||||
if (!config('portal.homologation_only', false)) return $next($request);
|
if (! config('portal.homologation_only', false)) {
|
||||||
$mode=config('portal.homologation_access_mode', 'reviewers');
|
return $next($request);
|
||||||
if ($mode==='perimeter') {
|
}
|
||||||
// Set only by the trusted server after its environment-access check.
|
$mode = config('portal.homologation_access_mode', 'reviewers');
|
||||||
// A client HTTP_INVESTMOZ_* header is deliberately not accepted.
|
if ($mode === 'perimeter') {
|
||||||
abort_unless($request->server('INVESTMOZ_HOMOLOGATION_ACCESS')==='granted',403,
|
// Set only by the trusted server after its environment-access check.
|
||||||
'Este ambiente de homologação tem acesso reservado à Tempo.');
|
// A client HTTP_INVESTMOZ_* header is deliberately not accepted.
|
||||||
$response=$next($request);
|
abort_unless($request->server('INVESTMOZ_HOMOLOGATION_ACCESS') === 'granted', 403,
|
||||||
$response->headers->set('Cache-Control','private, no-store');
|
'Este ambiente de homologação tem acesso reservado à Tempo.');
|
||||||
$response->headers->set('X-Robots-Tag','noindex, nofollow, noarchive');
|
$response = $next($request);
|
||||||
return $response;
|
$response->headers->set('Cache-Control', 'private, no-store');
|
||||||
}
|
$response->headers->set('X-Robots-Tag', 'noindex, nofollow, noarchive');
|
||||||
abort_unless($mode==='reviewers',503,'A reserva da homologação não está configurada.');
|
|
||||||
// Compatibility until an independent perimeter is explicitly configured.
|
return $response;
|
||||||
if ($request->is('login','logout','register','forgot-password','reset-password','reset-password/*',
|
}
|
||||||
'email/verify','email/verify/*','email/verification-notification','two-factor-challenge',
|
abort_unless($mode === 'reviewers', 503, 'A reserva da homologação não está configurada.');
|
||||||
'user/confirm-password','user/confirmed-password-status','user/two-factor-*',
|
// Compatibility until an independent perimeter is explicitly configured.
|
||||||
'settings/security','settings/password','user/password','passkeys/*','user/passkeys/*','up')) return $next($request);
|
if ($request->is('login', 'logout', 'register', 'forgot-password', 'reset-password', 'reset-password/*',
|
||||||
$actor=$request->user();
|
'email/verify', 'email/verify/*', 'email/verification-notification', 'two-factor-challenge',
|
||||||
if (!$actor) return $request->expectsJson()
|
'user/confirm-password', 'user/confirmed-password-status', 'user/two-factor-*',
|
||||||
? response()->json(['message'=>'Entre na conta autorizada para homologação.'],401)
|
'settings/security', 'settings/password', 'user/password', 'passkeys/*', 'user/passkeys/*', 'up')) {
|
||||||
: redirect()->guest(route('login'));
|
return $next($request);
|
||||||
abort_unless($actor->hasVerifiedEmail() && in_array(strtolower(trim($actor->email)),config('portal.homologation_reviewers',[]),true),403,
|
}
|
||||||
'Esta homologação está reservada às contas indicadas pela Tempo.');
|
$actor = $request->user();
|
||||||
$response=$next($request);$response->headers->set('Cache-Control','private, no-store');return $response;
|
if (! $actor) {
|
||||||
}
|
return $request->expectsJson()
|
||||||
|
? response()->json(['message' => 'Entre na conta autorizada para homologação.'], 401)
|
||||||
|
: redirect()->guest(route('login'));
|
||||||
|
}
|
||||||
|
abort_unless($actor->hasVerifiedEmail() && in_array(strtolower(trim($actor->email)), config('portal.homologation_reviewers', []), true), 403,
|
||||||
|
'Esta homologação está reservada às contas indicadas pela Tempo.');
|
||||||
|
$response = $next($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,30 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Services\DocumentManagementAccess;
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
class EnsureScopedEditorial
|
class EnsureScopedEditorial
|
||||||
{
|
{
|
||||||
public function handle(Request $request, Closure $next): Response
|
public function handle(Request $request, Closure $next): Response
|
||||||
{
|
{
|
||||||
$actor = $request->user();
|
$actor = $request->user();
|
||||||
abort_unless($actor, 403);
|
abort_unless($actor !== null, 403);
|
||||||
$access = app(\App\Services\DocumentManagementAccess::class);
|
$access = app(DocumentManagementAccess::class);
|
||||||
if ($access->full($actor)) {
|
if ($access->full($actor)) {
|
||||||
return $next($request);
|
return $next($request);
|
||||||
}
|
}
|
||||||
abort_unless($access->editorial($actor), 403);
|
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');
|
|| ($request->route()->getName() === 'services.moderate' && $request->route('type') === 'resources');
|
||||||
abort_unless($allowed, 403);
|
abort_unless($allowed, 403);
|
||||||
if ($request->route('id') !== null) {
|
if ($request->route('id') !== null) {
|
||||||
$access->assertEditableResource($actor, (int) $request->route('id'));
|
$access->assertEditableResource($actor, (int) $request->route('id'));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $next($request);
|
return $next($request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,41 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use App\Services\PortalProfileAccess;
|
||||||
|
use App\Services\ScopedPortalAdministration;
|
||||||
|
use App\Services\SimulationTaxGovernanceAccess;
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Symfony\Component\HttpFoundation\Response;
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
use App\Services\ScopedPortalAdministration;
|
|
||||||
|
|
||||||
final class EnsureScopedPortalAdministration
|
final class EnsureScopedPortalAdministration
|
||||||
{
|
{
|
||||||
public function handle(Request $request, Closure $next): Response
|
public function handle(Request $request, Closure $next): Response
|
||||||
{
|
{
|
||||||
$actor=$request->user();abort_unless($actor,403);
|
$actor = $request->user();
|
||||||
$scope=app(ScopedPortalAdministration::class);
|
abort_unless($actor !== null, 403);
|
||||||
$path=$request->path();
|
$scope = app(ScopedPortalAdministration::class);
|
||||||
$interests=$request->is('management/interests','management/interests/*','api/v1/investment/admin/interests/*');
|
$path = $request->path();
|
||||||
// Exact areas of P1; unrelated management, fiscal rules and private records keep their gate.
|
$interests = $request->is('management/interests', 'management/interests/*', 'api/v1/investment/admin/interests/*');
|
||||||
$catalogue=$request->is('management/economic-references/lot-01','management/economic-references/lot-01/*',
|
// Fiscal maintenance reuses authorised administration; unrelated gates remain unchanged.
|
||||||
'management/education','management/education/*','management/investment/references','management/investment/references/*','api/v1/investment/admin/references','api/v1/investment/admin/references/*',
|
$geometryRead = $request->isMethod('GET') && $path === 'management/territory-geometries';
|
||||||
'management/investment/zones','management/investment/zones/*','api/v2/investment/admin/zones','api/v2/investment/admin/zones/*',
|
$catalogue = $geometryRead || $request->is('management/territory-geometry-import', 'management/territory-geometry-import/*',
|
||||||
'management/balcao/atribuicoes','management/balcao/atribuicoes/*','management/balcao/servicos',
|
'management/economic-references/lot-01', 'management/economic-references/lot-01/*',
|
||||||
'management/balcao/fontes') || ($request->isMethod('GET') && $path==='management/balcao-install');
|
'management/education', 'management/education/*', 'management/investment/references', 'management/investment/references/*', 'api/v1/investment/admin/references', 'api/v1/investment/admin/references/*',
|
||||||
$allowed=$interests ? $scope->interestOperator($actor) : ($catalogue && $scope->administrative($actor));
|
'management/investment/zones', 'management/investment/zones/*', 'api/v2/investment/admin/zones', 'api/v2/investment/admin/zones/*',
|
||||||
abort_unless($allowed || ($actor->can('manage-portal') && !app(\App\Services\PortalProfileAccess::class)->has($actor,'auditor')),403,'Acesso reservado ao âmbito já designado.');
|
'management/balcao/atribuicoes', 'management/balcao/atribuicoes/*', 'management/balcao/servicos',
|
||||||
$response=$next($request);
|
'management/balcao/fontes') || ($request->isMethod('GET') && $path === 'management/balcao-install');
|
||||||
if (!$request->isMethod('GET') && $response->getStatusCode()<400) {
|
$fiscal = $request->is('api/v2/investment/admin/tax-rules', 'api/v2/investment/admin/tax-rules/*',
|
||||||
app(\App\Services\PortalProfileAccess::class)->audit($actor,'scoped_administration',[
|
'api/v2/investment/admin/tax-rule-sources', 'management/investment/tax-rules/*');
|
||||||
'method'=>$request->method(),'route'=>$request->route()?->uri(),'scope'=>$interests?'assigned-interest':'catalogue-administration']);
|
$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;
|
return $response;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ final class EnsureSimulationRecoveryCookie
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $response->withCookie(cookie(
|
$response->headers->setCookie(cookie(
|
||||||
self::NAME,
|
self::NAME,
|
||||||
$forget ? '' : $token,
|
$forget ? '' : $token,
|
||||||
$minutes,
|
$minutes,
|
||||||
@@ -64,6 +64,8 @@ final class EnsureSimulationRecoveryCookie
|
|||||||
false,
|
false,
|
||||||
'lax',
|
'lax',
|
||||||
));
|
));
|
||||||
|
|
||||||
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function isExplicitDraftActivity(Request $request, Response $response): bool
|
private function isExplicitDraftActivity(Request $request, Response $response): bool
|
||||||
|
|||||||
@@ -3,10 +3,13 @@
|
|||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
use App\Models\ExistingBusiness;
|
use App\Models\ExistingBusiness;
|
||||||
|
use App\Services\ContentManagement;
|
||||||
use App\Services\InvestorPath;
|
use App\Services\InvestorPath;
|
||||||
use App\Services\LegacyContent;
|
use App\Services\LegacyContent;
|
||||||
use App\Services\OpportunityManagement;
|
use App\Services\OpportunityManagement;
|
||||||
use App\Services\PortalProfileAccess;
|
use App\Services\PortalProfileAccess;
|
||||||
|
use App\Services\Procurement;
|
||||||
|
use App\Services\ScopedPortalAdministration;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Inertia\Middleware;
|
use Inertia\Middleware;
|
||||||
|
|
||||||
@@ -48,11 +51,16 @@ class HandleInertiaRequests extends Middleware
|
|||||||
*/
|
*/
|
||||||
public function share(Request $request): array
|
public function share(Request $request): array
|
||||||
{
|
{
|
||||||
|
$contentManagementAccess = app(ContentManagement::class)->access($request->user());
|
||||||
|
|
||||||
return [
|
return [
|
||||||
...parent::share($request),
|
...parent::share($request),
|
||||||
'name' => config('app.name'),
|
'name' => config('app.name'),
|
||||||
|
'procurementEnabled' => app(Procurement::class)->available(),
|
||||||
'homologationReserved' => (bool) config('portal.homologation_only', false),
|
'homologationReserved' => (bool) config('portal.homologation_only', false),
|
||||||
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
|
'profileAccess' => app(PortalProfileAccess::class)->navigation($request->user()),
|
||||||
|
'contentManagementHref' => $contentManagementAccess !== [] ? '/gestao-conteudos' : null,
|
||||||
|
'contentManagementAccess' => $contentManagementAccess,
|
||||||
'portalOperator' => config('portal.operator_name'),
|
'portalOperator' => config('portal.operator_name'),
|
||||||
'portalInstitutionalContactEmail' => filter_var(config('portal.institutional_contact_email'), FILTER_VALIDATE_EMAIL) ?: null,
|
'portalInstitutionalContactEmail' => filter_var(config('portal.institutional_contact_email'), FILTER_VALIDATE_EMAIL) ?: null,
|
||||||
'legacyContentEnabled' => app(LegacyContent::class)->available(),
|
'legacyContentEnabled' => app(LegacyContent::class)->available(),
|
||||||
@@ -68,19 +76,20 @@ class HandleInertiaRequests extends Middleware
|
|||||||
'create' => ['label' => 'Nova oportunidade', 'href' => '/management/opportunities/create'],
|
'create' => ['label' => 'Nova oportunidade', 'href' => '/management/opportunities/create'],
|
||||||
'installationHref' => '/management/opportunity-management-install',
|
'installationHref' => '/management/opportunity-management-install',
|
||||||
] : null,
|
] : 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()) ? [
|
'scopedAdministration' => $request->user() && app(ScopedPortalAdministration::class)->administrative($request->user()) ? [
|
||||||
['label'=>'Zonas e parques','href'=>'/management/investment/zones'],
|
['label' => 'Zonas e parques', 'href' => '/management/investment/zones'],
|
||||||
['label'=>'Referências económicas','href'=>'/management/economic-references/lot-01'],
|
['label' => 'Referências económicas', 'href' => '/management/economic-references/lot-01'],
|
||||||
['label'=>'Referências e formulários','href'=>'/management/investment/references'],
|
['label' => 'Referências e formulários', 'href' => '/management/investment/references'],
|
||||||
['label'=>'Educação e competências','href'=>'/management/education'],
|
['label' => 'Educação e competências', 'href' => '/management/education'],
|
||||||
['label'=>'Interesses atribuídos','href'=>'/management/interests'],
|
['label' => 'Interesses atribuídos', 'href' => '/management/interests'],
|
||||||
['label'=>'Atribuições de interesses','href'=>'/management/interests/atribuicoes'],
|
['label' => 'Atribuições de interesses', 'href' => '/management/interests/atribuicoes'],
|
||||||
['label'=>'Atribuições do Balcão','href'=>'/management/balcao/atribuicoes'],
|
['label' => 'Atribuições do Balcão', 'href' => '/management/balcao/atribuicoes'],
|
||||||
] : [],
|
] : [],
|
||||||
'auth' => [
|
'auth' => [
|
||||||
'user' => $request->user(),
|
'user' => $request->user(),
|
||||||
'canManagePortal' => $request->user()?->can('manage-portal') ?? false,
|
'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',
|
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -13,15 +13,19 @@ class PortalProfileSession
|
|||||||
{
|
{
|
||||||
public function handle(Request $request, Closure $next): Response
|
public function handle(Request $request, Closure $next): Response
|
||||||
{
|
{
|
||||||
|
if (! $request->user()) {
|
||||||
|
return $next($request);
|
||||||
|
}
|
||||||
|
|
||||||
$access = app(PortalProfileAccess::class);
|
$access = app(PortalProfileAccess::class);
|
||||||
$available = $access->governanceAvailable();
|
$available = $access->governanceAvailable();
|
||||||
if ($request->user() && (config('portal.profile_access_enabled') || config('portal.profile_administration_enabled')) && ! $available) {
|
if ((config('portal.profile_access_enabled') || config('portal.profile_administration_enabled')) && ! $available) {
|
||||||
$recovery = $request->is('management/profile-install', 'management/profile-install/bootstrap')
|
$recovery = $request->is('management/profile-install', 'management/profile-install/bootstrap')
|
||||||
|| ($request->is('logout') && $request->isMethod('POST'));
|
|| ($request->is('logout') && $request->isMethod('POST'));
|
||||||
abort_if(! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true) && ! $recovery, 503,
|
abort_if(! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true) && ! $recovery, 503,
|
||||||
'Autorizações indisponíveis: recuperar a consistência dos perfis antes de gravar. Pode terminar a sessão ou consultar o instalador.');
|
'Autorizações indisponíveis: recuperar a consistência dos perfis antes de gravar. Pode terminar a sessão ou consultar o instalador.');
|
||||||
}
|
}
|
||||||
if ($request->user() && $available) {
|
if ($available) {
|
||||||
$revision = (int) DB::table('users')->where('id', $request->user()->id)->value('portal_access_revision');
|
$revision = (int) DB::table('users')->where('id', $request->user()->id)->value('portal_access_revision');
|
||||||
$bound = $request->session()->get('portal.access_revision');
|
$bound = $request->session()->get('portal.access_revision');
|
||||||
if (($bound === null && $revision > 0) || ($bound !== null && (int) $bound !== $revision)) {
|
if (($bound === null && $revision > 0) || ($bound !== null && (int) $bound !== $revision)) {
|
||||||
|
|||||||
@@ -29,7 +29,9 @@ class ProtectProfileOpportunity
|
|||||||
if ($record && ($record->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades'))) {
|
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.');
|
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 = 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->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.');
|
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.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,15 +13,22 @@ class VerifiedOrSimpleParticipation
|
|||||||
{
|
{
|
||||||
public function handle(Request $request, Closure $next): Response
|
public function handle(Request $request, Closure $next): Response
|
||||||
{
|
{
|
||||||
if ($request->user()->hasVerifiedEmail()) return $next($request);
|
if ($request->user()->hasVerifiedEmail()) {
|
||||||
if ($request->isMethod('GET') && $request->is('investidor/manifestacoes', 'api/v1/investment/submissions')) return $next($request);
|
return $next($request);
|
||||||
|
}
|
||||||
|
if ($request->isMethod('GET') && $request->is('investidor/manifestacoes', 'api/v1/investment/submissions')) {
|
||||||
|
return $next($request);
|
||||||
|
}
|
||||||
$id = $request->route('id');
|
$id = $request->route('id');
|
||||||
$show = $request->isMethod('GET') && $request->is('investidor/manifestacoes/'.$id, 'api/v1/investment/submissions/'.$id);
|
$show = $request->isMethod('GET') && $request->is('investidor/manifestacoes/'.$id, 'api/v1/investment/submissions/'.$id);
|
||||||
$message = $request->isMethod('POST') && $request->is('investidor/manifestacoes/'.$id.'/messages', 'api/v1/investment/submissions/'.$id.'/messages');
|
$message = $request->isMethod('POST') && $request->is('investidor/manifestacoes/'.$id.'/messages', 'api/v1/investment/submissions/'.$id.'/messages');
|
||||||
if ($id && ($show || $message)) {
|
if ($id && ($show || $message)) {
|
||||||
$row = InvestmentSubmission::whereKey($id)->where('user_id', $request->user()->id)->firstOrFail();
|
$row = InvestmentSubmission::whereKey($id)->where('user_id', $request->user()->id)->firstOrFail();
|
||||||
if ($row->status === 'submitted' && ($row->payload['simple_participation'] ?? false) === true) return $next($request);
|
if ($row->status === 'submitted' && ($row->payload['simple_participation'] ?? false) === true) {
|
||||||
|
return $next($request);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return app(EnsureEmailIsVerified::class)->handle($request, $next);
|
return app(EnsureEmailIsVerified::class)->handle($request, $next);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ class ResolveSimulationTaxParametersRequest extends FormRequest
|
|||||||
'component' => ['required', 'in:IRPC,IVA,ISPC,IRPS,INSS,RETENCOES,DIREITOS_ADUANEIROS,ICE'],
|
'component' => ['required', 'in:IRPC,IVA,ISPC,IRPS,INSS,RETENCOES,DIREITOS_ADUANEIROS,ICE'],
|
||||||
'period_start' => ['required', 'date_format:Y-m-d'],
|
'period_start' => ['required', 'date_format:Y-m-d'],
|
||||||
'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
|
'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'],
|
'context.*' => ['string', 'max:160'],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ namespace App\Http\Requests;
|
|||||||
|
|
||||||
use App\Models\LandAssistanceCase;
|
use App\Models\LandAssistanceCase;
|
||||||
use App\Services\CountryCatalogue;
|
use App\Services\CountryCatalogue;
|
||||||
|
use App\Services\InvestmentConsumerScope;
|
||||||
use App\Services\InvestmentGeography;
|
use App\Services\InvestmentGeography;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\Validator;
|
use Illuminate\Validation\Validator;
|
||||||
@@ -19,7 +21,14 @@ class StoreLandAssistanceCaseRequest extends FormRequest
|
|||||||
{
|
{
|
||||||
$payload = $this->validated('payload');
|
$payload = $this->validated('payload');
|
||||||
|
|
||||||
return is_array($payload) ? $payload : [];
|
if (! is_array($payload)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
if (! empty($payload['investor_path_case_id'])) {
|
||||||
|
return app(InvestmentConsumerScope::class)->bind($this->user(), $payload['investor_path_case_id'], $payload, $this->routeIs('land-assistance.support'));
|
||||||
|
}
|
||||||
|
|
||||||
|
return Arr::except($payload, ['context_opportunity', 'context_opportunity_snapshot']);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function authorize(): bool
|
public function authorize(): bool
|
||||||
@@ -33,7 +42,10 @@ class StoreLandAssistanceCaseRequest extends FormRequest
|
|||||||
return [
|
return [
|
||||||
'version' => [$this->isMethod('post') && ! $this->routeIs('land-assistance.support') ? 'nullable' : 'required', 'integer', 'min:1'],
|
'version' => [$this->isMethod('post') && ! $this->routeIs('land-assistance.support') ? 'nullable' : 'required', 'integer', 'min:1'],
|
||||||
'context_revision' => ['nullable', 'integer', 'min:0'], 'context_reviewed' => ['nullable', 'boolean'],
|
'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.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.request_description' => ['nullable', 'string', 'max:4000'],
|
||||||
'payload.project_reference' => ['nullable', 'string', 'max:160'],
|
'payload.project_reference' => ['nullable', 'string', 'max:160'],
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
|
|||||||
'contact_province', 'contact_district', 'preferred_channel',
|
'contact_province', 'contact_district', 'preferred_channel',
|
||||||
];
|
];
|
||||||
$economic = [
|
$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',
|
'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',
|
'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',
|
'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',
|
'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',
|
'sales_taxable', 'sales_exempt', 'sales_zero_rate', 'exports', 'deductible_costs', 'non_deductible_costs',
|
||||||
'carried_losses', 'payroll', 'outbound_payments', 'imports', 'claimed_benefits', 'reference_date',
|
'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_operation', 'fiscal_activity', 'fiscal_establishments', 'fiscal_documentation',
|
||||||
'fiscal_customs_code', 'fiscal_vat_refund_state',
|
'fiscal_customs_code', 'fiscal_vat_refund_state',
|
||||||
'offer_or_demand', 'opportunity_type', 'opportunity_type_other', 'opportunity_description',
|
'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.detail_level' => ['nullable', 'in:simple,advanced'],
|
||||||
'economic_snapshot.business_plan_snapshot' => ['nullable', 'string', 'max:60000'],
|
'economic_snapshot.business_plan_snapshot' => ['nullable', 'string', 'max:60000'],
|
||||||
'economic_snapshot.financial_tools_snapshot' => ['nullable', 'string', 'max:30000'],
|
'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_team_snapshot' => ['nullable', 'string', 'max:30000'],
|
||||||
'economic_snapshot.project_execution_snapshot' => ['nullable', 'string', 'max:30000'],
|
'economic_snapshot.project_execution_snapshot' => ['nullable', 'string', 'max:30000'],
|
||||||
'economic_snapshot.project_risk_responses_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',
|
'currency', 'funds_origin_countries', 'environmental_category', 'tax_calculation', 'fiscal_scenario_mode', 'offer_or_demand',
|
||||||
'opportunity_type', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration',
|
'opportunity_type', 'confidentiality', 'publish_requested', 'terms_accepted', 'truth_declaration',
|
||||||
'reuse_simulation', 'contact_authorisation', 'publication_authorisation', 'public_fields_confirmation', 'validation_acknowledged',
|
'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'],
|
'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'],
|
'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;
|
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>> */
|
/** @return array<string, list<mixed>> */
|
||||||
public function rules(): array
|
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 [
|
return [
|
||||||
|
'scenario_kind' => ['sometimes', 'in:custom_planning'],
|
||||||
'base' => ['required', 'numeric', 'min:0'],
|
'base' => ['required', 'numeric', 'min:0'],
|
||||||
'rate' => ['required', 'numeric', 'between:0,100'],
|
'rate' => ['required', 'numeric', 'between:0,100'],
|
||||||
'reduction' => ['required', 'numeric', 'between:0,100'],
|
'reduction' => ['required', 'numeric', 'between:0,100'],
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Http\Resources;
|
namespace App\Http\Resources;
|
||||||
|
|
||||||
|
use App\Services\ExistingBusinessClassification;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\Resources\Json\JsonResource;
|
use Illuminate\Http\Resources\Json\JsonResource;
|
||||||
|
|
||||||
@@ -27,7 +28,7 @@ class PublicBusinessOpportunityResource extends JsonResource
|
|||||||
'province' => $this->resource->getAttribute('province'),
|
'province' => $this->resource->getAttribute('province'),
|
||||||
'district' => $this->resource->getAttribute('district'),
|
'district' => $this->resource->getAttribute('district'),
|
||||||
'locality' => $this->resource->getAttribute('locality'),
|
'locality' => $this->resource->getAttribute('locality'),
|
||||||
'multidimensional' => app(\App\Services\ExistingBusinessClassification::class)->publicRows($this->resource),
|
'multidimensional' => app(ExistingBusinessClassification::class)->publicRows($this->resource),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+47
-22
@@ -4,6 +4,7 @@ namespace App\Jobs;
|
|||||||
|
|
||||||
use App\Models\Simulation;
|
use App\Models\Simulation;
|
||||||
use App\Services\SimulationExecution;
|
use App\Services\SimulationExecution;
|
||||||
|
use App\Support\IsolatedQaDatabase;
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
@@ -62,29 +63,39 @@ class RunSimulation implements ShouldQueue
|
|||||||
throw new \RuntimeException('Simulation has no scenario.');
|
throw new \RuntimeException('Simulation has no scenario.');
|
||||||
}
|
}
|
||||||
$input = json_decode($scenario->parameters, true, flags: JSON_THROW_ON_ERROR);
|
$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();
|
$resultId = (string) Str::uuid();
|
||||||
$engineVersion = 'portal-arithmetic-v1+simulation-v'.$simulation->version_no;
|
$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,
|
if (in_array($input['scenario_kind'] ?? null, ['fiscal_rule_qa_preview', 'fiscal_rule_published'], true)) {
|
||||||
'currency' => null, 'legal_interpretation' => false, 'formula_version' => 'portal-arithmetic-v1',
|
if ($input['scenario_kind'] === 'fiscal_rule_qa_preview') {
|
||||||
'contract_version' => 1,
|
abort_unless(IsolatedQaDatabase::allowsSchemaChanges(), 404);
|
||||||
'context' => [
|
}
|
||||||
'reference_date' => substr((string) $scenario->created_at, 0, 10),
|
$result = $input['fiscal_preview'];
|
||||||
'currency' => null,
|
$engineVersion = $result['context']['engine_version'];
|
||||||
'currency_fraction_digits' => null,
|
$result['context']['scenario_id'] = (string) $scenario->id;
|
||||||
'scenario_id' => (string) $scenario->id,
|
$result['context']['scenario_version'] = (int) $scenario->version_no;
|
||||||
'scenario_version' => (int) $scenario->version_no,
|
} else {
|
||||||
'engine_version' => $engineVersion,
|
$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']]);
|
||||||
'ruleset_version' => null,
|
$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',
|
||||||
'result' => [
|
'contract_version' => 1,
|
||||||
'status' => 'calculated',
|
'context' => [
|
||||||
'value' => (string) $row->value,
|
'reference_date' => substr((string) $scenario->created_at, 0, 10),
|
||||||
'unit' => null,
|
'currency' => null,
|
||||||
'explanation' => 'Resultado aritmético determinístico; não constitui cálculo nem conclusão fiscal.',
|
'currency_fraction_digits' => null,
|
||||||
'missing_inputs' => [],
|
'scenario_id' => (string) $scenario->id,
|
||||||
'source_ids' => [],
|
'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);
|
$json = json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
|
||||||
$canonicalResult = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$json])->canonical;
|
$canonicalResult = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$json])->canonical;
|
||||||
$resultHash = hash('sha256', $canonicalResult);
|
$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_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,
|
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()]);
|
'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;
|
$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,
|
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_type' => 'user_input', 'source_id' => $scenario->id, 'source_version' => (string) $scenario->version_no,
|
||||||
'source_snapshot' => $sourceJson, 'source_sha256' => hash('sha256', $canonicalSource), 'created_at' => now()]);
|
'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,
|
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()]);
|
'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);
|
}, 3);
|
||||||
|
|||||||
@@ -2,4 +2,10 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @property string|null $external_id
|
||||||
|
* @property string|null $source_system
|
||||||
|
* @property string $full_name
|
||||||
|
* @property string|null $phone
|
||||||
|
*/
|
||||||
class Contact extends CrmRecord {}
|
class Contact extends CrmRecord {}
|
||||||
|
|||||||
@@ -10,10 +10,16 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
* @property string $validation_status
|
* @property string $validation_status
|
||||||
* @property string $valid_from
|
* @property string $valid_from
|
||||||
* @property string|null $valid_until
|
* @property string|null $valid_until
|
||||||
|
* @property array<string, mixed>|null $fiscal_acceptance
|
||||||
*/
|
*/
|
||||||
class InvestmentLegalSource extends Model
|
class InvestmentLegalSource extends Model
|
||||||
{
|
{
|
||||||
use HasUuids;
|
use HasUuids;
|
||||||
|
|
||||||
protected $guarded = ['id'];
|
protected $guarded = ['id'];
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['fiscal_acceptance' => 'array'];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ class InvestmentZone extends DomainRecord
|
|||||||
{
|
{
|
||||||
protected $hidden = ['editorial_draft', 'operational_details'];
|
protected $hidden = ['editorial_draft', 'operational_details'];
|
||||||
|
|
||||||
protected $casts = ['operational_details' => 'array', 'operational_details' => 'array', 'version_no' => 'integer', 'published_at' => 'datetime', 'aliases' => 'array', 'activities' => 'array', 'resources' => 'array', 'historical_territory' => 'array', 'area_components' => 'array', 'source_evidence' => 'array', 'area_value' => 'decimal:4', 'data_as_of' => 'date', 'sources_consulted_at' => 'date'];
|
protected $casts = ['operational_details' => 'array', 'version_no' => 'integer', 'published_at' => 'datetime', 'aliases' => 'array', 'activities' => 'array', 'resources' => 'array', 'historical_territory' => 'array', 'area_components' => 'array', 'source_evidence' => 'array', 'area_value' => 'decimal:4', 'data_as_of' => 'date', 'sources_consulted_at' => 'date'];
|
||||||
|
|
||||||
/** @return BelongsTo<GeoLocation, $this> */
|
/** @return BelongsTo<GeoLocation, $this> */
|
||||||
public function primaryTerritory(): BelongsTo
|
public function primaryTerritory(): BelongsTo
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
|
use App\Services\OpportunityMaturity;
|
||||||
|
use App\Services\OpportunityPublicText;
|
||||||
|
use App\Services\ProactiveInvestment;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
@@ -31,12 +34,25 @@ class Opportunity extends Model
|
|||||||
|
|
||||||
protected $appends = ['maturity_catalogue_version'];
|
protected $appends = ['maturity_catalogue_version'];
|
||||||
|
|
||||||
|
public function toArray(): array
|
||||||
|
{
|
||||||
|
$data = parent::toArray();
|
||||||
|
if (isset($data['description'])) {
|
||||||
|
$data['description'] = OpportunityPublicText::description($this, $data['description']);
|
||||||
|
}
|
||||||
|
if ($this->exists && ($proactive = app(ProactiveInvestment::class)->publicData($this))) {
|
||||||
|
$data['proactive'] = $proactive;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
|
||||||
public function getMaturityCatalogueVersionAttribute(): ?string
|
public function getMaturityCatalogueVersionAttribute(): ?string
|
||||||
{
|
{
|
||||||
// Only published metadata is public; never expose the current private draft.
|
// Only published metadata is public; never expose the current private draft.
|
||||||
$version = data_get($this->workflow_context, 'publication.maturity.catalogue_version');
|
$version = data_get($this->workflow_context, 'publication.maturity.catalogue_version');
|
||||||
|
|
||||||
return in_array($version, [\App\Services\OpportunityMaturity::VERSION, \App\Services\OpportunityMaturity::LEGACY], true)
|
return in_array($version, [OpportunityMaturity::VERSION, OpportunityMaturity::LEGACY], true)
|
||||||
? $version : null;
|
? $version : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +84,8 @@ class Opportunity extends Model
|
|||||||
$scope = $public ? 'public' : ($visible && $this->owner_user_id !== null ? 'restricted' : 'unpublished');
|
$scope = $public ? 'public' : ($visible && $this->owner_user_id !== null ? 'restricted' : 'unpublished');
|
||||||
|
|
||||||
return ['scope' => $scope, 'public_catalog' => $public, 'label' => match ($scope) {
|
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',
|
'restricted' => 'Disponibilizada com acesso restrito — perfis e organização autorizados',
|
||||||
default => 'Sem versão disponibilizada; aprovação interna é uma etapa distinta',
|
default => 'Sem versão disponibilizada; aprovação interna é uma etapa distinta',
|
||||||
}];
|
}];
|
||||||
|
|||||||
+15
-4
@@ -2,10 +2,15 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @property list<array<string, mixed>> $specializations
|
||||||
|
* @property string $url
|
||||||
|
*/
|
||||||
class Sector extends Model
|
class Sector extends Model
|
||||||
{
|
{
|
||||||
use SoftDeletes;
|
use SoftDeletes;
|
||||||
@@ -20,18 +25,24 @@ class Sector extends Model
|
|||||||
'published_at' => 'datetime',
|
'published_at' => 'datetime',
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Presentation only: historical masters and foreign keys remain untouched. */
|
/** Presentation only: historical masters and foreign keys remain untouched.
|
||||||
public function scopeChoices($query)
|
* @param Builder<Sector> $query
|
||||||
|
* @return Builder<Sector>
|
||||||
|
*/
|
||||||
|
public function scopeChoices(Builder $query): Builder
|
||||||
{
|
{
|
||||||
return $query->where('is_active', true)->where('slug', '!=', 'energia');
|
return $query->where('is_active', true)->where('slug', '!=', 'energia');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function scopeCatalog($query)
|
/** @param Builder<Sector> $query
|
||||||
|
* @return Builder<Sector>
|
||||||
|
*/
|
||||||
|
public function scopeCatalog(Builder $query): Builder
|
||||||
{
|
{
|
||||||
return $query->choices()->whereNotNull('published_at')->where('slug', '!=', 'fintech');
|
return $query->choices()->whereNotNull('published_at')->where('slug', '!=', 'fintech');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getNameAttribute($value)
|
public function getNameAttribute(?string $value): ?string
|
||||||
{
|
{
|
||||||
return ($this->attributes['slug'] ?? null) === 'fintech' ? 'Mercado Financeiro — Fintech' : $value;
|
return ($this->attributes['slug'] ?? null) === 'fintech' ? 'Mercado Financeiro — Fintech' : $value;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ use Illuminate\Support\Carbon;
|
|||||||
* @property string $component
|
* @property string $component
|
||||||
* @property string $scope_key
|
* @property string $scope_key
|
||||||
* @property string $status
|
* @property string $status
|
||||||
|
* @property array<string, mixed> $rule_definition
|
||||||
|
* @property array<string, mixed> $parameters
|
||||||
|
* @property array<string, mixed> $rounding_policy
|
||||||
* @property int $author_id
|
* @property int $author_id
|
||||||
* @property int|null $reviewer_id
|
* @property int|null $reviewer_id
|
||||||
* @property int|null $approver_id
|
* @property int|null $approver_id
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ namespace App\Policies;
|
|||||||
|
|
||||||
use App\Models\ExistingBusiness;
|
use App\Models\ExistingBusiness;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\ExistingBusinessProfileCategory;
|
||||||
use App\Services\PortalProfileAccess;
|
use App\Services\PortalProfileAccess;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -87,11 +88,13 @@ class ExistingBusinessPolicy
|
|||||||
return $this->designatedAny($user);
|
return $this->designatedAny($user);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Filter before projecting or decrypting private fields in the review queue. */
|
/** Filter before projecting or decrypting private fields in the review queue.
|
||||||
|
* @param Builder<ExistingBusiness> $query
|
||||||
|
*/
|
||||||
public function scopeReviewQueue(Builder $query, User $user): void
|
public function scopeReviewQueue(Builder $query, User $user): void
|
||||||
{
|
{
|
||||||
if (app(PortalProfileAccess::class)->available()) {
|
if (app(PortalProfileAccess::class)->available()) {
|
||||||
$query->whereIn('modality',array_keys(\App\Services\ExistingBusinessProfileCategory::MAP));
|
$query->whereIn('modality', array_keys(ExistingBusinessProfileCategory::MAP));
|
||||||
$ids = (clone $query)->get()->filter(fn (ExistingBusiness $business) => $this->view($user, $business))->modelKeys();
|
$ids = (clone $query)->get()->filter(fn (ExistingBusiness $business) => $this->view($user, $business))->modelKeys();
|
||||||
$query->whereKey($ids);
|
$query->whereKey($ids);
|
||||||
}
|
}
|
||||||
@@ -119,13 +122,18 @@ class ExistingBusinessPolicy
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
$access = app(PortalProfileAccess::class);
|
$access = app(PortalProfileAccess::class);
|
||||||
if ($access->has($user, 'auditor')) { return false; }
|
if ($access->has($user, 'auditor')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
if (! $access->available()) {
|
if (! $access->available()) {
|
||||||
return $access->legacyWriteAllowed($user) && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
return $access->legacyWriteAllowed($user) && (bool) $user->two_factor_confirmed_at && (bool) $user->two_factor_secret
|
||||||
&& in_array(strtolower($user->email), config('existing-business.reviewers', []), true);
|
&& in_array(strtolower($user->email), config('existing-business.reviewers', []), true);
|
||||||
}
|
}
|
||||||
if ($business->modality !== 'company_sale') { return false; }
|
if ($business->modality !== 'company_sale') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
$responsibility = $dimension === 'regulation' ? 'legal_reviewer' : 'technical_reviewer';
|
$responsibility = $dimension === 'regulation' ? 'legal_reviewer' : 'technical_reviewer';
|
||||||
|
|
||||||
return collect($access->grants($user, 'validator'))->contains(fn ($g) => $g->organization_id === null
|
return collect($access->grants($user, 'validator'))->contains(fn ($g) => $g->organization_id === null
|
||||||
&& in_array('business_sale', json_decode($g->opportunity_types, true), true)
|
&& in_array('business_sale', json_decode($g->opportunity_types, true), true)
|
||||||
&& in_array($responsibility, json_decode($g->responsibilities, true), true));
|
&& in_array($responsibility, json_decode($g->responsibilities, true), true));
|
||||||
@@ -137,6 +145,7 @@ class ExistingBusinessPolicy
|
|||||||
|| app(PortalProfileAccess::class)->has($user, 'auditor') || ! $this->designated($user, 'publishers', $business)) {
|
|| app(PortalProfileAccess::class)->has($user, 'auditor') || ! $this->designated($user, 'publishers', $business)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return ! DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
return ! DB::table('business_workflow_transitions')->where('existing_business_id', $business->id)
|
||||||
->whereIn('to_status', ['approval_l2', 'approved'])->where('actor_id', $user->id)->exists();
|
->whereIn('to_status', ['approval_l2', 'approved'])->where('actor_id', $user->id)->exists();
|
||||||
}
|
}
|
||||||
@@ -156,8 +165,8 @@ class ExistingBusinessPolicy
|
|||||||
{
|
{
|
||||||
$access = app(PortalProfileAccess::class);
|
$access = app(PortalProfileAccess::class);
|
||||||
if ($access->available()) {
|
if ($access->available()) {
|
||||||
$category=$business ? \App\Services\ExistingBusinessProfileCategory::category($business) : null;
|
$category = $business ? ExistingBusinessProfileCategory::category($business) : null;
|
||||||
if (($business !== null && $category === null) || ! $access->mfa($user) || $access->has($user,'auditor')) {
|
if (($business !== null && $category === null) || ! $access->mfa($user) || $access->has($user, 'auditor')) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
$role = $designation === 'publishers' ? 'publisher' : 'validator';
|
$role = $designation === 'publishers' ? 'publisher' : 'validator';
|
||||||
@@ -168,7 +177,7 @@ class ExistingBusinessPolicy
|
|||||||
$organizationMatches = $grant->organization_id === null
|
$organizationMatches = $grant->organization_id === null
|
||||||
|| ($business !== null && $grant->organization_id === $business->organization_id);
|
|| ($business !== null && $grant->organization_id === $business->organization_id);
|
||||||
if ($organizationMatches
|
if ($organizationMatches
|
||||||
&& ($category !== null ? in_array($category,json_decode($grant->opportunity_types,true,512,JSON_THROW_ON_ERROR),true) : array_intersect(array_values(\App\Services\ExistingBusinessProfileCategory::MAP),json_decode($grant->opportunity_types,true,512,JSON_THROW_ON_ERROR)) !== [])) {
|
&& ($category !== null ? in_array($category, json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR), true) : array_intersect(array_values(ExistingBusinessProfileCategory::MAP), json_decode($grant->opportunity_types, true, 512, JSON_THROW_ON_ERROR)) !== [])) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ use Illuminate\Support\Facades\Gate;
|
|||||||
use Illuminate\Support\Facades\RateLimiter;
|
use Illuminate\Support\Facades\RateLimiter;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Illuminate\Validation\Rules\Password;
|
use Illuminate\Validation\Rules\Password;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Laravel\Fortify\Contracts\LogoutResponse;
|
||||||
use Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided;
|
use Laravel\Fortify\Events\ValidTwoFactorAuthenticationCodeProvided;
|
||||||
|
|
||||||
class AppServiceProvider extends ServiceProvider
|
class AppServiceProvider extends ServiceProvider
|
||||||
@@ -45,12 +47,12 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
|
|
||||||
// Fortify calls this response AFTER invalidating/regenerating the server session.
|
// Fortify calls this response AFTER invalidating/regenerating the server session.
|
||||||
// Clear the client's encryption key too, so Back must reauthorize private pages.
|
// Clear the client's encryption key too, so Back must reauthorize private pages.
|
||||||
$this->app->bind(\Laravel\Fortify\Contracts\LogoutResponse::class, function () {
|
$this->app->bind(LogoutResponse::class, function () {
|
||||||
return new class extends \Laravel\Fortify\Http\Responses\LogoutResponse
|
return new class extends \Laravel\Fortify\Http\Responses\LogoutResponse
|
||||||
{
|
{
|
||||||
public function toResponse($request)
|
public function toResponse($request)
|
||||||
{
|
{
|
||||||
\Inertia\Inertia::clearHistory();
|
Inertia::clearHistory();
|
||||||
|
|
||||||
return parent::toResponse($request);
|
return parent::toResponse($request);
|
||||||
}
|
}
|
||||||
@@ -77,6 +79,8 @@ class AppServiceProvider extends ServiceProvider
|
|||||||
Cache::forget('portal_home_en');
|
Cache::forget('portal_home_en');
|
||||||
Cache::forget('portal_home_v2_pt');
|
Cache::forget('portal_home_v2_pt');
|
||||||
Cache::forget('portal_home_v2_en');
|
Cache::forget('portal_home_v2_en');
|
||||||
|
Cache::forget('portal_home_sector_organization_v1_pt');
|
||||||
|
Cache::forget('portal_home_sector_organization_v1_en');
|
||||||
};
|
};
|
||||||
$model::saved($invalidate);
|
$model::saved($invalidate);
|
||||||
$model::deleted($invalidate);
|
$model::deleted($invalidate);
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ class InvestorGuidance
|
|||||||
return Schema::hasColumn('tasks', 'desk_case_id');
|
return Schema::hasColumn('tasks', 'desk_case_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Reads each linked module with its own owner rule; case membership does not grant access to a private simulator. */
|
/** Reads each linked module with its own owner rule; case membership does not grant access to a private simulator.
|
||||||
/** @return array<string,mixed> */
|
* @return array<string,mixed> */
|
||||||
public function context(User $actor, \stdClass $case): array
|
public function context(User $actor, \stdClass $case): array
|
||||||
{
|
{
|
||||||
$base = $this->desk->decode($case->payload);
|
$base = $this->desk->decode($case->payload);
|
||||||
|
|||||||
@@ -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];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -103,7 +103,9 @@ final class BusinessFormSchema
|
|||||||
// The field limit is a text length, not an 8% ceiling.
|
// The field limit is a text length, not an 8% ceiling.
|
||||||
$rules['payload.equity_percentage'] = ['nullable', 'numeric', 'between:0,100',
|
$rules['payload.equity_percentage'] = ['nullable', 'numeric', 'between:0,100',
|
||||||
function ($attribute, $value, $fail) {
|
function ($attribute, $value, $fail) {
|
||||||
if (strlen((string) $value) > 8) $fail('Indique a percentagem com até 8 caracteres.');
|
if (strlen((string) $value) > 8) {
|
||||||
|
$fail('Indique a percentagem com até 8 caracteres.');
|
||||||
|
}
|
||||||
}];
|
}];
|
||||||
foreach (['valid_until', 'mandate_valid_until'] as $date) {
|
foreach (['valid_until', 'mandate_valid_until'] as $date) {
|
||||||
$rules['payload.'.$date][] = 'date_format:Y-m-d';
|
$rules['payload.'.$date][] = 'date_format:Y-m-d';
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
<?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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
private function decode(?\stdClass $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];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function current(string $cluster): array
|
||||||
|
{
|
||||||
|
return $this->decode($this->events($cluster)->orderByRaw("(after_data->>'version')::integer DESC")->first());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $draft
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed>|null $draft
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
* @param array<array-key, mixed> $input
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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 !== null, 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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>|null
|
||||||
|
*/
|
||||||
|
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,64 @@
|
|||||||
|
<?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
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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,87 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Support\CheckedFile;
|
||||||
|
use DOMDocument;
|
||||||
|
use DOMElement;
|
||||||
|
|
||||||
|
/** Supplement the six named agribusiness sections without changing corridor masters or source documents. */
|
||||||
|
final class CorridorAgribusiness
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $links
|
||||||
|
*/
|
||||||
|
public function enrich(string $html, array $links = []): string
|
||||||
|
{
|
||||||
|
$data = json_decode(CheckedFile::read(__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,130 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\InvestmentDossier;
|
||||||
|
use App\Models\Opportunity;
|
||||||
|
use App\Models\Sector;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Support\CheckedFile;
|
||||||
|
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.
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function portfolioOpportunityIds(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.';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function entries(): array
|
||||||
|
{
|
||||||
|
$data = json_decode(CheckedFile::read(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function articleLinks(): array
|
||||||
|
{
|
||||||
|
// Reading an original article must work before the optional sector/opportunity catalogue is loaded.
|
||||||
|
if (! Sector::where('slug', 'agronegocio')->where('is_active', true)->exists()) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,8 +15,8 @@ final class DeclaredOriginStatistics
|
|||||||
abort_unless(app(ScopedPortalAdministration::class)->interestOperator($actor), 403);
|
abort_unless(app(ScopedPortalAdministration::class)->interestOperator($actor), 403);
|
||||||
$names = array_column(app(CountryCatalogue::class)->all(), 'name', 'code');
|
$names = array_column(app(CountryCatalogue::class)->all(), 'name', 'code');
|
||||||
$groups = [];
|
$groups = [];
|
||||||
$interests=DB::table('interest_requests')->whereNull('deleted_at');
|
$interests = DB::table('interest_requests')->whereNull('deleted_at');
|
||||||
app(ScopedPortalAdministration::class)->interestQuery($interests,$actor);
|
app(ScopedPortalAdministration::class)->interestQuery($interests, $actor);
|
||||||
foreach ($interests->select('metadata')->cursor() as $row) {
|
foreach ($interests->select('metadata')->cursor() as $row) {
|
||||||
$metadata = json_decode($row->metadata ?? '{}', true);
|
$metadata = json_decode($row->metadata ?? '{}', true);
|
||||||
$code = $metadata['declared_origin_country_code'] ?? null;
|
$code = $metadata['declared_origin_country_code'] ?? null;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Services;
|
namespace App\Services;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Support\CheckedFile;
|
||||||
use Illuminate\Database\Query\Builder;
|
use Illuminate\Database\Query\Builder;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Gate;
|
use Illuminate\Support\Facades\Gate;
|
||||||
@@ -26,8 +27,9 @@ class DocumentManagementAccess
|
|||||||
/** Restore the approved editorial operation without a global management grant. */
|
/** Restore the approved editorial operation without a global management grant. */
|
||||||
public function editorial(User $actor): bool
|
public function editorial(User $actor): bool
|
||||||
{
|
{
|
||||||
return config('portal.homologation_only', false)
|
// Tempo's named editorial designation does not depend on whether the
|
||||||
&& in_array(strtolower(trim($actor->email)), config('homologation_editorial.accounts', []), true)
|
// 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)->superuser($actor)
|
||||||
&& ! app(PortalProfileAccess::class)->has($actor, 'auditor')
|
&& ! app(PortalProfileAccess::class)->has($actor, 'auditor')
|
||||||
&& app(PortalProfileAccess::class)->mfa($actor);
|
&& app(PortalProfileAccess::class)->mfa($actor);
|
||||||
@@ -36,6 +38,7 @@ class DocumentManagementAccess
|
|||||||
public function editorialResources(User $actor): Builder
|
public function editorialResources(User $actor): Builder
|
||||||
{
|
{
|
||||||
abort_unless($this->editorial($actor), 403);
|
abort_unless($this->editorial($actor), 403);
|
||||||
|
|
||||||
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
return DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
|
||||||
->whereNull('d.deleted_at')->where('d.status', '!=', 'deleted')
|
->whereNull('d.deleted_at')->where('d.status', '!=', 'deleted')
|
||||||
->where(function ($query) use ($actor) {
|
->where(function ($query) use ($actor) {
|
||||||
@@ -49,6 +52,11 @@ class DocumentManagementAccess
|
|||||||
->where('d.external_id', $item['external_id']);
|
->where('d.external_id', $item['external_id']);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
foreach (json_decode(CheckedFile::read(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']);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,6 +82,9 @@ class DocumentManagementAccess
|
|||||||
return $query;
|
return $query;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $data
|
||||||
|
*/
|
||||||
public function audit(User $actor, string $action, array $data): void
|
public function audit(User $actor, string $action, array $data): void
|
||||||
{
|
{
|
||||||
DB::table('audit_events')->insert([
|
DB::table('audit_events')->insert([
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Services;
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Support\CheckedFile;
|
||||||
use Illuminate\Database\Query\Builder;
|
use Illuminate\Database\Query\Builder;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -11,14 +12,19 @@ use Illuminate\Support\Facades\Schema;
|
|||||||
class EconomicReferenceCatalog
|
class EconomicReferenceCatalog
|
||||||
{
|
{
|
||||||
public const LOT = 'lot-01';
|
public const LOT = 'lot-01';
|
||||||
|
|
||||||
public const SOURCE = 'economic-reference-lot-01';
|
public const SOURCE = 'economic-reference-lot-01';
|
||||||
|
|
||||||
public const MANIFEST_SHA256 = 'ba1bb3406fd55e39c19fd2a2755f3dfc2a1160b67eee8b3b6e12cd43f4223b04';
|
public const MANIFEST_SHA256 = 'ba1bb3406fd55e39c19fd2a2755f3dfc2a1160b67eee8b3b6e12cd43f4223b04';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function manifest(): array
|
public function manifest(): array
|
||||||
{
|
{
|
||||||
$file = database_path('data/economic-references-lot-01.json');
|
$file = database_path('data/economic-references-lot-01.json');
|
||||||
abort_unless(is_file($file) && hash_equals(self::MANIFEST_SHA256, hash_file('sha256', $file)), 422, 'Manifesto económico ausente ou diferente da revisão delimitada.');
|
abort_unless(is_file($file) && hash_equals(self::MANIFEST_SHA256, CheckedFile::sha256($file)), 422, 'Manifesto económico ausente ou diferente da revisão delimitada.');
|
||||||
$manifest = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
$manifest = json_decode(CheckedFile::read($file), true, 512, JSON_THROW_ON_ERROR);
|
||||||
abort_unless(($manifest['lot'] ?? '') === self::LOT && count($manifest['activities'] ?? []) === 5
|
abort_unless(($manifest['lot'] ?? '') === self::LOT && count($manifest['activities'] ?? []) === 5
|
||||||
&& count($manifest['chains'] ?? []) === 5 && count($manifest['links'] ?? []) === 4, 422, 'Lote económico fora do âmbito.');
|
&& count($manifest['chains'] ?? []) === 5 && count($manifest['links'] ?? []) === 4, 422, 'Lote económico fora do âmbito.');
|
||||||
|
|
||||||
@@ -40,7 +46,9 @@ class EconomicReferenceCatalog
|
|||||||
|
|
||||||
public function available(): bool
|
public function available(): bool
|
||||||
{
|
{
|
||||||
if (! $this->schemaAvailable() || $this->publicationState() !== 'published') { return false; }
|
if (! $this->schemaAvailable() || $this->publicationState() !== 'published') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return DB::table('reference_catalog_versions')->where('id', $this->manifest()['catalog']['id'])->where('status', 'published')->exists();
|
return DB::table('reference_catalog_versions')->where('id', $this->manifest()['catalog']['id'])->where('status', 'published')->exists();
|
||||||
}
|
}
|
||||||
@@ -48,7 +56,9 @@ class EconomicReferenceCatalog
|
|||||||
public function constrain(Builder $query, string $kind): Builder
|
public function constrain(Builder $query, string $kind): Builder
|
||||||
{
|
{
|
||||||
$manifest = $this->manifest();
|
$manifest = $this->manifest();
|
||||||
if ($kind === 'activity') $query->where('id', '!=', SectorOrganization::LEGACY_ACTIVITY_ID);
|
if ($kind === 'activity') {
|
||||||
|
$query->where('id', '!=', SectorOrganization::LEGACY_ACTIVITY_ID);
|
||||||
|
}
|
||||||
if (in_array($kind, ['activity', 'chain'], true) && ! $this->available()) {
|
if (in_array($kind, ['activity', 'chain'], true) && ! $this->available()) {
|
||||||
$query->whereNotIn('id', array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'));
|
$query->whereNotIn('id', array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'));
|
||||||
}
|
}
|
||||||
@@ -59,17 +69,29 @@ class EconomicReferenceCatalog
|
|||||||
/** A withdrawn published reference can be retained verbatim, never introduced as a new choice. */
|
/** A withdrawn published reference can be retained verbatim, never introduced as a new choice. */
|
||||||
public function historicalTarget(string $kind, string $id): bool
|
public function historicalTarget(string $kind, string $id): bool
|
||||||
{
|
{
|
||||||
if ($kind === 'activity' && $id === SectorOrganization::LEGACY_ACTIVITY_ID) return DB::table('economic_activities')->where('id', $id)->where('sector_id', 2)->where('status', 'published')->exists();
|
if ($kind === 'activity' && $id === SectorOrganization::LEGACY_ACTIVITY_ID) {
|
||||||
if (! in_array($kind, ['activity', 'chain'], true) || ! $this->schemaAvailable()) { return false; }
|
return DB::table('economic_activities')->where('id', $id)->where('sector_id', 2)->where('status', 'published')->exists();
|
||||||
|
}
|
||||||
|
if (! in_array($kind, ['activity', 'chain'], true) || ! $this->schemaAvailable()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
$manifest = $this->manifest();
|
$manifest = $this->manifest();
|
||||||
if (! in_array($id, array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'), true)) { return false; }
|
if (! in_array($id, array_column($manifest[$kind === 'activity' ? 'activities' : 'chains'], 'id'), true)) {
|
||||||
if (! DB::table('audit_events')->where('source_system', self::SOURCE)->where('action', 'publish')->exists()) { return false; }
|
return false;
|
||||||
|
}
|
||||||
|
if (! DB::table('audit_events')->where('source_system', self::SOURCE)->where('action', 'publish')->exists()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return $kind === 'activity'
|
return $kind === 'activity'
|
||||||
? DB::table('economic_activities')->where('id', $id)->where('status', 'published')->exists()
|
? DB::table('economic_activities')->where('id', $id)->where('status', 'published')->exists()
|
||||||
: DB::table('value_chains')->where('id', $id)->whereNull('deleted_at')->exists();
|
: DB::table('value_chains')->where('id', $id)->whereNull('deleted_at')->exists();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $historicalIds
|
||||||
|
* @return Collection<int, \stdClass>
|
||||||
|
*/
|
||||||
public function activities(array $historicalIds = []): Collection
|
public function activities(array $historicalIds = []): Collection
|
||||||
{
|
{
|
||||||
$rows = DB::table('economic_activities')->where('status', 'published')->get();
|
$rows = DB::table('economic_activities')->where('status', 'published')->get();
|
||||||
@@ -79,14 +101,19 @@ class EconomicReferenceCatalog
|
|||||||
foreach ($historicalIds as $id) {
|
foreach ($historicalIds as $id) {
|
||||||
$seen = [];
|
$seen = [];
|
||||||
while (isset($byId[$id]) && ! isset($seen[$id])) {
|
while (isset($byId[$id]) && ! isset($seen[$id])) {
|
||||||
$allowed[] = $id; $seen[$id] = true; $id = $byId[$id]->parent_id;
|
$allowed[] = $id;
|
||||||
|
$seen[$id] = true;
|
||||||
|
$id = $byId[$id]->parent_id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$available = $this->available();
|
$available = $this->available();
|
||||||
return $rows->filter(fn ($r) => in_array($r->id, $allowed, true))->map(function ($row) use ($byId, $available) {
|
|
||||||
|
return $rows->filter(fn ($r) => in_array($r->id, $allowed, true))->map(function ($row) use ($byId, $available): \stdClass {
|
||||||
$meta = property_exists($row, 'metadata') ? json_decode($row->metadata, true) : [];
|
$meta = property_exists($row, 'metadata') ? json_decode($row->metadata, true) : [];
|
||||||
$path = []; $current = $row; $seen = [];
|
$path = [];
|
||||||
|
$current = $row;
|
||||||
|
$seen = [];
|
||||||
while ($current && ! isset($seen[$current->id])) {
|
while ($current && ! isset($seen[$current->id])) {
|
||||||
$seen[$current->id] = true;
|
$seen[$current->id] = true;
|
||||||
array_unshift($path, ['id' => $current->id, 'code' => $current->code, 'label' => $current->label_pt_mz]);
|
array_unshift($path, ['id' => $current->id, 'code' => $current->code, 'label' => $current->label_pt_mz]);
|
||||||
@@ -94,21 +121,31 @@ class EconomicReferenceCatalog
|
|||||||
}
|
}
|
||||||
$isLot = ($meta['lot'] ?? '') === self::LOT;
|
$isLot = ($meta['lot'] ?? '') === self::LOT;
|
||||||
|
|
||||||
return (object) ['id' => $row->id, 'parent_id' => $row->parent_id, 'sector_id' => $row->sector_id,
|
$option = ['id' => $row->id, 'parent_id' => $row->parent_id, 'sector_id' => $row->sector_id,
|
||||||
'label_pt_mz' => $row->label_pt_mz, 'catalog_version_id' => $row->catalog_version_id, 'code' => $row->code,
|
'label_pt_mz' => $row->label_pt_mz, 'catalog_version_id' => $row->catalog_version_id, 'code' => $row->code,
|
||||||
'level' => $meta['level'] ?? null, 'path' => $path, 'display_label' => implode(' → ', array_column($path, 'code')).' — '.$row->label_pt_mz,
|
'level' => $meta['level'] ?? null, 'path' => $path, 'display_label' => implode(' → ', array_column($path, 'code')).' — '.$row->label_pt_mz,
|
||||||
'source_version' => $meta['source_version'] ?? null, 'edition' => $meta['edition'] ?? null,
|
'source_version' => $meta['source_version'] ?? null, 'edition' => $meta['edition'] ?? null,
|
||||||
'historical_only' => $isLot && ! $available];
|
'historical_only' => $isLot && ! $available];
|
||||||
|
$result = new \stdClass;
|
||||||
|
foreach ($option as $key => $value) {
|
||||||
|
$result->{$key} = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $result;
|
||||||
})->values();
|
})->values();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function validHierarchy(int $sectorId, ?string $subsectorId, ?string $activityId, bool $historical = false): bool
|
public function validHierarchy(int $sectorId, ?string $subsectorId, ?string $activityId, bool $historical = false): bool
|
||||||
{
|
{
|
||||||
if (! $subsectorId || ! $activityId) { return false; }
|
if (! $subsectorId || ! $activityId) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
$sector = DB::table('sectors')->where('id', $sectorId)->whereNull('deleted_at')->where('is_active', true)->exists();
|
$sector = DB::table('sectors')->where('id', $sectorId)->whereNull('deleted_at')->where('is_active', true)->exists();
|
||||||
$subsector = DB::table('economic_activities')->where('id', $subsectorId)->where('status', 'published')->first();
|
$subsector = DB::table('economic_activities')->where('id', $subsectorId)->where('status', 'published')->first();
|
||||||
$activity = DB::table('economic_activities')->where('id', $activityId)->where('status', 'published')->first();
|
$activity = DB::table('economic_activities')->where('id', $activityId)->where('status', 'published')->first();
|
||||||
if (! $sector || ! $subsector || ! $activity || $activity->catalog_version_id !== $subsector->catalog_version_id) { return false; }
|
if (! $sector || ! $subsector || ! $activity || $activity->catalog_version_id !== $subsector->catalog_version_id) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
$manifest = $this->manifest();
|
$manifest = $this->manifest();
|
||||||
if ($activity->catalog_version_id !== $manifest['catalog']['id']) {
|
if ($activity->catalog_version_id !== $manifest['catalog']['id']) {
|
||||||
$root = $subsector->parent_id ? DB::table('economic_activities')->where('id', $subsector->parent_id)->where('status', 'published')->first() : null;
|
$root = $subsector->parent_id ? DB::table('economic_activities')->where('id', $subsector->parent_id)->where('status', 'published')->first() : null;
|
||||||
@@ -116,10 +153,15 @@ class EconomicReferenceCatalog
|
|||||||
return $root && (int) $root->sector_id === $sectorId && $activity->parent_id === $subsector->id;
|
return $root && (int) $root->sector_id === $sectorId && $activity->parent_id === $subsector->id;
|
||||||
}
|
}
|
||||||
if ((! $this->available() && ! $historical) || $sectorId !== (int) $manifest['existing']['sector']['id']
|
if ((! $this->available() && ! $historical) || $sectorId !== (int) $manifest['existing']['sector']['id']
|
||||||
|| $subsector->code !== '01' || $activity->code !== '01120') { return false; }
|
|| $subsector->code !== '01' || $activity->code !== '01120') {
|
||||||
$current = $activity; $codes = []; $seen = [];
|
return false;
|
||||||
|
}
|
||||||
|
$current = $activity;
|
||||||
|
$codes = [];
|
||||||
|
$seen = [];
|
||||||
while ($current && ! isset($seen[$current->id])) {
|
while ($current && ! isset($seen[$current->id])) {
|
||||||
$seen[$current->id] = true; array_unshift($codes, $current->code);
|
$seen[$current->id] = true;
|
||||||
|
array_unshift($codes, $current->code);
|
||||||
$current = $current->parent_id ? DB::table('economic_activities')->where('id', $current->parent_id)->where('catalog_version_id', $activity->catalog_version_id)->where('status', 'published')->first() : null;
|
$current = $current->parent_id ? DB::table('economic_activities')->where('id', $current->parent_id)->where('catalog_version_id', $activity->catalog_version_id)->where('status', 'published')->first() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,19 +4,22 @@ namespace App\Services;
|
|||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\Malware\MalwareScanner;
|
use App\Services\Malware\MalwareScanner;
|
||||||
|
use App\Support\CheckedFile;
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
use Illuminate\Support\Str;
|
|
||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
/** Bounded authenticated extension. No generic seeding, arbitrary path or caller-supplied actor. */
|
/** Bounded authenticated extension. No generic seeding, arbitrary path or caller-supplied actor. */
|
||||||
class EconomicReferenceInstallation
|
class EconomicReferenceInstallation
|
||||||
{
|
{
|
||||||
public const MIGRATION = '2026_10_16_120000_extend_economic_reference_hierarchy';
|
public const MIGRATION = '2026_10_16_120000_extend_economic_reference_hierarchy';
|
||||||
|
|
||||||
public const OPERATIONS = ['schema', 'import', 'publish', 'withdraw'];
|
public const OPERATIONS = ['schema', 'import', 'publish', 'withdraw'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function files(): array
|
public function files(): array
|
||||||
{
|
{
|
||||||
return ['app/Services/EconomicReferenceCatalog.php', 'app/Services/EconomicReferenceInstallation.php',
|
return ['app/Services/EconomicReferenceCatalog.php', 'app/Services/EconomicReferenceInstallation.php',
|
||||||
@@ -32,13 +35,22 @@ class EconomicReferenceInstallation
|
|||||||
return hash('sha256', json_encode(array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files()), JSON_THROW_ON_ERROR));
|
return hash('sha256', json_encode(array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files()), JSON_THROW_ON_ERROR));
|
||||||
}
|
}
|
||||||
|
|
||||||
private function directory(): string { return storage_path('app/private/investmoz-v2/economic-references/lot-01'); }
|
private function directory(): string
|
||||||
|
{
|
||||||
|
return storage_path('app/private/investmoz-v2/economic-references/lot-01');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function target(): array
|
private function target(): array
|
||||||
{
|
{
|
||||||
return (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
return (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $target
|
||||||
|
*/
|
||||||
private function qa(array $target): bool
|
private function qa(array $target): bool
|
||||||
{
|
{
|
||||||
return app()->environment('testing') && str_ends_with($target['database'], '_test') && (int) $target['port'] === 55441
|
return app()->environment('testing') && str_ends_with($target['database'], '_test') && (int) $target['port'] === 55441
|
||||||
@@ -48,20 +60,32 @@ class EconomicReferenceInstallation
|
|||||||
private function authorize(User $actor, bool $write = false, string $operation = ''): void
|
private function authorize(User $actor, bool $write = false, string $operation = ''): void
|
||||||
{
|
{
|
||||||
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor), 403, 'Acesso reservado à gestão autorizada.');
|
abort_unless($actor->hasVerifiedEmail() && app(ScopedPortalAdministration::class)->administrative($actor), 403, 'Acesso reservado à gestão autorizada.');
|
||||||
if (! $write) { return; }
|
if (! $write) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
$access = app(PortalProfileAccess::class);
|
$access = app(PortalProfileAccess::class);
|
||||||
abort_if($access->has($actor, 'auditor'), 403, 'A restrição de Auditor permite apenas consulta.');
|
abort_if($access->has($actor, 'auditor'), 403, 'A restrição de Auditor permite apenas consulta.');
|
||||||
abort_unless($access->mfa($actor), 403, 'Conclua MFA nesta sessão para executar esta ação.');
|
abort_unless($access->mfa($actor), 403, 'Conclua MFA nesta sessão para executar esta ação.');
|
||||||
if ($operation === 'schema') { app(PortalProfileInstallation::class)->authorize($actor, true); }
|
if ($operation === 'schema') {
|
||||||
|
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||||
|
}
|
||||||
abort_unless(! app()->environment('testing') || $this->qa($this->target()), 403, 'Alvo QA isolado inválido.');
|
abort_unless(! app()->environment('testing') || $this->qa($this->target()), 403, 'Alvo QA isolado inválido.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $target
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function evidence(array $target, string $code, string $operation): array
|
private function evidence(array $target, string $code, string $operation): array
|
||||||
{
|
{
|
||||||
if ($this->qa($target)) { return ['ready' => true, 'mode' => 'isolated_QA', 'date' => null]; }
|
if ($this->qa($target)) {
|
||||||
if (app()->environment('testing')) { return ['ready' => false, 'mode' => 'invalid_QA', 'date' => null]; }
|
return ['ready' => true, 'mode' => 'isolated_QA', 'date' => null];
|
||||||
|
}
|
||||||
|
if (app()->environment('testing')) {
|
||||||
|
return ['ready' => false, 'mode' => 'invalid_QA', 'date' => null];
|
||||||
|
}
|
||||||
$path = $this->directory().'/readiness.json';
|
$path = $this->directory().'/readiness.json';
|
||||||
$proof = is_file($path) ? json_decode(file_get_contents($path), true) : [];
|
$proof = is_file($path) ? json_decode(CheckedFile::read($path), true) : [];
|
||||||
$date = strtotime($proof['verified_at'] ?? '');
|
$date = strtotime($proof['verified_at'] ?? '');
|
||||||
$permission = $proof['active_authorization'] ?? [];
|
$permission = $proof['active_authorization'] ?? [];
|
||||||
$ready = ! config('database.connections.pgsql.url') && in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
|
$ready = ! config('database.connections.pgsql.url') && in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
|
||||||
@@ -73,8 +97,8 @@ class EconomicReferenceInstallation
|
|||||||
&& ($proof['qa_passed'] ?? false) && ($proof['compatibility_verified'] ?? false)
|
&& ($proof['qa_passed'] ?? false) && ($proof['compatibility_verified'] ?? false)
|
||||||
&& str_ends_with($proof['restore_target']['database'] ?? '', '_test') && (int) ($proof['restore_target']['port'] ?? 0) === 55441
|
&& str_ends_with($proof['restore_target']['database'] ?? '', '_test') && (int) ($proof['restore_target']['port'] ?? 0) === 55441
|
||||||
&& is_file($proof['dump_path'] ?? '') && is_file($proof['files_path'] ?? '')
|
&& is_file($proof['dump_path'] ?? '') && is_file($proof['files_path'] ?? '')
|
||||||
&& hash_equals($proof['dump_sha256'] ?? '', hash_file('sha256', $proof['dump_path']))
|
&& hash_equals($proof['dump_sha256'] ?? '', CheckedFile::sha256($proof['dump_path']))
|
||||||
&& hash_equals($proof['files_sha256'] ?? '', hash_file('sha256', $proof['files_path']))
|
&& hash_equals($proof['files_sha256'] ?? '', CheckedFile::sha256($proof['files_path']))
|
||||||
&& ($permission['decision_record'] ?? '') !== '' && ($permission['code_hash'] ?? '') === $code
|
&& ($permission['decision_record'] ?? '') !== '' && ($permission['code_hash'] ?? '') === $code
|
||||||
&& ($permission['manifest_sha256'] ?? '') === EconomicReferenceCatalog::MANIFEST_SHA256
|
&& ($permission['manifest_sha256'] ?? '') === EconomicReferenceCatalog::MANIFEST_SHA256
|
||||||
&& in_array($operation, $permission['operations'] ?? [], true);
|
&& in_array($operation, $permission['operations'] ?? [], true);
|
||||||
@@ -83,25 +107,35 @@ class EconomicReferenceInstallation
|
|||||||
'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
|
'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** No source scan/write in preview. Paths are fixed, private and confined to this lot. */
|
/** No source scan/write in preview. Paths are fixed, private and confined to this lot.
|
||||||
|
* @param array<array-key, mixed> $manifest
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function sources(array $manifest): array
|
private function sources(array $manifest): array
|
||||||
{
|
{
|
||||||
$root = realpath($this->directory()); $sources = [];
|
$root = realpath($this->directory());
|
||||||
|
$sources = [];
|
||||||
foreach ($manifest['sources'] as $entry) {
|
foreach ($manifest['sources'] as $entry) {
|
||||||
$path = $root ? realpath($root.DIRECTORY_SEPARATOR.$entry['relative_path']) : false;
|
$path = $root ? realpath($root.DIRECTORY_SEPARATOR.$entry['relative_path']) : false;
|
||||||
$inside = $path && str_starts_with(strtolower(str_replace('\\', '/', $path)), strtolower(str_replace('\\', '/', $root)).'/');
|
$inside = $path && str_starts_with(strtolower(str_replace('\\', '/', $path)), strtolower(str_replace('\\', '/', $root)).'/');
|
||||||
$matches = $inside && is_file($path) && filesize($path) === $entry['bytes'] && hash_equals($entry['sha256'], hash_file('sha256', $path));
|
$matches = $inside && is_file($path) && filesize($path) === $entry['bytes'] && hash_equals($entry['sha256'], CheckedFile::sha256($path));
|
||||||
$sources[] = ['name' => $entry['name'], 'sha256' => $entry['sha256'], 'bytes' => $entry['bytes'], 'ready' => (bool) $matches];
|
$sources[] = ['name' => $entry['name'], 'sha256' => $entry['sha256'], 'bytes' => $entry['bytes'], 'ready' => (bool) $matches];
|
||||||
}
|
}
|
||||||
|
|
||||||
return $sources;
|
return $sources;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $manifest
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function referenceRows(array $manifest): array
|
private function referenceRows(array $manifest): array
|
||||||
{
|
{
|
||||||
$rows = [['table' => 'reference_catalog_versions', 'data' => $manifest['catalog']]];
|
$rows = [['table' => 'reference_catalog_versions', 'data' => $manifest['catalog']]];
|
||||||
foreach (['activities' => 'economic_activities', 'chains' => 'value_chains', 'links' => 'value_chain_links'] as $group => $table) {
|
foreach (['activities' => 'economic_activities', 'chains' => 'value_chains', 'links' => 'value_chain_links'] as $group => $table) {
|
||||||
foreach ($manifest[$group] as $row) { $rows[] = ['table' => $table, 'data' => $row]; }
|
foreach ($manifest[$group] as $row) {
|
||||||
|
$rows[] = ['table' => $table, 'data' => $row];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $rows;
|
return $rows;
|
||||||
@@ -113,41 +147,67 @@ class EconomicReferenceInstallation
|
|||||||
->whereRaw("after_data->'result'->'changed' @> ?::jsonb", [json_encode([$id])])->exists();
|
->whereRaw("after_data->'result'->'changed' @> ?::jsonb", [json_encode([$id])])->exists();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $manifest
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function references(array $manifest, bool $schemaReady): array
|
private function references(array $manifest, bool $schemaReady): array
|
||||||
{
|
{
|
||||||
$results = [];
|
$results = [];
|
||||||
foreach ($this->referenceRows($manifest) as $row) {
|
foreach ($this->referenceRows($manifest) as $row) {
|
||||||
$expected = $row['data']; $table = $row['table'];
|
$expected = $row['data'];
|
||||||
|
$table = $row['table'];
|
||||||
$current = DB::table($table)->where('id', $expected['id'])->first();
|
$current = DB::table($table)->where('id', $expected['id'])->first();
|
||||||
$conflict = false;
|
$conflict = false;
|
||||||
foreach ($expected as $key => $value) {
|
foreach ($expected as $key => $value) {
|
||||||
if (! $current || ($key === 'metadata' && ! $schemaReady)) { continue; }
|
if (! $current || ($key === 'metadata' && ! $schemaReady)) {
|
||||||
if ($key === 'status') { $conflict = $conflict || ! in_array($current->$key, ['draft', 'published'], true); continue; }
|
continue;
|
||||||
if ($key === 'data_classification') { $conflict = $conflict || ! in_array($current->$key, ['internal', 'public'], true); continue; }
|
}
|
||||||
|
if ($key === 'status') {
|
||||||
|
$conflict = $conflict || ! in_array($current->$key, ['draft', 'published'], true);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($key === 'data_classification') {
|
||||||
|
$conflict = $conflict || ! in_array($current->$key, ['internal', 'public'], true);
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
$actual = $key === 'metadata' ? json_decode($current->$key, true) : $current->$key;
|
$actual = $key === 'metadata' ? json_decode($current->$key, true) : $current->$key;
|
||||||
if (OpportunityCanonicalValue::hash($actual) !== OpportunityCanonicalValue::hash($value)) { $conflict = true; }
|
if (OpportunityCanonicalValue::hash($actual) !== OpportunityCanonicalValue::hash($value)) {
|
||||||
|
$conflict = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
$identity = DB::table($table)->where('id', '!=', $expected['id']);
|
$identity = DB::table($table)->where('id', '!=', $expected['id']);
|
||||||
if ($table === 'reference_catalog_versions') { $identity->where('catalog_code', $expected['catalog_code'])->where('version_no', $expected['version_no'])->where('locale', $expected['locale']); }
|
if ($table === 'reference_catalog_versions') {
|
||||||
elseif ($table === 'economic_activities') { $identity->where('catalog_version_id', $expected['catalog_version_id'])->where('code', $expected['code']); }
|
$identity->where('catalog_code', $expected['catalog_code'])->where('version_no', $expected['version_no'])->where('locale', $expected['locale']);
|
||||||
else { $identity->where('source_system', $expected['source_system'])->where('external_id', $expected['external_id']); }
|
} elseif ($table === 'economic_activities') {
|
||||||
|
$identity->where('catalog_version_id', $expected['catalog_version_id'])->where('code', $expected['code']);
|
||||||
|
} else {
|
||||||
|
$identity->where('source_system', $expected['source_system'])->where('external_id', $expected['external_id']);
|
||||||
|
}
|
||||||
$conflict = $conflict || $identity->exists();
|
$conflict = $conflict || $identity->exists();
|
||||||
if ($table === 'value_chains') {
|
if ($table === 'value_chains') {
|
||||||
$conflict = $conflict || DB::table($table)->where('id', '!=', $expected['id'])->where('cluster_id', $expected['cluster_id'])->where('code', $expected['code'])->whereNull('deleted_at')->exists();
|
$conflict = $conflict || DB::table($table)->where('id', '!=', $expected['id'])->where('cluster_id', $expected['cluster_id'])->where('code', $expected['code'])->whereNull('deleted_at')->exists();
|
||||||
}
|
}
|
||||||
$results[] = ['table' => $table, 'id' => $expected['id'], 'code' => $expected['code'] ?? $expected['external_id'] ?? $expected['catalog_code'],
|
$results[] = ['table' => $table, 'id' => $expected['id'], 'code' => $expected['code'] ?? $expected['external_id'] ?? $expected['catalog_code'],
|
||||||
'status' => $conflict ? 'conflict' : ($current ? 'reuse' : 'insert'), 'current_hash' => $current ? OpportunityCanonicalValue::hash((array) $current) : null,
|
'status' => $conflict ? 'conflict' : ($current ? 'reuse' : 'insert'), 'current_hash' => $current ? OpportunityCanonicalValue::hash((array) $current) : null,
|
||||||
'current_visibility' => $current?->status ?? $current?->data_classification ?? null];
|
'current_visibility' => $current->status ?? $current->data_classification ?? null];
|
||||||
}
|
}
|
||||||
|
|
||||||
return $results;
|
return $results;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function preview(User $actor): array
|
public function preview(User $actor): array
|
||||||
{
|
{
|
||||||
$this->authorize($actor);
|
$this->authorize($actor);
|
||||||
$catalog = app(EconomicReferenceCatalog::class); $manifest = $catalog->manifest();
|
$catalog = app(EconomicReferenceCatalog::class);
|
||||||
$target = $this->target(); $code = $this->fingerprint();
|
$manifest = $catalog->manifest();
|
||||||
|
$target = $this->target();
|
||||||
|
$code = $this->fingerprint();
|
||||||
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
|
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
|
||||||
$column = $catalog->schemaAvailable();
|
$column = $catalog->schemaAvailable();
|
||||||
$unique = DB::selectOne("SELECT 1 FROM pg_constraint WHERE conrelid='public.economic_activities'::regclass AND conname='economic_activities_sector_uq'") !== null;
|
$unique = DB::selectOne("SELECT 1 FROM pg_constraint WHERE conrelid='public.economic_activities'::regclass AND conname='economic_activities_sector_uq'") !== null;
|
||||||
@@ -155,19 +215,31 @@ class EconomicReferenceInstallation
|
|||||||
$index = DB::selectOne("SELECT 1 FROM pg_indexes WHERE schemaname='public' AND indexname='economic_activities_sector_idx'") !== null;
|
$index = DB::selectOne("SELECT 1 FROM pg_indexes WHERE schemaname='public' AND indexname='economic_activities_sector_idx'") !== null;
|
||||||
$installed = $ledger && $column && ! $unique && $sectorNullable && $index;
|
$installed = $ledger && $column && ! $unique && $sectorNullable && $index;
|
||||||
$consistent = $installed || (! $ledger && ! $column && $unique && ! $sectorNullable && ! $index);
|
$consistent = $installed || (! $ledger && ! $column && $unique && ! $sectorNullable && ! $index);
|
||||||
$rows = $this->references($manifest, $column); $sources = $this->sources($manifest); $reasons = [];
|
$rows = $this->references($manifest, $column);
|
||||||
|
$sources = $this->sources($manifest);
|
||||||
|
$reasons = [];
|
||||||
foreach (['sector' => 'sectors', 'cluster' => 'economic_clusters'] as $name => $table) {
|
foreach (['sector' => 'sectors', 'cluster' => 'economic_clusters'] as $name => $table) {
|
||||||
$expected = $manifest['existing'][$name]; $record = DB::table($table)->where('id', $expected['id'])->whereNull('deleted_at')->first();
|
$expected = $manifest['existing'][$name];
|
||||||
|
$record = DB::table($table)->where('id', $expected['id'])->whereNull('deleted_at')->first();
|
||||||
foreach (array_filter($expected, fn ($v) => $v !== null) as $field => $value) {
|
foreach (array_filter($expected, fn ($v) => $v !== null) as $field => $value) {
|
||||||
if (! $record || (string) ($record->$field ?? '') !== (string) $value) { $reasons[] = 'Identidade/atributos do '.$name.' divergentes do manifesto; não foi usada semelhança de nomes.'; break; }
|
if (! $record || (string) ($record->$field ?? '') !== (string) $value) {
|
||||||
|
$reasons[] = 'Identidade/atributos do '.$name.' divergentes do manifesto; não foi usada semelhança de nomes.';
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (! $consistent) { $reasons[] = 'Ledger e esquema divergentes; reconciliar antes de instalar.'; }
|
if (! $consistent) {
|
||||||
if (collect($rows)->contains('status', 'conflict')) { $reasons[] = 'Conflito de identidade/versão: não será aplicado parcialmente.'; }
|
$reasons[] = 'Ledger e esquema divergentes; reconciliar antes de instalar.';
|
||||||
if (collect($sources)->contains('ready', false)) { $reasons[] = 'Exemplar privado ausente ou com bytes diferentes.'; }
|
}
|
||||||
|
if (collect($rows)->contains('status', 'conflict')) {
|
||||||
|
$reasons[] = 'Conflito de identidade/versão: não será aplicado parcialmente.';
|
||||||
|
}
|
||||||
|
if (collect($sources)->contains('ready', false)) {
|
||||||
|
$reasons[] = 'Exemplar privado ausente ou com bytes diferentes.';
|
||||||
|
}
|
||||||
$imported = ! collect($rows)->contains(fn ($r) => $r['status'] !== 'reuse');
|
$imported = ! collect($rows)->contains(fn ($r) => $r['status'] !== 'reuse');
|
||||||
$scanPath = $this->directory().'/scans.json';
|
$scanPath = $this->directory().'/scans.json';
|
||||||
$scan = is_file($scanPath) ? json_decode(file_get_contents($scanPath), true) : null;
|
$scan = is_file($scanPath) ? json_decode(CheckedFile::read($scanPath), true) : null;
|
||||||
$state = ['target' => $target, 'code_hash' => $code, 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256,
|
$state = ['target' => $target, 'code_hash' => $code, 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256,
|
||||||
'migration' => self::MIGRATION, 'installed' => $installed, 'consistent' => $consistent, 'imported' => $imported,
|
'migration' => self::MIGRATION, 'installed' => $installed, 'consistent' => $consistent, 'imported' => $imported,
|
||||||
'publication' => $catalog->publicationState(), 'rows' => $rows, 'sources' => $sources, 'scan' => $scan,
|
'publication' => $catalog->publicationState(), 'rows' => $rows, 'sources' => $sources, 'scan' => $scan,
|
||||||
@@ -175,15 +247,27 @@ class EconomicReferenceInstallation
|
|||||||
$operations = [];
|
$operations = [];
|
||||||
foreach (self::OPERATIONS as $operation) {
|
foreach (self::OPERATIONS as $operation) {
|
||||||
$why = $reasons;
|
$why = $reasons;
|
||||||
try { $this->authorize($actor, true, $operation); } catch (HttpException $e) { $why[] = $e->getMessage(); }
|
try {
|
||||||
|
$this->authorize($actor, true, $operation);
|
||||||
|
} catch (HttpException $e) {
|
||||||
|
$why[] = $e->getMessage();
|
||||||
|
}
|
||||||
$evidence = $this->evidence($target, $code, $operation);
|
$evidence = $this->evidence($target, $code, $operation);
|
||||||
if (! $evidence['ready']) { $why[] = 'Decisão própria do ativo e prova fresca desta revisão/alvo/backup/restauro necessárias.'; }
|
if (! $evidence['ready']) {
|
||||||
if ($operation !== 'schema' && ! $installed) { $why[] = 'Instale primeiro o esquema nominal.'; }
|
$why[] = 'Decisão própria do ativo e prova fresca desta revisão/alvo/backup/restauro necessárias.';
|
||||||
if (in_array($operation, ['publish', 'withdraw'], true) && ! $imported) { $why[] = 'Importação privada completa necessária antes de publicar/retirar.'; }
|
}
|
||||||
|
if ($operation !== 'schema' && ! $installed) {
|
||||||
|
$why[] = 'Instale primeiro o esquema nominal.';
|
||||||
|
}
|
||||||
|
if (in_array($operation, ['publish', 'withdraw'], true) && ! $imported) {
|
||||||
|
$why[] = 'Importação privada completa necessária antes de publicar/retirar.';
|
||||||
|
}
|
||||||
if (in_array($operation, ['publish', 'withdraw'], true) && ! DB::table('audit_events')->where('source_system', EconomicReferenceCatalog::SOURCE)->where('action', 'import')->where('after_data->result->manifest_sha256', EconomicReferenceCatalog::MANIFEST_SHA256)->exists()) {
|
if (in_array($operation, ['publish', 'withdraw'], true) && ! DB::table('audit_events')->where('source_system', EconomicReferenceCatalog::SOURCE)->where('action', 'import')->where('after_data->result->manifest_sha256', EconomicReferenceCatalog::MANIFEST_SHA256)->exists()) {
|
||||||
$why[] = 'Execute a importação privada autenticada, inclusive para registos reutilizados.';
|
$why[] = 'Execute a importação privada autenticada, inclusive para registos reutilizados.';
|
||||||
}
|
}
|
||||||
if ($operation === 'withdraw' && $state['publication'] === 'private') { $why[] = 'O lote ainda não teve publicação para retirar.'; }
|
if ($operation === 'withdraw' && $state['publication'] === 'private') {
|
||||||
|
$why[] = 'O lote ainda não teve publicação para retirar.';
|
||||||
|
}
|
||||||
if ($operation === 'withdraw' && collect($rows)->contains(fn ($r) => $r['status'] === 'reuse'
|
if ($operation === 'withdraw' && collect($rows)->contains(fn ($r) => $r['status'] === 'reuse'
|
||||||
&& in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id']))) {
|
&& in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id']))) {
|
||||||
$why[] = 'Há referências anteriores já públicas reutilizadas: reconciliar o mapa de retirada antes de agir.';
|
$why[] = 'Há referências anteriores já públicas reutilizadas: reconciliar o mapa de retirada antes de agir.';
|
||||||
@@ -195,22 +279,34 @@ class EconomicReferenceInstallation
|
|||||||
return [...$state, 'operations' => $operations];
|
return [...$state, 'operations' => $operations];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $manifest
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function scan(array $manifest): array
|
private function scan(array $manifest): array
|
||||||
{
|
{
|
||||||
$directory = realpath($this->directory()); $records = [];
|
$directory = realpath($this->directory());
|
||||||
abort_unless($directory, 422, 'Área privada do lote indisponível.');
|
$records = [];
|
||||||
|
abort_unless(is_string($directory), 422, 'Área privada do lote indisponível.');
|
||||||
$paths = [['name' => 'manifesto', 'path' => database_path('data/economic-references-lot-01.json'), 'sha256' => EconomicReferenceCatalog::MANIFEST_SHA256]];
|
$paths = [['name' => 'manifesto', 'path' => database_path('data/economic-references-lot-01.json'), 'sha256' => EconomicReferenceCatalog::MANIFEST_SHA256]];
|
||||||
foreach ($manifest['sources'] as $source) { $paths[] = ['name' => $source['name'], 'path' => $directory.'/'.$source['relative_path'], 'sha256' => $source['sha256']]; }
|
foreach ($manifest['sources'] as $source) {
|
||||||
|
$paths[] = ['name' => $source['name'], 'path' => $directory.'/'.$source['relative_path'], 'sha256' => $source['sha256']];
|
||||||
|
}
|
||||||
foreach ($paths as $file) {
|
foreach ($paths as $file) {
|
||||||
abort_unless(is_file($file['path']) && hash_equals($file['sha256'], hash_file('sha256', $file['path'])), 409, 'Originais alterados após prévia.');
|
abort_unless(is_file($file['path']) && hash_equals($file['sha256'], CheckedFile::sha256($file['path'])), 409, 'Originais alterados após prévia.');
|
||||||
// Scanner's path confinement uses the private source directory; manifest is scanned via a private exact copy.
|
// Scanner's path confinement uses the private source directory; manifest is scanned via a private exact copy.
|
||||||
$path = $file['path'];
|
$path = $file['path'];
|
||||||
if ($file['name'] === 'manifesto') { $path = $directory.'/manifest-scanned.json'; file_put_contents($path, file_get_contents($file['path'])); }
|
if ($file['name'] === 'manifesto') {
|
||||||
$result = app(MalwareScanner::class)->scan($path, filesize($path), $directory);
|
$path = $directory.'/manifest-scanned.json';
|
||||||
if ($result['signatures_at'] instanceof \DateTimeInterface) { $result['signatures_at'] = $result['signatures_at']->format(DATE_ATOM); }
|
file_put_contents($path, file_get_contents($file['path']));
|
||||||
|
}
|
||||||
|
$result = app(MalwareScanner::class)->scan($path, CheckedFile::size($path), $directory);
|
||||||
|
if ($result['signatures_at'] instanceof \DateTimeInterface) {
|
||||||
|
$result['signatures_at'] = $result['signatures_at']->format(DATE_ATOM);
|
||||||
|
}
|
||||||
$records[] = ['name' => $file['name'], 'sha256' => $file['sha256'], 'scan' => $result];
|
$records[] = ['name' => $file['name'], 'sha256' => $file['sha256'], 'scan' => $result];
|
||||||
abort_unless($result['result'] === 'clean', 423, 'Scan não concluído ou não limpo para '.$file['name'].'. Nenhuma referência foi importada/publicada.');
|
abort_unless($result['result'] === 'clean', 423, 'Scan não concluído ou não limpo para '.$file['name'].'. Nenhuma referência foi importada/publicada.');
|
||||||
abort_unless(hash_equals($file['sha256'], hash_file('sha256', $file['path'])) && hash_equals($file['sha256'], hash_file('sha256', $path)), 409, 'Bytes alterados durante o scan.');
|
abort_unless(CheckedFile::matches($file['path'], $file['sha256']) && CheckedFile::matches($path, $file['sha256']), 409, 'Bytes alterados durante o scan.');
|
||||||
}
|
}
|
||||||
$proof = ['at' => now()->toIso8601String(), 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'files' => $records];
|
$proof = ['at' => now()->toIso8601String(), 'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'files' => $records];
|
||||||
file_put_contents($directory.'/scans.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
file_put_contents($directory.'/scans.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||||
@@ -218,11 +314,15 @@ class EconomicReferenceInstallation
|
|||||||
return $proof;
|
return $proof;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $input
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function apply(User $actor, string $operation, array $input): array
|
public function apply(User $actor, string $operation, array $input): array
|
||||||
{
|
{
|
||||||
abort_unless(in_array($operation, self::OPERATIONS, true), 404);
|
abort_unless(in_array($operation, self::OPERATIONS, true), 404);
|
||||||
$this->authorize($actor, true, $operation);
|
$this->authorize($actor, true, $operation);
|
||||||
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', 'reason', '_token']), 422, 'Campo de ator, manifesto ou conteúdo arbitrário não permitido.');
|
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', 'reason', '_token']) !== [], 422, 'Campo de ator, manifesto ou conteúdo arbitrário não permitido.');
|
||||||
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted', 'reason' => 'required|string|min:20|max:1000'])->validate();
|
||||||
|
|
||||||
return DB::transaction(function () use ($actor, $operation, $data) {
|
return DB::transaction(function () use ($actor, $operation, $data) {
|
||||||
@@ -235,44 +335,73 @@ class EconomicReferenceInstallation
|
|||||||
|
|
||||||
return [...$receipt['result'], 'replayed' => true, 'current_publication' => app(EconomicReferenceCatalog::class)->publicationState()];
|
return [...$receipt['result'], 'replayed' => true, 'current_publication' => app(EconomicReferenceCatalog::class)->publicationState()];
|
||||||
}
|
}
|
||||||
$plan = $this->preview($actor); $phase = $plan['operations'][$operation];
|
$plan = $this->preview($actor);
|
||||||
|
$phase = $plan['operations'][$operation];
|
||||||
abort_unless(hash_equals($phase['hash'], $data['hash']), 409, 'Alvo, ator, revisão ou estado alterados; consulte nova prévia.');
|
abort_unless(hash_equals($phase['hash'], $data['hash']), 409, 'Alvo, ator, revisão ou estado alterados; consulte nova prévia.');
|
||||||
abort_unless($phase['ready'], 422, implode(' ', $phase['reasons']));
|
abort_unless($phase['ready'], 422, implode(' ', $phase['reasons']));
|
||||||
$manifest = app(EconomicReferenceCatalog::class)->manifest(); $changed = []; $reused = [];
|
$manifest = app(EconomicReferenceCatalog::class)->manifest();
|
||||||
foreach ($this->referenceRows($manifest) as $row) { DB::table($row['table'])->where('id', $row['data']['id'])->lockForUpdate()->first(); }
|
$changed = [];
|
||||||
|
$reused = [];
|
||||||
|
foreach ($this->referenceRows($manifest) as $row) {
|
||||||
|
DB::table($row['table'])->where('id', $row['data']['id'])->lockForUpdate()->first();
|
||||||
|
}
|
||||||
DB::table('sectors')->where('id', $manifest['existing']['sector']['id'])->lockForUpdate()->first();
|
DB::table('sectors')->where('id', $manifest['existing']['sector']['id'])->lockForUpdate()->first();
|
||||||
DB::table('economic_clusters')->where('id', $manifest['existing']['cluster']['id'])->lockForUpdate()->first();
|
DB::table('economic_clusters')->where('id', $manifest['existing']['cluster']['id'])->lockForUpdate()->first();
|
||||||
// Recheck after locks in case another approved writer changed a reused master.
|
// Recheck after locks in case another approved writer changed a reused master.
|
||||||
abort_unless($this->preview($actor)['operations'][$operation]['hash'] === $phase['hash'], 409, 'Referências alteradas durante a preparação da operação.');
|
abort_unless($this->preview($actor)['operations'][$operation]['hash'] === $phase['hash'], 409, 'Referências alteradas durante a preparação da operação.');
|
||||||
if ($operation === 'schema' && ! $plan['installed']) {
|
if ($operation === 'schema' && ! $plan['installed']) {
|
||||||
config(['economic_references.authenticated_installation' => true]);
|
config(['economic_references.authenticated_installation' => true]);
|
||||||
try { abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na migration nominal.'); }
|
try {
|
||||||
finally { config(['economic_references.authenticated_installation' => false]); }
|
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na migration nominal.');
|
||||||
|
} finally {
|
||||||
|
config(['economic_references.authenticated_installation' => false]);
|
||||||
|
}
|
||||||
abort_unless($this->preview($actor)['installed'], 500, 'Esquema instalado não corresponde ao plano.');
|
abort_unless($this->preview($actor)['installed'], 500, 'Esquema instalado não corresponde ao plano.');
|
||||||
$changed[] = self::MIGRATION;
|
$changed[] = self::MIGRATION;
|
||||||
} elseif ($operation === 'import') {
|
} elseif ($operation === 'import') {
|
||||||
$scan = $this->scan($manifest);
|
$scan = $this->scan($manifest);
|
||||||
foreach ($this->referenceRows($manifest) as $i => $row) {
|
foreach ($this->referenceRows($manifest) as $i => $row) {
|
||||||
if ($plan['rows'][$i]['status'] === 'reuse') { $reused[] = $row['data']['id']; continue; }
|
if ($plan['rows'][$i]['status'] === 'reuse') {
|
||||||
$values = $row['data']; if (isset($values['metadata'])) { $values['metadata'] = json_encode($values['metadata'], JSON_THROW_ON_ERROR); }
|
$reused[] = $row['data']['id'];
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$values = $row['data'];
|
||||||
|
if (isset($values['metadata'])) {
|
||||||
|
$values['metadata'] = json_encode($values['metadata'], JSON_THROW_ON_ERROR);
|
||||||
|
}
|
||||||
DB::table($row['table'])->insert([...$values, 'created_at' => now(), 'updated_at' => now()]);
|
DB::table($row['table'])->insert([...$values, 'created_at' => now(), 'updated_at' => now()]);
|
||||||
$changed[] = $values['id'];
|
$changed[] = $values['id'];
|
||||||
}
|
}
|
||||||
} elseif ($operation === 'publish' || $operation === 'withdraw') {
|
} elseif ($operation === 'publish' || $operation === 'withdraw') {
|
||||||
if ($operation === 'publish') { $scan = $this->scan($manifest); }
|
if ($operation === 'publish') {
|
||||||
|
$scan = $this->scan($manifest);
|
||||||
|
}
|
||||||
foreach ($this->referenceRows($manifest) as $row) {
|
foreach ($this->referenceRows($manifest) as $row) {
|
||||||
$table = $row['table']; $record = DB::table($table)->where('id', $row['data']['id'])->lockForUpdate()->first();
|
$table = $row['table'];
|
||||||
|
$record = DB::table($table)->where('id', $row['data']['id'])->lockForUpdate()->first();
|
||||||
if (in_array($table, ['reference_catalog_versions', 'economic_activities'], true)) {
|
if (in_array($table, ['reference_catalog_versions', 'economic_activities'], true)) {
|
||||||
if ($operation === 'publish' && $record->status === 'draft') {
|
if ($operation === 'publish' && $record->status === 'draft') {
|
||||||
DB::table($table)->where('id', $record->id)->update(['status' => 'published', 'updated_at' => now()]); $changed[] = $record->id;
|
DB::table($table)->where('id', $record->id)->update(['status' => 'published', 'updated_at' => now()]);
|
||||||
} else { $reused[] = $record->id; }
|
$changed[] = $record->id;
|
||||||
|
} else {
|
||||||
|
$reused[] = $record->id;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
$visibility = $operation === 'publish' ? 'public' : 'internal';
|
$visibility = $operation === 'publish' ? 'public' : 'internal';
|
||||||
// Withdrawal touches only objects this importer created, never pre-existing public references.
|
// Withdrawal touches only objects this importer created, never pre-existing public references.
|
||||||
$createdHere = $this->createdHere($record->id);
|
$createdHere = $this->createdHere($record->id);
|
||||||
if ($operation === 'withdraw' && ! $createdHere) { $reused[] = $record->id; continue; }
|
if ($operation === 'withdraw' && ! $createdHere) {
|
||||||
if ($record->data_classification !== $visibility) { DB::table($table)->where('id', $record->id)->update(['data_classification' => $visibility, 'updated_at' => now()]); $changed[] = $record->id; }
|
$reused[] = $record->id;
|
||||||
else { $reused[] = $record->id; }
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ($record->data_classification !== $visibility) {
|
||||||
|
DB::table($table)->where('id', $record->id)->update(['data_classification' => $visibility, 'updated_at' => now()]);
|
||||||
|
$changed[] = $record->id;
|
||||||
|
} else {
|
||||||
|
$reused[] = $record->id;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -280,7 +409,9 @@ class EconomicReferenceInstallation
|
|||||||
'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'code_hash' => $plan['code_hash'], 'replayed' => false,
|
'manifest_sha256' => EconomicReferenceCatalog::MANIFEST_SHA256, 'code_hash' => $plan['code_hash'], 'replayed' => false,
|
||||||
'publications' => $operation === 'publish' ? 'references only; no investment or original source publication' : 'none', 'business_records_changed' => 0,
|
'publications' => $operation === 'publish' ? 'references only; no investment or original source publication' : 'none', 'business_records_changed' => 0,
|
||||||
'receipt' => $data['idempotency_key'], 'scan' => $scan ?? null];
|
'receipt' => $data['idempotency_key'], 'scan' => $scan ?? null];
|
||||||
if ($operation === 'import') { $result['previously_public'] = array_values(array_column(array_filter($plan['rows'], fn ($r) => $r['status'] === 'reuse' && in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id'])), 'id')); }
|
if ($operation === 'import') {
|
||||||
|
$result['previously_public'] = array_column(array_filter($plan['rows'], fn ($r) => $r['status'] === 'reuse' && in_array($r['current_visibility'], ['public', 'published'], true) && ! $this->createdHere($r['id'])), 'id');
|
||||||
|
}
|
||||||
DB::table('audit_events')->insert(['source_system' => EconomicReferenceCatalog::SOURCE, 'entity_type' => 'economic-reference-batch', 'entity_id' => $manifest['catalog']['id'],
|
DB::table('audit_events')->insert(['source_system' => EconomicReferenceCatalog::SOURCE, 'entity_type' => 'economic-reference-batch', 'entity_id' => $manifest['catalog']['id'],
|
||||||
'actor_user_id' => $actor->id, 'correlation_id' => $data['idempotency_key'], 'action' => $operation, 'data_classification' => 'restricted',
|
'actor_user_id' => $actor->id, 'correlation_id' => $data['idempotency_key'], 'action' => $operation, 'data_classification' => 'restricted',
|
||||||
'after_data' => json_encode(['request_hash' => $requestHash, 'reason' => $data['reason'], 'result' => $result], JSON_THROW_ON_ERROR)]);
|
'after_data' => json_encode(['request_hash' => $requestHash, 'reason' => $data['reason'], 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||||
|
|||||||
@@ -3,8 +3,10 @@
|
|||||||
namespace App\Services;
|
namespace App\Services;
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Support\CheckedFile;
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\File;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
@@ -12,75 +14,139 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
|
|||||||
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
|
/** Nominal schema installation. No imports, backfill, publication, permissions or flags. */
|
||||||
class EditorialInstallation
|
class EditorialInstallation
|
||||||
{
|
{
|
||||||
public const SOURCE='editorial-schema-installation';
|
public const SOURCE = 'editorial-schema-installation';
|
||||||
public const MIGRATION='2026_10_18_160000_add_portal_editorial_content';
|
|
||||||
|
public const MIGRATION = '2026_10_18_160000_add_portal_editorial_content';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function files(): array
|
public function files(): array
|
||||||
{
|
{
|
||||||
return ['app/Http/Controllers/EditorialArticleController.php', 'app/Http/Controllers/PortalManagementController.php', 'app/Http/Controllers/PortalServicesController.php', 'app/Http/Controllers/PublicPortalController.php', 'app/Services/InvestmentCatalogue.php', 'app/Services/LegacyContent.php', 'app/Services/OpportunityClassification.php', 'routes/web.php', 'database/migrations/2026_10_18_160000_add_portal_editorial_content.php', 'resources/js/pages/management/editor.tsx', 'resources/js/pages/portal/article-editor.tsx', 'resources/js/pages/portal/article.tsx', 'resources/js/pages/portal/document.tsx', 'resources/js/pages/portal/manage.tsx', 'app/Services/EditorialInstallation.php', 'resources/views/management/editorial-installation.blade.php', 'resources/views/management/editorial-mfa.blade.php'];
|
return ['app/Http/Controllers/EditorialArticleController.php', 'app/Http/Controllers/PortalManagementController.php', 'app/Http/Controllers/PortalServicesController.php', 'app/Http/Controllers/PublicPortalController.php', 'app/Services/InvestmentCatalogue.php', 'app/Services/LegacyContent.php', 'app/Services/OpportunityClassification.php', 'routes/web.php', 'database/migrations/2026_10_18_160000_add_portal_editorial_content.php', 'resources/js/pages/management/editor.tsx', 'resources/js/pages/portal/article-editor.tsx', 'resources/js/pages/portal/article.tsx', 'resources/js/pages/portal/document.tsx', 'resources/js/pages/portal/manage.tsx', 'app/Services/EditorialInstallation.php', 'resources/views/management/editorial-installation.blade.php', 'resources/views/management/editorial-mfa.blade.php'];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function fingerprint(): string
|
public function fingerprint(): string
|
||||||
{
|
{
|
||||||
$files=array_map(fn($p)=>[$p,hash_file('sha256',base_path($p))],$this->files());
|
$files = array_map(fn ($p) => [$p, hash_file('sha256', base_path($p))], $this->files());
|
||||||
foreach(\Illuminate\Support\Facades\File::allFiles(public_path('build')) as $file){$files[]=['public/build/'.$file->getRelativePathname(),hash_file('sha256',$file->getPathname())];}
|
foreach (File::allFiles(public_path('build')) as $file) {
|
||||||
usort($files,fn($a,$b)=>strcmp($a[0],$b[0]));
|
$files[] = ['public/build/'.$file->getRelativePathname(), hash_file('sha256', $file->getPathname())];
|
||||||
return hash('sha256',json_encode($files,JSON_THROW_ON_ERROR));
|
}
|
||||||
|
usort($files, fn ($a, $b) => strcmp($a[0], $b[0]));
|
||||||
|
|
||||||
|
return hash('sha256', json_encode($files, JSON_THROW_ON_ERROR));
|
||||||
}
|
}
|
||||||
private function authorize(User $actor,bool $write=false): void
|
|
||||||
|
private function authorize(User $actor, bool $write = false): void
|
||||||
{
|
{
|
||||||
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'),403,'Gestão autorizada necessária.');
|
abort_unless($actor->hasVerifiedEmail() && $actor->can('manage-portal'), 403, 'Gestão autorizada necessária.');
|
||||||
if($write){app(PortalProfileInstallation::class)->authorize($actor,true);}
|
if ($write) {
|
||||||
|
app(PortalProfileInstallation::class)->authorize($actor, true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
private function evidence(array $target,string $code): array
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $target
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
private function evidence(array $target, string $code): array
|
||||||
{
|
{
|
||||||
$qa=app()->environment('testing') && (int)$target['port']===55441 && str_ends_with($target['database'],'_test')
|
$qa = app()->environment('testing') && (int) $target['port'] === 55441 && str_ends_with($target['database'], '_test')
|
||||||
&& config('database.connections.pgsql.host')==='127.0.0.1' && !config('database.connections.pgsql.url');
|
&& config('database.connections.pgsql.host') === '127.0.0.1' && ! config('database.connections.pgsql.url');
|
||||||
if($qa){return ['ready'=>true,'mode'=>'isolated_QA'];}
|
if ($qa) {
|
||||||
if(app()->environment('testing')){return ['ready'=>false,'mode'=>'invalid_QA'];}
|
return ['ready' => true, 'mode' => 'isolated_QA'];
|
||||||
$path=storage_path('app/private/investmoz-v2/editorial/readiness.json');
|
}
|
||||||
$p=is_file($path)?json_decode(file_get_contents($path),true):[];$date=strtotime($p['verified_at'] ?? '');$auth=$p['active_authorization'] ?? [];
|
if (app()->environment('testing')) {
|
||||||
$ready=$target['database']==='investemoz' && (int)$target['port']===5432 && !config('database.connections.pgsql.url')
|
return ['ready' => false, 'mode' => 'invalid_QA'];
|
||||||
&& in_array(config('database.connections.pgsql.host'),['127.0.0.1','localhost'],true)
|
}
|
||||||
&& ($p['target']['database'] ?? '')===$target['database'] && (int)($p['target']['port'] ?? 0)===(int)$target['port']
|
$path = storage_path('app/private/investmoz-v2/editorial/readiness.json');
|
||||||
&& ($p['code_hash'] ?? '')===$code && $date!==false && $date<=time() && $date>=time()-86400
|
$p = is_file($path) ? json_decode(CheckedFile::read($path), true) : [];
|
||||||
|
$date = strtotime($p['verified_at'] ?? '');
|
||||||
|
$auth = $p['active_authorization'] ?? [];
|
||||||
|
$ready = $target['database'] === 'investemoz' && (int) $target['port'] === 5432 && ! config('database.connections.pgsql.url')
|
||||||
|
&& in_array(config('database.connections.pgsql.host'), ['127.0.0.1', 'localhost'], true)
|
||||||
|
&& ($p['target']['database'] ?? '') === $target['database'] && (int) ($p['target']['port'] ?? 0) === (int) $target['port']
|
||||||
|
&& ($p['code_hash'] ?? '') === $code && $date !== false && $date <= time() && $date >= time() - 86400
|
||||||
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
|
&& ($p['restore_verified'] ?? false) && ($p['files_verified'] ?? false) && ($p['qa_passed'] ?? false) && ($p['compatibility_verified'] ?? false)
|
||||||
&& ($p['restored_boot_verified'] ?? false) && (int)($p['restore_target']['port'] ?? 0)===55441 && str_ends_with($p['restore_target']['database'] ?? '','_test')
|
&& ($p['restored_boot_verified'] ?? false) && (int) ($p['restore_target']['port'] ?? 0) === 55441 && str_ends_with($p['restore_target']['database'] ?? '', '_test')
|
||||||
&& ($auth['decision_record'] ?? '')!=='' && ($auth['code_hash'] ?? '')===$code && ($auth['migration'] ?? '')===self::MIGRATION;
|
&& ($auth['decision_record'] ?? '') !== '' && ($auth['code_hash'] ?? '') === $code && ($auth['migration'] ?? '') === self::MIGRATION;
|
||||||
foreach(['dump','files'] as $kind){$file=$p[$kind.'_path'] ?? ''; $ready=$ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '',hash_file('sha256',$file));}
|
foreach (['dump', 'files'] as $kind) {
|
||||||
return ['ready'=>$ready,'mode'=>'active_requires_own_authorization_and_fresh_proof','proof_hash'=>is_file($path)?hash_file('sha256',$path):null];
|
$file = $p[$kind.'_path'] ?? '';
|
||||||
|
$ready = $ready && is_file($file) && hash_equals($p[$kind.'_sha256'] ?? '', CheckedFile::sha256($file));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['ready' => $ready, 'mode' => 'active_requires_own_authorization_and_fresh_proof', 'proof_hash' => is_file($path) ? hash_file('sha256', $path) : null];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function preview(User $actor): array
|
public function preview(User $actor): array
|
||||||
{
|
{
|
||||||
$this->authorize($actor);$target=(array)DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');$code=$this->fingerprint();
|
$this->authorize($actor);
|
||||||
$ledgerCount=DB::table('migrations')->where('migration',self::MIGRATION)->count();$ledger=$ledgerCount===1;$column=Schema::hasColumn('portal_resources','editorial_content');
|
$target = (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
|
||||||
$shape=DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='portal_resources' AND column_name='editorial_content'");
|
$code = $this->fingerprint();
|
||||||
$correct=$shape && $shape->data_type==='jsonb' && $shape->is_nullable==='YES';
|
$ledgerCount = DB::table('migrations')->where('migration', self::MIGRATION)->count();
|
||||||
$consistent=($ledger && $column && $correct) || ($ledgerCount===0 && !$column);$reasons=[];
|
$ledger = $ledgerCount === 1;
|
||||||
if(!$consistent){$reasons[]='Ledger e coluna divergentes; reconciliar sem instalação parcial.';}
|
$column = Schema::hasColumn('portal_resources', 'editorial_content');
|
||||||
try{$this->authorize($actor,true);}catch(HttpException $e){$reasons[]=$e->getMessage();}
|
$shape = DB::selectOne("SELECT data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='portal_resources' AND column_name='editorial_content'");
|
||||||
$evidence=$this->evidence($target,$code);if(!$evidence['ready']){$reasons[]='Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';}
|
$correct = $shape && $shape->data_type === 'jsonb' && $shape->is_nullable === 'YES';
|
||||||
$state=['target'=>$target,'migration'=>self::MIGRATION,'code_hash'=>$code,'installed'=>$ledger && $column,
|
$consistent = ($ledger && $column && $correct) || ($ledgerCount === 0 && ! $column);
|
||||||
'consistent'=>$consistent,'ready'=>$reasons===[],'reasons'=>$reasons,'evidence'=>$evidence];
|
$reasons = [];
|
||||||
return [...$state,'hash'=>hash_hmac('sha256',json_encode([$actor->id,session()->getId(),$state],JSON_THROW_ON_ERROR),config('app.key'))];
|
if (! $consistent) {
|
||||||
|
$reasons[] = 'Ledger e coluna divergentes; reconciliar sem instalação parcial.';
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$this->authorize($actor, true);
|
||||||
|
} catch (HttpException $e) {
|
||||||
|
$reasons[] = $e->getMessage();
|
||||||
|
}
|
||||||
|
$evidence = $this->evidence($target, $code);
|
||||||
|
if (! $evidence['ready']) {
|
||||||
|
$reasons[] = 'Decisão específica e backup/restauro/arranque frescos desta revisão necessários.';
|
||||||
|
}
|
||||||
|
$state = ['target' => $target, 'migration' => self::MIGRATION, 'code_hash' => $code, 'installed' => $ledger && $column,
|
||||||
|
'consistent' => $consistent, 'ready' => $reasons === [], 'reasons' => $reasons, 'evidence' => $evidence];
|
||||||
|
|
||||||
|
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
|
||||||
}
|
}
|
||||||
public function apply(User $actor,array $input): array
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $input
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function apply(User $actor, array $input): array
|
||||||
{
|
{
|
||||||
$this->authorize($actor,true);
|
$this->authorize($actor, true);
|
||||||
abort_if(array_diff(array_keys($input),['hash','idempotency_key','confirm','_token']),422,'Ator, migration ou caminho arbitrário não permitido.');
|
abort_if(array_diff(array_keys($input), ['hash', 'idempotency_key', 'confirm', '_token']) !== [], 422, 'Ator, migration ou caminho arbitrário não permitido.');
|
||||||
$data=Validator::make($input,['hash'=>'required|string|size:64','idempotency_key'=>'required|uuid','confirm'=>'required|accepted'])->validate();
|
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'idempotency_key' => 'required|uuid', 'confirm' => 'required|accepted'])->validate();
|
||||||
return DB::transaction(function()use($actor,$data){
|
|
||||||
DB::select('SELECT pg_advisory_xact_lock(181026,160000)');$requestHash=hash('sha256',json_encode($data,JSON_THROW_ON_ERROR));
|
return DB::transaction(function () use ($actor, $data) {
|
||||||
$old=DB::table('audit_events')->where('source_system',self::SOURCE)->where('correlation_id',$data['idempotency_key'])->first();
|
DB::select('SELECT pg_advisory_xact_lock(181026,160000)');
|
||||||
if($old){$receipt=json_decode($old->after_data,true);abort_unless((int)$old->actor_user_id===$actor->id && hash_equals($receipt['request_hash'],$requestHash),409,'Chave já utilizada com outro ator ou conteúdo.');return [...$receipt['result'],'replayed'=>true];}
|
$requestHash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||||
$plan=$this->preview($actor);abort_unless(hash_equals($plan['hash'],$data['hash']),409,'Prévia alterada; consulte novamente.');abort_unless($plan['ready'],422,implode(' ',$plan['reasons']));
|
$old = DB::table('audit_events')->where('source_system', self::SOURCE)->where('correlation_id', $data['idempotency_key'])->first();
|
||||||
if(!$plan['installed']){
|
if ($old) {
|
||||||
config(['editorial.authenticated_installation'=>true]);
|
$receipt = json_decode($old->after_data, true);
|
||||||
try{abort_unless(Artisan::call('migrate',['--path'=>'database/migrations/'.self::MIGRATION.'.php','--force'=>true])===0,500,'Falha na instalação nominal.');}
|
abort_unless((int) $old->actor_user_id === $actor->id && hash_equals($receipt['request_hash'], $requestHash), 409, 'Chave já utilizada com outro ator ou conteúdo.');
|
||||||
finally{config(['editorial.authenticated_installation'=>false]);}
|
|
||||||
|
return [...$receipt['result'], 'replayed' => true];
|
||||||
}
|
}
|
||||||
abort_unless($this->preview($actor)['installed'],500,'Esquema nominal inconsistente.');
|
$plan = $this->preview($actor);
|
||||||
$result=['migration'=>$plan['migration'],'code_hash'=>$plan['code_hash'],'target'=>$plan['target'],'changed'=>!$plan['installed'],'business_records_changed'=>0,'replayed'=>false,'receipt'=>$data['idempotency_key']];
|
abort_unless(hash_equals($plan['hash'], $data['hash']), 409, 'Prévia alterada; consulte novamente.');
|
||||||
DB::table('audit_events')->insert(['source_system'=>self::SOURCE,'entity_type'=>'portal-editorial-schema','entity_id'=>null,'actor_user_id'=>$actor->id,
|
abort_unless($plan['ready'], 422, implode(' ', $plan['reasons']));
|
||||||
'correlation_id'=>$data['idempotency_key'],'action'=>'schema','data_classification'=>'restricted','after_data'=>json_encode(['request_hash'=>$requestHash,'result'=>$result],JSON_THROW_ON_ERROR)]);
|
if (! $plan['installed']) {
|
||||||
|
config(['editorial.authenticated_installation' => true]);
|
||||||
|
try {
|
||||||
|
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha na instalação nominal.');
|
||||||
|
} finally {
|
||||||
|
config(['editorial.authenticated_installation' => false]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
abort_unless($this->preview($actor)['installed'], 500, 'Esquema nominal inconsistente.');
|
||||||
|
$result = ['migration' => $plan['migration'], 'code_hash' => $plan['code_hash'], 'target' => $plan['target'], 'changed' => ! $plan['installed'], 'business_records_changed' => 0, 'replayed' => false, 'receipt' => $data['idempotency_key']];
|
||||||
|
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'portal-editorial-schema', 'entity_id' => null, 'actor_user_id' => $actor->id,
|
||||||
|
'correlation_id' => $data['idempotency_key'], 'action' => 'schema', 'data_classification' => 'restricted', 'after_data' => json_encode(['request_hash' => $requestHash, 'result' => $result], JSON_THROW_ON_ERROR)]);
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Support\CheckedFile;
|
||||||
|
use GuzzleHttp\Psr7\Uri;
|
||||||
|
use GuzzleHttp\Psr7\UriResolver;
|
||||||
|
use Illuminate\Database\Query\Builder;
|
||||||
|
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(): 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', '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');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>|null
|
||||||
|
*/
|
||||||
|
public function original(\stdClass $resource): ?array
|
||||||
|
{
|
||||||
|
$document = DB::table('documents')->where('id', $resource->document_id)->first();
|
||||||
|
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'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed>|null $original
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function content(\stdClass $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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed>|null $override
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function reading(\stdClass $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')->where('id', $resource->document_id)->first();
|
||||||
|
// 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(CheckedFile::read(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,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ use App\Models\ExistingBusiness;
|
|||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Policies\ExistingBusinessPolicy;
|
use App\Policies\ExistingBusinessPolicy;
|
||||||
use App\Services\Mne\BusinessRepository;
|
use App\Services\Mne\BusinessRepository;
|
||||||
|
use App\Support\StructuredData;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Support\Facades\Crypt;
|
use Illuminate\Support\Facades\Crypt;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
@@ -19,8 +20,12 @@ use Illuminate\Validation\ValidationException;
|
|||||||
class ExistingBusinessClassification
|
class ExistingBusinessClassification
|
||||||
{
|
{
|
||||||
public const VERSION = 'business-classification-20261016-v1';
|
public const VERSION = 'business-classification-20261016-v1';
|
||||||
|
|
||||||
private const ACTIONS = ['classification_prepared', 'classification_reviewed', 'classification_disclosed', 'classification_withdrawn'];
|
private const ACTIONS = ['classification_prepared', 'classification_reviewed', 'classification_disclosed', 'classification_withdrawn'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function context(ExistingBusiness $business): array
|
public function context(ExistingBusiness $business): array
|
||||||
{
|
{
|
||||||
$revision = DB::table('existing_business_revisions')->where('business_id', $business->id)->whereIn('action', self::ACTIONS)->orderByDesc('version_no')->first(['snapshot']);
|
$revision = DB::table('existing_business_revisions')->where('business_id', $business->id)->whereIn('action', self::ACTIONS)->orderByDesc('version_no')->first(['snapshot']);
|
||||||
@@ -33,11 +38,18 @@ class ExistingBusinessClassification
|
|||||||
return $state;
|
return $state;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $row
|
||||||
|
*/
|
||||||
private function hash(array $row): string
|
private function hash(array $row): string
|
||||||
{
|
{
|
||||||
return OpportunityCanonicalValue::hash($row);
|
return OpportunityCanonicalValue::hash($row);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $row
|
||||||
|
* @return array<array-key, mixed>|null
|
||||||
|
*/
|
||||||
private function evidence(array $row, ExistingBusiness $business): ?array
|
private function evidence(array $row, ExistingBusiness $business): ?array
|
||||||
{
|
{
|
||||||
$id = $row['classification']['document_id'] ?? null;
|
$id = $row['classification']['document_id'] ?? null;
|
||||||
@@ -51,6 +63,9 @@ class ExistingBusinessClassification
|
|||||||
return $document ? (array) $document : ['unavailable' => $id];
|
return $document ? (array) $document : ['unavailable' => $id];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $row
|
||||||
|
*/
|
||||||
private function evidenceHash(array $row, ExistingBusiness $business): ?string
|
private function evidenceHash(array $row, ExistingBusiness $business): ?string
|
||||||
{
|
{
|
||||||
$evidence = $this->evidence($row, $business);
|
$evidence = $this->evidence($row, $business);
|
||||||
@@ -58,6 +73,9 @@ class ExistingBusinessClassification
|
|||||||
return $evidence === null ? null : OpportunityCanonicalValue::hash($evidence);
|
return $evidence === null ? null : OpportunityCanonicalValue::hash($evidence);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $rows
|
||||||
|
*/
|
||||||
private function validateRows(array $rows, ExistingBusiness $business, bool $confirming = false): void
|
private function validateRows(array $rows, ExistingBusiness $business, bool $confirming = false): void
|
||||||
{
|
{
|
||||||
$seen = [];
|
$seen = [];
|
||||||
@@ -80,7 +98,8 @@ class ExistingBusinessClassification
|
|||||||
if (array_diff(array_keys($row), ['related_id', 'relation_type', 'classification'])) {
|
if (array_diff(array_keys($row), ['related_id', 'relation_type', 'classification'])) {
|
||||||
$fail('classification', 'Metadados de decisão ou campos desconhecidos não podem ser enviados pelo autor.');
|
$fail('classification', 'Metadados de decisão ou campos desconhecidos não podem ser enviados pelo autor.');
|
||||||
}
|
}
|
||||||
$c = $row['classification']; $kind = $c['target_type'];
|
$c = $row['classification'];
|
||||||
|
$kind = $c['target_type'];
|
||||||
if (($kind === 'sector' && ! ctype_digit($row['related_id'])) || ($kind !== 'sector' && ! Str::isUuid($row['related_id']))) {
|
if (($kind === 'sector' && ! ctype_digit($row['related_id'])) || ($kind !== 'sector' && ! Str::isUuid($row['related_id']))) {
|
||||||
$fail('related_id', 'Identificador de referência inválido.');
|
$fail('related_id', 'Identificador de referência inválido.');
|
||||||
}
|
}
|
||||||
@@ -91,7 +110,9 @@ class ExistingBusinessClassification
|
|||||||
$fail('classification.purpose', 'Regime, admissão e benefício usam a relação regulatória com a zona.');
|
$fail('classification.purpose', 'Regime, admissão e benefício usam a relação regulatória com a zona.');
|
||||||
}
|
}
|
||||||
$identity = OpportunityClassification::TARGETS[$kind][0].':'.$row['related_id'].':'.$c['purpose'];
|
$identity = OpportunityClassification::TARGETS[$kind][0].':'.$row['related_id'].':'.$c['purpose'];
|
||||||
if (isset($seen[$identity])) { $fail('related_id', 'Referência e finalidade já associadas; recupere a relação existente.'); }
|
if (isset($seen[$identity])) {
|
||||||
|
$fail('related_id', 'Referência e finalidade já associadas; recupere a relação existente.');
|
||||||
|
}
|
||||||
$seen[$identity] = true;
|
$seen[$identity] = true;
|
||||||
if (! empty($c['valid_from']) && ! empty($c['valid_until']) && $c['valid_until'] < $c['valid_from']) {
|
if (! empty($c['valid_from']) && ! empty($c['valid_until']) && $c['valid_until'] < $c['valid_from']) {
|
||||||
$fail('classification.valid_until', 'O fim da vigência precede o início.');
|
$fail('classification.valid_until', 'O fim da vigência precede o início.');
|
||||||
@@ -100,13 +121,17 @@ class ExistingBusinessClassification
|
|||||||
$fail('classification.authority_id', 'Entidade competente não consta do catálogo publicado.');
|
$fail('classification.authority_id', 'Entidade competente não consta do catálogo publicado.');
|
||||||
}
|
}
|
||||||
$evidence = $this->evidence($row, $business);
|
$evidence = $this->evidence($row, $business);
|
||||||
if ($evidence && isset($evidence['unavailable'])) { $fail('classification.document_id', 'Documento não está associado a este anúncio.'); }
|
if ($evidence && isset($evidence['unavailable'])) {
|
||||||
|
$fail('classification.document_id', 'Documento não está associado a este anúncio.');
|
||||||
|
}
|
||||||
if (($c['external_status'] ?? '') === 'documented_granted' && (empty($c['document_id']) || empty(trim($c['external_act_reference'] ?? '')))) {
|
if (($c['external_status'] ?? '') === 'documented_granted' && (empty($c['document_id']) || empty(trim($c['external_act_reference'] ?? '')))) {
|
||||||
$fail('classification.external_act_reference', 'Um ato declarado como concedido exige documento e referência próprios.');
|
$fail('classification.external_act_reference', 'Um ato declarado como concedido exige documento e referência próprios.');
|
||||||
}
|
}
|
||||||
if ($confirming) {
|
if ($confirming) {
|
||||||
foreach (['criteria', 'justification', 'source_reference', 'citation'] as $key) {
|
foreach (['criteria', 'justification', 'source_reference', 'citation'] as $key) {
|
||||||
if (empty(trim($c[$key] ?? ''))) { $fail('classification.'.$key, 'Confirmação exige fundamento e fonte/citação por relação; a preparação pode continuar preliminar.'); }
|
if (empty(trim($c[$key] ?? ''))) {
|
||||||
|
$fail('classification.'.$key, 'Confirmação exige fundamento e fonte/citação por relação; a preparação pode continuar preliminar.');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ($evidence && ($evidence['status'] !== 'active' || $evidence['deleted_at'] !== null || $evidence['malware_scan_status'] !== 'clean'
|
if ($evidence && ($evidence['status'] !== 'active' || $evidence['deleted_at'] !== null || $evidence['malware_scan_status'] !== 'clean'
|
||||||
|| ! hash_equals(trim($evidence['sha256']), trim((string) $evidence['malware_scanned_sha256']))
|
|| ! hash_equals(trim($evidence['sha256']), trim((string) $evidence['malware_scanned_sha256']))
|
||||||
@@ -117,13 +142,21 @@ class ExistingBusinessClassification
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $row
|
||||||
|
* @param array<array-key, mixed> $state
|
||||||
|
*/
|
||||||
private function effective(ExistingBusiness $business, array $row, array $state): string
|
private function effective(ExistingBusiness $business, array $row, array $state): string
|
||||||
{
|
{
|
||||||
$decision = $state['decisions'][$this->hash($row)] ?? null;
|
$decision = $state['decisions'][$this->hash($row)] ?? null;
|
||||||
if (! $decision) { return $row['classification']['requested_state'] ?? 'preliminary'; }
|
if (! $decision) {
|
||||||
if ($decision['state'] !== 'confirmed') { return $decision['state']; }
|
return $row['classification']['requested_state'] ?? 'preliminary';
|
||||||
|
}
|
||||||
|
if ($decision['state'] !== 'confirmed') {
|
||||||
|
return $decision['state'];
|
||||||
|
}
|
||||||
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||||
$reviewer = User::find($decision['actor_id']);
|
$reviewer = User::whereKey($decision['actor_id'])->first();
|
||||||
if (! $reviewer || ! app(ExistingBusinessPolicy::class)->classificationReviewerScope($reviewer, $business, $dimension)
|
if (! $reviewer || ! app(ExistingBusinessPolicy::class)->classificationReviewerScope($reviewer, $business, $dimension)
|
||||||
|| (int) ($state['authors'][$this->hash($row)] ?? 0) === (int) $reviewer->id
|
|| (int) ($state['authors'][$this->hash($row)] ?? 0) === (int) $reviewer->id
|
||||||
|| ($decision['evidence_hash'] ?? null) !== $this->evidenceHash($row, $business)) {
|
|| ($decision['evidence_hash'] ?? null) !== $this->evidenceHash($row, $business)) {
|
||||||
@@ -133,13 +166,17 @@ class ExistingBusinessClassification
|
|||||||
return 'confirmed';
|
return 'confirmed';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function privateView(User $actor, ExistingBusiness $business): array
|
public function privateView(User $actor, ExistingBusiness $business): array
|
||||||
{
|
{
|
||||||
Gate::forUser($actor)->authorize('view', $business);
|
Gate::forUser($actor)->authorize('view', $business);
|
||||||
$state = $this->context($business);
|
$state = $this->context($business);
|
||||||
$rows = [];
|
$rows = [];
|
||||||
foreach ($state['relations'] as $row) {
|
foreach ($state['relations'] as $row) {
|
||||||
$hash = $this->hash($row); $dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
$hash = $this->hash($row);
|
||||||
|
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||||
$rows[] = ['hash' => $hash, 'relation' => $row, 'dimension' => $dimension, 'state' => $this->effective($business, $row, $state),
|
$rows[] = ['hash' => $hash, 'relation' => $row, 'dimension' => $dimension, 'state' => $this->effective($business, $row, $state),
|
||||||
'can_review' => Gate::forUser($actor)->allows('reviewClassification', $business) && app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
|
'can_review' => Gate::forUser($actor)->allows('reviewClassification', $business) && app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
|
||||||
&& (int) ($state['authors'][$hash] ?? 0) !== (int) $actor->id,
|
&& (int) ($state['authors'][$hash] ?? 0) !== (int) $actor->id,
|
||||||
@@ -158,6 +195,9 @@ class ExistingBusinessClassification
|
|||||||
'documents' => $documents->map(fn ($d) => ['id' => $d->id, 'payload' => ['title' => $d->file_name], 'file' => ['file_name' => $d->file_name]])];
|
'documents' => $documents->map(fn ($d) => ['id' => $d->id, 'payload' => ['title' => $d->file_name], 'file' => ['file_name' => $d->file_name]])];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $input
|
||||||
|
*/
|
||||||
public function act(User $actor, string $id, array $input): ExistingBusiness
|
public function act(User $actor, string $id, array $input): ExistingBusiness
|
||||||
{
|
{
|
||||||
$data = Validator::make($input, [
|
$data = Validator::make($input, [
|
||||||
@@ -167,26 +207,32 @@ class ExistingBusinessClassification
|
|||||||
'hash' => ['required_if:action,review', 'string', 'size:64'],
|
'hash' => ['required_if:action,review', 'string', 'size:64'],
|
||||||
'state' => ['required_if:action,review', Rule::in(['in_validation', 'confirmed', 'rejected', 'archived', 'revoked'])],
|
'state' => ['required_if:action,review', Rule::in(['in_validation', 'confirmed', 'rejected', 'archived', 'revoked'])],
|
||||||
], ['reason.required' => 'Indique o fundamento da ação.', 'reason.min' => 'O fundamento deve ter pelo menos 20 caracteres.'])->validate();
|
], ['reason.required' => 'Indique o fundamento da ação.', 'reason.min' => 'O fundamento deve ter pelo menos 20 caracteres.'])->validate();
|
||||||
abort_if(array_diff(array_keys($input), ['action', 'version_no', 'reason', 'rows', 'hash', 'state']), 422, 'Esta ação aceita apenas campos da classificação.');
|
abort_if(array_diff(array_keys($input), ['action', 'version_no', 'reason', 'rows', 'hash', 'state']) !== [], 422, 'Esta ação aceita apenas campos da classificação.');
|
||||||
|
|
||||||
return DB::transaction(function () use ($actor, $id, $data) {
|
return DB::transaction(function () use ($actor, $id, $data) {
|
||||||
$business = app(BusinessRepository::class)->find($id, true);
|
$business = app(BusinessRepository::class)->find($id, true);
|
||||||
$action = $data['action'];
|
$action = $data['action'];
|
||||||
Gate::forUser($actor)->authorize(match ($action) { 'prepare' => 'prepareClassification', 'review' => 'reviewClassification', default => 'discloseClassification' }, $business);
|
Gate::forUser($actor)->authorize(match ($action) {
|
||||||
|
'prepare' => 'prepareClassification', 'review' => 'reviewClassification', default => 'discloseClassification'
|
||||||
|
}, $business);
|
||||||
abort_unless($business->version_no === (int) $data['version_no'], 409, 'A versão mudou. Atualize antes de decidir; preserve os valores preparados.');
|
abort_unless($business->version_no === (int) $data['version_no'], 409, 'A versão mudou. Atualize antes de decidir; preserve os valores preparados.');
|
||||||
$state = $this->context($business);
|
$state = $this->context($business);
|
||||||
if ($action === 'prepare') {
|
if ($action === 'prepare') {
|
||||||
$this->validateRows($data['rows'], $business);
|
$this->validateRows($data['rows'], $business);
|
||||||
$state['relations'] = $data['rows'];
|
$state['relations'] = $data['rows'];
|
||||||
foreach ($data['rows'] as $row) { $state['authors'][$this->hash($row)] ??= $actor->id; }
|
foreach ($data['rows'] as $row) {
|
||||||
|
$state['authors'][$this->hash($row)] ??= $actor->id;
|
||||||
|
}
|
||||||
} elseif ($action === 'review') {
|
} elseif ($action === 'review') {
|
||||||
$search = in_array($data['state'], ['revoked', 'archived'], true) ? [...$state['relations'], ...$state['publication']] : $state['relations'];
|
$search = in_array($data['state'], ['revoked', 'archived'], true) ? [...$state['relations'], ...$state['publication']] : $state['relations'];
|
||||||
$row = collect($search)->first(fn ($r) => hash_equals($this->hash($r), $data['hash']));
|
$row = collect(StructuredData::collectionItems($search))->first(fn ($r) => hash_equals($this->hash($r), $data['hash']));
|
||||||
abort_unless($row, 409, 'Associação inexistente nesta versão.');
|
abort_unless($row, 409, 'Associação inexistente nesta versão.');
|
||||||
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
$dimension = OpportunityClassification::TARGETS[$row['classification']['target_type']][2];
|
||||||
abort_unless(app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
|
abort_unless(app(ExistingBusinessPolicy::class)->classificationReviewerScope($actor, $business, $dimension)
|
||||||
&& (int) ($state['authors'][$data['hash']] ?? 0) !== (int) $actor->id, 403, 'Revisão exige responsabilidade e independência aplicáveis.');
|
&& (int) ($state['authors'][$data['hash']] ?? 0) !== (int) $actor->id, 403, 'Revisão exige responsabilidade e independência aplicáveis.');
|
||||||
if ($data['state'] === 'confirmed') { $this->validateRows([$row], $business, true); }
|
if ($data['state'] === 'confirmed') {
|
||||||
|
$this->validateRows([$row], $business, true);
|
||||||
|
}
|
||||||
$prior = $state['decisions'][$data['hash']] ?? [];
|
$prior = $state['decisions'][$data['hash']] ?? [];
|
||||||
$decision = ['state' => $data['state'], 'actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => $data['reason'],
|
$decision = ['state' => $data['state'], 'actor_id' => $actor->id, 'at' => now()->toIso8601String(), 'reason' => $data['reason'],
|
||||||
'evidence_hash' => $this->evidenceHash($row, $business), 'version' => ($prior['version'] ?? 0) + 1];
|
'evidence_hash' => $this->evidenceHash($row, $business), 'version' => ($prior['version'] ?? 0) + 1];
|
||||||
@@ -216,21 +262,35 @@ class ExistingBusinessClassification
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed>|null $preparedState
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function publicRows(ExistingBusiness $business, ?array $preparedState = null): array
|
public function publicRows(ExistingBusiness $business, ?array $preparedState = null): array
|
||||||
{
|
{
|
||||||
if ($business->trashed() || $business->status !== 'published' || ! $business->published_at || $business->published_at->isFuture()
|
if ($business->trashed() || $business->status !== 'published' || ! $business->published_at || $business->published_at->isFuture()
|
||||||
|| ($business->expires_at && $business->expires_at->isBefore(today()))) { return []; }
|
|| ($business->expires_at && $business->expires_at->isBefore(today()))) {
|
||||||
$state = $preparedState ?? $this->context($business); $rows = [];
|
return [];
|
||||||
|
}
|
||||||
|
$state = $preparedState ?? $this->context($business);
|
||||||
|
$rows = [];
|
||||||
foreach ($state['publication'] as $row) {
|
foreach ($state['publication'] as $row) {
|
||||||
$c = $row['classification']; $kind = $c['target_type'];
|
$c = $row['classification'];
|
||||||
if (($c['disclosure'] ?? '') !== 'public' || ! isset(OpportunityClassification::TARGETS[$kind])) { continue; }
|
$kind = $c['target_type'];
|
||||||
|
if (($c['disclosure'] ?? '') !== 'public' || ! isset(OpportunityClassification::TARGETS[$kind])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
$target = app(OpportunityClassification::class)->targets($kind)->where('id', $row['related_id'])->first();
|
$target = app(OpportunityClassification::class)->targets($kind)->where('id', $row['related_id'])->first();
|
||||||
if (! $target || (! empty($c['valid_from']) && $c['valid_from'] > today()->toDateString()) || (! empty($c['valid_until']) && $c['valid_until'] < today()->toDateString())) { continue; }
|
if (! $target || (! empty($c['valid_from']) && $c['valid_from'] > today()->toDateString()) || (! empty($c['valid_until']) && $c['valid_until'] < today()->toDateString())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
$effective = $this->effective($business, $row, $state);
|
$effective = $this->effective($business, $row, $state);
|
||||||
if (in_array($effective, ['archived', 'revoked'], true)) { continue; }
|
if (in_array($effective, ['archived', 'revoked'], true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
$rows[] = ['dimension' => OpportunityClassification::TARGETS[$kind][2], 'target_type' => $kind, 'target_id' => (string) $row['related_id'],
|
$rows[] = ['dimension' => OpportunityClassification::TARGETS[$kind][2], 'target_type' => $kind, 'target_id' => (string) $row['related_id'],
|
||||||
'label' => $target->{OpportunityClassification::TARGETS[$kind][1]}, 'target_code' => $target->code ?? null,
|
'label' => $target->{OpportunityClassification::TARGETS[$kind][1]}, 'target_code' => $target->code ?? null,
|
||||||
'reference_path' => $kind === 'activity' ? (app(EconomicReferenceCatalog::class)->activities()->firstWhere('id', $target->id)?->path ?? []) : [], 'purpose' => $c['purpose'], 'purpose_label' => OpportunityClassification::PURPOSES[$c['purpose']],
|
'reference_path' => $kind === 'activity' ? (app(EconomicReferenceCatalog::class)->activities()->firstWhere('id', $target->id)->path ?? []) : [], 'purpose' => $c['purpose'], 'purpose_label' => OpportunityClassification::PURPOSES[$c['purpose']],
|
||||||
'state' => $effective, 'source_reference' => $c['source_reference'] ?? null, 'citation' => $c['citation'] ?? null,
|
'state' => $effective, 'source_reference' => $c['source_reference'] ?? null, 'citation' => $c['citation'] ?? null,
|
||||||
'authority_id' => $c['authority_id'] ?? null, 'production_stage' => $c['production_stage'] ?? null,
|
'authority_id' => $c['authority_id'] ?? null, 'production_stage' => $c['production_stage'] ?? null,
|
||||||
'external_status' => $c['external_status'], 'valid_from' => $c['valid_from'] ?? null, 'valid_until' => $c['valid_until'] ?? null];
|
'external_status' => $c['external_status'], 'valid_from' => $c['valid_from'] ?? null, 'valid_until' => $c['valid_until'] ?? null];
|
||||||
@@ -239,6 +299,9 @@ class ExistingBusinessClassification
|
|||||||
return $rows;
|
return $rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function filterRules(): array
|
public function filterRules(): array
|
||||||
{
|
{
|
||||||
return ['association_type' => ['nullable', Rule::in(array_keys(OpportunityClassification::TARGETS))],
|
return ['association_type' => ['nullable', Rule::in(array_keys(OpportunityClassification::TARGETS))],
|
||||||
@@ -247,25 +310,41 @@ class ExistingBusinessClassification
|
|||||||
'chain_id' => ['nullable', 'uuid'], 'authority_id' => ['nullable', 'uuid'], 'subsector_id' => ['nullable', 'uuid']];
|
'chain_id' => ['nullable', 'uuid'], 'authority_id' => ['nullable', 'uuid'], 'subsector_id' => ['nullable', 'uuid']];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $filters
|
||||||
|
* @param Builder<ExistingBusiness> $query
|
||||||
|
*/
|
||||||
public function constrain(Builder $query, array $filters): void
|
public function constrain(Builder $query, array $filters): void
|
||||||
{
|
{
|
||||||
$filters = array_filter(array_intersect_key($filters, $this->filterRules()), fn ($v) => $v !== null && $v !== '');
|
$filters = array_filter(array_intersect_key($filters, $this->filterRules()), fn ($v) => $v !== null && $v !== '');
|
||||||
if ($filters === []) { return; }
|
if ($filters === []) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
$ids = [];
|
$ids = [];
|
||||||
(clone $query)->reorder()->select('existing_businesses.*')->chunkById(200, function ($records) use ($filters, &$ids) {
|
(clone $query)->reorder()->select('existing_businesses.*')->chunkById(200, function ($records) use ($filters, &$ids) {
|
||||||
foreach ($records as $business) {
|
foreach ($records as $business) {
|
||||||
$rows = $this->publicRows($business); $same = array_intersect_key($filters, array_flip(['association_type', 'association_target', 'association_purpose', 'association_state']));
|
$rows = $this->publicRows($business);
|
||||||
|
$same = array_intersect_key($filters, array_flip(['association_type', 'association_target', 'association_purpose', 'association_state']));
|
||||||
$matches = ! $same || collect($rows)->contains(function ($row) use ($same) {
|
$matches = ! $same || collect($rows)->contains(function ($row) use ($same) {
|
||||||
foreach (['association_type' => 'target_type', 'association_target' => 'target_id', 'association_purpose' => 'purpose', 'association_state' => 'state'] as $key => $field) {
|
foreach (['association_type' => 'target_type', 'association_target' => 'target_id', 'association_purpose' => 'purpose', 'association_state' => 'state'] as $key => $field) {
|
||||||
if (isset($same[$key]) && $same[$key] !== $row[$field]) { return false; }
|
if (isset($same[$key]) && $same[$key] !== $row[$field]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
foreach (['chain_id' => 'chain', 'subsector_id' => 'activity'] as $key => $type) {
|
foreach (['chain_id' => 'chain', 'subsector_id' => 'activity'] as $key => $type) {
|
||||||
if (! empty($filters[$key])) { $matches = $matches && collect($rows)->contains(fn ($r) => $r['target_type'] === $type && $r['target_id'] === $filters[$key]); }
|
if (! empty($filters[$key])) {
|
||||||
|
$matches = $matches && collect($rows)->contains(fn ($r) => $r['target_type'] === $type && $r['target_id'] === $filters[$key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! empty($filters['authority_id'])) {
|
||||||
|
$matches = $matches && collect($rows)->contains(fn ($r) => ($r['authority_id'] ?? null) === $filters['authority_id']);
|
||||||
|
}
|
||||||
|
if ($matches) {
|
||||||
|
$ids[] = $business->id;
|
||||||
}
|
}
|
||||||
if (! empty($filters['authority_id'])) { $matches = $matches && collect($rows)->contains(fn ($r) => ($r['authority_id'] ?? null) === $filters['authority_id']); }
|
|
||||||
if ($matches) { $ids[] = $business->id; }
|
|
||||||
}
|
}
|
||||||
}, 'existing_businesses.id', 'id');
|
}, 'existing_businesses.id', 'id');
|
||||||
$query->whereIn('existing_businesses.id', $ids);
|
$query->whereIn('existing_businesses.id', $ids);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Services;
|
namespace App\Services;
|
||||||
|
|
||||||
use App\Models\ExistingBusiness;
|
use App\Models\ExistingBusiness;
|
||||||
@@ -9,28 +10,28 @@ final class ExistingBusinessProfileCategory
|
|||||||
// Exact catalogue correspondences plus the explicit mappings already present
|
// Exact catalogue correspondences plus the explicit mappings already present
|
||||||
// in BusinessWizard and the transaction variants in OpportunityCategoryFields.
|
// in BusinessWizard and the transaction variants in OpportunityCategoryFields.
|
||||||
public const MAP = [
|
public const MAP = [
|
||||||
'company_sale'=>'business_sale', 'participation_sale'=>'business_sale',
|
'company_sale' => 'business_sale', 'participation_sale' => 'business_sale',
|
||||||
'buyer_search'=>'business_sale', 'succession'=>'business_sale',
|
'buyer_search' => 'business_sale', 'succession' => 'business_sale',
|
||||||
'franchise'=>'franchise', 'real_estate'=>'real_estate', 'land_right'=>'land_rights',
|
'franchise' => 'franchise', 'real_estate' => 'real_estate', 'land_right' => 'land_rights',
|
||||||
'investment_project'=>'investment_project', 'expansion'=>'investment_project',
|
'investment_project' => 'investment_project', 'expansion' => 'investment_project',
|
||||||
'internationalization'=>'investment_project', 'agricultural_investment'=>'investment_project',
|
'internationalization' => 'investment_project', 'agricultural_investment' => 'investment_project',
|
||||||
'business_partnership'=>'business_partnership', 'strategic_partner'=>'business_partnership',
|
'business_partnership' => 'business_partnership', 'strategic_partner' => 'business_partnership',
|
||||||
'joint_venture'=>'business_partnership', 'capital_increase'=>'financing',
|
'joint_venture' => 'business_partnership', 'capital_increase' => 'financing',
|
||||||
'financial_investor'=>'financing', 'financing_request'=>'financing',
|
'financial_investor' => 'financing', 'financing_request' => 'financing',
|
||||||
'concession_opportunity'=>'concession', 'supply_opportunity'=>'supply',
|
'concession_opportunity' => 'concession', 'supply_opportunity' => 'supply',
|
||||||
];
|
];
|
||||||
|
|
||||||
// Native form types are separate from the persisted modality. No default to a project.
|
// Native form types are separate from the persisted modality. No default to a project.
|
||||||
public const FORM_TYPES = [
|
public const FORM_TYPES = [
|
||||||
'investment_project'=>'investment_project', 'company_sale'=>'company_sale',
|
'investment_project' => 'investment_project', 'company_sale' => 'company_sale',
|
||||||
'asset_sale'=>'asset_sale', 'business_partnership'=>'business_partnership',
|
'asset_sale' => 'asset_sale', 'business_partnership' => 'business_partnership',
|
||||||
'financing_request'=>'financing_request', 'concession_opportunity'=>'concession_opportunity',
|
'financing_request' => 'financing_request', 'concession_opportunity' => 'concession_opportunity',
|
||||||
'supply_opportunity'=>'supply_opportunity', 'participation_sale'=>'company_sale',
|
'supply_opportunity' => 'supply_opportunity', 'participation_sale' => 'company_sale',
|
||||||
'asset_lease'=>'asset_sale', 'capital_increase'=>'financing_request',
|
'asset_lease' => 'asset_sale', 'capital_increase' => 'financing_request',
|
||||||
'financial_investor'=>'financing_request', 'strategic_partner'=>'business_partnership',
|
'financial_investor' => 'financing_request', 'strategic_partner' => 'business_partnership',
|
||||||
'joint_venture'=>'business_partnership', 'expansion'=>'investment_project',
|
'joint_venture' => 'business_partnership', 'expansion' => 'investment_project',
|
||||||
'agricultural_investment'=>'investment_project', 'internationalization'=>'investment_project',
|
'agricultural_investment' => 'investment_project', 'internationalization' => 'investment_project',
|
||||||
'buyer_search'=>'company_sale', 'succession'=>'company_sale',
|
'buyer_search' => 'company_sale', 'succession' => 'company_sale',
|
||||||
];
|
];
|
||||||
|
|
||||||
public static function category(ExistingBusiness $business): ?string
|
public static function category(ExistingBusiness $business): ?string
|
||||||
|
|||||||
@@ -38,6 +38,9 @@ final class FintechInvestment
|
|||||||
|
|
||||||
public function __construct(private readonly VirtualDesk $desk) {}
|
public function __construct(private readonly VirtualDesk $desk) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $input
|
||||||
|
*/
|
||||||
public function save(User $actor, string $id, array $input): void
|
public function save(User $actor, string $id, array $input): void
|
||||||
{
|
{
|
||||||
$keys = implode(',', array_keys(self::FIELDS));
|
$keys = implode(',', array_keys(self::FIELDS));
|
||||||
@@ -89,6 +92,9 @@ final class FintechInvestment
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $value
|
||||||
|
*/
|
||||||
private function fingerprint(array $value): string
|
private function fingerprint(array $value): string
|
||||||
{
|
{
|
||||||
$canonical = function ($v) use (&$canonical) {
|
$canonical = function ($v) use (&$canonical) {
|
||||||
@@ -105,6 +111,10 @@ final class FintechInvestment
|
|||||||
return hash('sha256', json_encode($canonical($value), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
return hash('sha256', json_encode($canonical($value), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $record
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function reviewFingerprints(array $record): array
|
public function reviewFingerprints(array $record): array
|
||||||
{
|
{
|
||||||
$profile = $record['profile'] ?? [];
|
$profile = $record['profile'] ?? [];
|
||||||
@@ -121,6 +131,11 @@ final class FintechInvestment
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $payload
|
||||||
|
* @param array<array-key, mixed> $steps
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function adjustSteps(array $payload, array $steps): array
|
public function adjustSteps(array $payload, array $steps): array
|
||||||
{
|
{
|
||||||
$record = $payload['investor_path']['fintech'] ?? null;
|
$record = $payload['investor_path']['fintech'] ?? null;
|
||||||
@@ -145,6 +160,11 @@ final class FintechInvestment
|
|||||||
return $steps;
|
return $steps;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $payload
|
||||||
|
* @param array<array-key, mixed> $steps
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function view(array $payload, array $steps): array
|
public function view(array $payload, array $steps): array
|
||||||
{
|
{
|
||||||
$record = $payload['investor_path']['fintech'] ?? null;
|
$record = $payload['investor_path']['fintech'] ?? null;
|
||||||
@@ -174,7 +194,7 @@ final class FintechInvestment
|
|||||||
|
|
||||||
return ['guidance' => $guidance, 'guidance_version' => InvestorGuidanceRules::VERSION, 'schema' => self::VERSION, 'record' => $record, 'fields' => self::FIELDS, 'activities' => self::ACTIVITIES, 'countries' => app(CountryCatalogue::class)->all(),
|
return ['guidance' => $guidance, 'guidance_version' => InvestorGuidanceRules::VERSION, 'schema' => self::VERSION, 'record' => $record, 'fields' => self::FIELDS, 'activities' => self::ACTIVITIES, 'countries' => app(CountryCatalogue::class)->all(),
|
||||||
'requirements' => $requirements, 'documents' => $docs, 'review_fingerprints' => $record ? $this->reviewFingerprints($record) : [],
|
'requirements' => $requirements, 'documents' => $docs, 'review_fingerprints' => $record ? $this->reviewFingerprints($record) : [],
|
||||||
'affected_reviews' => array_values(array_column(array_filter($steps,fn ($s) => $s['fintech_review_required'] ?? false), 'code')),
|
'affected_reviews' => array_column(array_filter($steps, fn ($s) => $s['fintech_review_required'] ?? false), 'code'),
|
||||||
'limits' => ['Fintech é caracterização do investimento, não nova categoria jurídica ou autorização.', 'Preparação de orçamento, tecnologia, documentos e parceiros pode avançar em paralelo.', 'Países de operação não alteram país mestre, origem, nacionalidade ou residências.', 'Capitais mínimos, taxas, prazos e licenças específicos permanecem por determinar sem disposição e período aplicáveis.']];
|
'limits' => ['Fintech é caracterização do investimento, não nova categoria jurídica ou autorização.', 'Preparação de orçamento, tecnologia, documentos e parceiros pode avançar em paralelo.', 'Países de operação não alteram país mestre, origem, nacionalidade ou residências.', 'Capitais mínimos, taxas, prazos e licenças específicos permanecem por determinar sem disposição e período aplicáveis.']];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ final class InterestWorkflow
|
|||||||
|
|
||||||
return DB::transaction(function () use ($actor, $interest, $status, $note, $nextAction, $dueAt, $assigneeId, $assignmentProvided, $actionProvided) {
|
return DB::transaction(function () use ($actor, $interest, $status, $note, $nextAction, $dueAt, $assigneeId, $assignmentProvided, $actionProvided) {
|
||||||
$locked = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id);
|
$locked = InterestRequest::query()->lockForUpdate()->findOrFail($interest->id);
|
||||||
abort_unless(app(ScopedPortalAdministration::class)->interest($actor,$locked),403);
|
abort_unless(app(ScopedPortalAdministration::class)->interest($actor, $locked), 403);
|
||||||
$from = $locked->status;
|
$from = $locked->status;
|
||||||
$actionDate = $dueAt ? Carbon::parse($dueAt)->toDateString() : null;
|
$actionDate = $dueAt ? Carbon::parse($dueAt)->toDateString() : null;
|
||||||
$followUpChanged = ($actionProvided && ($locked->next_action !== $nextAction
|
$followUpChanged = ($actionProvided && ($locked->next_action !== $nextAction
|
||||||
|
|||||||
@@ -5,9 +5,15 @@ namespace App\Services;
|
|||||||
use App\Http\Controllers\InvestmentPortfolioController;
|
use App\Http\Controllers\InvestmentPortfolioController;
|
||||||
use App\Models\InvestmentDossier;
|
use App\Models\InvestmentDossier;
|
||||||
use App\Models\Opportunity;
|
use App\Models\Opportunity;
|
||||||
|
use App\Models\Sector;
|
||||||
|
use App\Support\StructuredData;
|
||||||
use Illuminate\Database\Eloquent\Builder;
|
use Illuminate\Database\Eloquent\Builder;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
|
||||||
class InvestmentCatalogue
|
class InvestmentCatalogue
|
||||||
{
|
{
|
||||||
@@ -17,8 +23,8 @@ class InvestmentCatalogue
|
|||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
public function filters(Request $request): array
|
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'))],
|
'preparation' => ['nullable', Rule::in(array_column(OpportunityMaturity::searchOptions(), 'value'))],
|
||||||
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
'opportunity_id' => ['nullable', 'integer', 'min:1'],
|
||||||
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
|
||||||
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
|
'include_national' => ['nullable', 'boolean'], 'territory_basis' => ['nullable', 'in:all,direct,context'],
|
||||||
@@ -26,7 +32,7 @@ class InvestmentCatalogue
|
|||||||
'cluster_id' => ['nullable', 'uuid'], 'corridor_id' => ['nullable', 'uuid'], 'project_id' => ['nullable', 'uuid'],
|
'cluster_id' => ['nullable', 'uuid'], 'corridor_id' => ['nullable', 'uuid'], 'project_id' => ['nullable', 'uuid'],
|
||||||
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
|
'geo_location_id' => ['nullable', 'uuid'], 'education' => ['nullable', 'boolean'],
|
||||||
'zee_id' => ['nullable', 'uuid'], 'zfi_id' => ['nullable', 'uuid'], 'park_id' => ['nullable', 'uuid'],
|
'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'],
|
'maturity_level' => ['nullable', 'integer', 'between:1,8'], 'facets' => ['nullable', 'array', 'max:20'], 'facets.*' => ['integer', 'min:1'],
|
||||||
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
'min_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999'],
|
||||||
'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])],
|
'max_amount' => ['nullable', 'numeric', 'min:0', 'max:999999999999', ...($request->filled('min_amount') ? ['gte:min_amount'] : [])],
|
||||||
@@ -40,14 +46,15 @@ class InvestmentCatalogue
|
|||||||
'category' => ['nullable', 'in:'.implode(',', OpportunityManagement::CATEGORIES)],
|
'category' => ['nullable', 'in:'.implode(',', OpportunityManagement::CATEGORIES)],
|
||||||
'publication_state' => ['nullable', 'in:published'],
|
'publication_state' => ['nullable', 'in:published'],
|
||||||
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
'per_page' => ['nullable', 'integer', 'between:1,50'], 'page' => ['nullable', 'integer', 'min:1']]);
|
||||||
|
$filters = app(InvestmentGeography::class)->provinceSearch($filters);
|
||||||
app(InvestmentGeography::class)->selection($filters);
|
app(InvestmentGeography::class)->selection($filters);
|
||||||
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
|
$aliases = ['park' => 'park_id', 'cluster' => 'cluster_id', 'corridor' => 'corridor_id', 'project' => 'project_id'];
|
||||||
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
|
$alias = $aliases[$filters['association_type'] ?? ''] ?? null;
|
||||||
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
|
if ($alias && ! empty($filters['association_target']) && empty($filters['association_purpose']) && empty($filters['association_state'])) {
|
||||||
if (! empty($filters[$alias]) && $filters[$alias] !== $filters['association_target']) {
|
if (! empty($filters[$alias]) && $filters[$alias] !== $filters['association_target']) {
|
||||||
throw \Illuminate\Validation\ValidationException::withMessages([$alias => 'Foram indicadas duas selecções diferentes para o mesmo filtro. Escolha apenas uma.']);
|
throw ValidationException::withMessages([$alias => 'Foram indicadas duas selecções diferentes para o mesmo filtro. Escolha apenas uma.']);
|
||||||
}
|
}
|
||||||
if (\Illuminate\Support\Str::isUuid($filters['association_target'])) {
|
if (Str::isUuid($filters['association_target'])) {
|
||||||
$filters[$alias] = $filters['association_target'];
|
$filters[$alias] = $filters['association_target'];
|
||||||
unset($filters['association_type'], $filters['association_target']);
|
unset($filters['association_type'], $filters['association_target']);
|
||||||
}
|
}
|
||||||
@@ -62,14 +69,22 @@ class InvestmentCatalogue
|
|||||||
*/
|
*/
|
||||||
public function query(array $filters): Builder
|
public function query(array $filters): Builder
|
||||||
{
|
{
|
||||||
|
$filters = app(InvestmentGeography::class)->provinceSearch($filters);
|
||||||
$query = Opportunity::published()->with('sector:id,name,slug');
|
$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);
|
$associated = $this->publicAssociatedIds($filters);
|
||||||
if (($filters['territory_basis'] ?? 'all') === 'direct') {
|
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')));
|
$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') {
|
} 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->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()))
|
$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'])) {
|
if (! empty($filters['opportunity_id'])) {
|
||||||
$query->whereKey($filters['opportunity_id']);
|
$query->whereKey($filters['opportunity_id']);
|
||||||
@@ -78,12 +93,18 @@ class InvestmentCatalogue
|
|||||||
$includeNational = filter_var($filters['include_national'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
$includeNational = filter_var($filters['include_national'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||||
if ($path !== []) {
|
if ($path !== []) {
|
||||||
$ids = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
|
$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)
|
$territory->whereIn('opportunities.primary_territory_id', $ids)
|
||||||
->orWhereExists(fn ($locations) => $locations->selectRaw('1')->from('opportunity_locations as territory_link')
|
->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));
|
->whereColumn('territory_link.opportunity_id', 'opportunities.id')->whereIn('territory_link.geo_location_id', $ids));
|
||||||
|
if (count($path) === 1) {
|
||||||
|
$this->declaredProvince($territory, $path[0]->name);
|
||||||
|
}
|
||||||
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
||||||
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
|
app(InvestmentRelations::class)->opportunityTerritories($territory, $ids);
|
||||||
|
if (count($path) === 1) {
|
||||||
|
$this->approvedCorridorProvince($territory, $path[0]->id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ($includeNational) {
|
if ($includeNational) {
|
||||||
$territory->orWhere('opportunities.geography_scope', 'national');
|
$territory->orWhere('opportunities.geography_scope', 'national');
|
||||||
@@ -158,8 +179,15 @@ class InvestmentCatalogue
|
|||||||
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
|
->join('geo_locations as target', 'target.id', '=', 'link.geo_location_id')
|
||||||
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
|
->whereColumn('link.opportunity_id', 'opportunities.id')->whereIn('link.geo_location_id', $locationIds ?? [])
|
||||||
->whereNull('target.deleted_at')->where('target.data_classification', 'public'));
|
->whereNull('target.deleted_at')->where('target.data_classification', 'public'));
|
||||||
|
$province = app(InvestmentGeography::class)->publicReferences()->where('id', $filters['geo_location_id'])->where('location_type', 'province')->first(['name']);
|
||||||
|
if ($province) {
|
||||||
|
$this->declaredProvince($matches, $province->name);
|
||||||
|
}
|
||||||
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
if (($filters['territory_basis'] ?? 'all') !== 'direct') {
|
||||||
app(InvestmentRelations::class)->opportunityTerritories($matches, $locationIds ?? []);
|
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']);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -198,7 +226,9 @@ class InvestmentCatalogue
|
|||||||
if (! empty($filters['before'])) {
|
if (! empty($filters['before'])) {
|
||||||
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before']));
|
$query->whereExists(fn ($sub) => $sub->selectRaw('1')->from('opportunity_profiles')->whereColumn('opportunity_id', 'opportunities.id')->where('target_date', '<=', $filters['before']));
|
||||||
}
|
}
|
||||||
if (! empty($filters['category'])) $query->where('opportunity_category', $filters['category']);
|
if (! empty($filters['category'])) {
|
||||||
|
$query->where('opportunity_category', $filters['category']);
|
||||||
|
}
|
||||||
app(OpportunityClassification::class)->constrain($query, $filters);
|
app(OpportunityClassification::class)->constrain($query, $filters);
|
||||||
$sort = $filters['sort'] ?? 'recent';
|
$sort = $filters['sort'] ?? 'recent';
|
||||||
|
|
||||||
@@ -210,6 +240,60 @@ class InvestmentCatalogue
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Opportunity> $query */
|
||||||
|
private function declaredProvince(Builder $query, string $name): void
|
||||||
|
{
|
||||||
|
// Read the published province declaration only when no more precise territory contradicts it.
|
||||||
|
// This does not assign any canonical ID, district, post, locality or coordinates to the record.
|
||||||
|
$query->orWhere(fn ($declared) => $declared->whereNull('opportunities.primary_territory_id')
|
||||||
|
->whereNotExists(fn ($links) => $links->selectRaw('1')->from('opportunity_locations')->whereColumn('opportunity_id', 'opportunities.id'))
|
||||||
|
->where('opportunities.geography_scope', '!=', 'national')
|
||||||
|
->whereRaw('lower(btrim(opportunities.province)) = ?', [mb_strtolower(trim($name))]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param Builder<Opportunity> $query */
|
||||||
|
private function approvedCorridorProvince(Builder $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
|
/** @param array<string,mixed> $territoryFilters
|
||||||
* @return array<string,mixed> */
|
* @return array<string,mixed> */
|
||||||
public function references(bool $management = false, array $territoryFilters = []): array
|
public function references(bool $management = false, array $territoryFilters = []): array
|
||||||
@@ -220,9 +304,9 @@ class InvestmentCatalogue
|
|||||||
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
'authorities' => DB::table('authorities')->where('status', 'published')->get(['id', 'label_pt_mz']),
|
||||||
'categories' => OpportunityManagement::CATEGORIES,
|
'categories' => OpportunityManagement::CATEGORIES,
|
||||||
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
'options' => DB::table('investment_reference_options')->when(! $management, fn ($q) => $q->where('active', true))->orderBy('sort_order')->orderBy('label')->get(),
|
||||||
'sectors' => \App\Models\Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name', 'slug']),
|
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name', 'slug']),
|
||||||
'maturityCatalogue' => ['version'=>OpportunityMaturity::VERSION, 'stages'=>OpportunityMaturity::STAGES,
|
'maturityCatalogue' => ['version' => OpportunityMaturity::VERSION, 'stages' => OpportunityMaturity::STAGES,
|
||||||
'legacyVersion'=>OpportunityMaturity::LEGACY, 'legacyLabels'=>OpportunityMaturity::LEGACY_LABELS]];
|
'legacyVersion' => OpportunityMaturity::LEGACY, 'legacyLabels' => OpportunityMaturity::LEGACY_LABELS]];
|
||||||
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
foreach (self::RELATIONS as $relation => [$foreign, $table]) {
|
||||||
$query = DB::table($table)->whereNull('deleted_at');
|
$query = DB::table($table)->whereNull('deleted_at');
|
||||||
if (! $management) {
|
if (! $management) {
|
||||||
@@ -231,67 +315,86 @@ class InvestmentCatalogue
|
|||||||
} elseif (in_array($relation, ['clusters', 'corridors'], true)) {
|
} elseif (in_array($relation, ['clusters', 'corridors'], true)) {
|
||||||
$query->whereIn('id', $this->publicStructureIds($relation, $foreign));
|
$query->whereIn('id', $this->publicStructureIds($relation, $foreign));
|
||||||
} else {
|
} 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') {
|
if (! $management && $path !== [] && $relation !== 'locations') {
|
||||||
$dossiers = InvestmentPortfolioController::visible();
|
$dossiers = InvestmentPortfolioController::visible();
|
||||||
app(InvestmentGeography::class)->constrainDossiersToTerritories($dossiers,
|
app(InvestmentGeography::class)->constrainDossiersToTerritories($dossiers,
|
||||||
app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id));
|
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']);
|
$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();
|
$zones = app(InvestmentZones::class)->visible();
|
||||||
if (! $management && $territoryFilters !== []) {
|
if (! $management && $territoryFilters !== []) {
|
||||||
// Opportunity words/modalities are not names/categories of zones.
|
// Opportunity words/modalities are not names/categories of zones.
|
||||||
$zones = app(InvestmentZones::class)->search(\Illuminate\Support\Arr::only($territoryFilters,
|
$zones = app(InvestmentZones::class)->search(Arr::only($territoryFilters,
|
||||||
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
|
['province_id', 'district_id', 'admin_post_id', 'locality_id', 'province', 'district', 'geo_location_id']));
|
||||||
}
|
}
|
||||||
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
$result['zones'] = $zones->orderBy('name')->get(['id', 'name', 'category']);
|
||||||
if (! $management && ($path !== [] || ! empty($territoryFilters['sector']))) {
|
if (! $management && $path !== []) {
|
||||||
$scope = \Illuminate\Support\Arr::only($territoryFilters, ['sector','province_id','district_id','admin_post_id','locality_id','include_national']);
|
// A chain's documented scope comes from its public cluster, never
|
||||||
$available = ['chain' => [], 'activity' => []];
|
// from the opportunities surviving the current search.
|
||||||
$this->query($scope)->reorder()->chunkById(200, function ($records) use (&$available) {
|
$ids = app(OpportunityClassification::class)->targets('chain')
|
||||||
foreach ($records as $record) {
|
->whereIn('cluster_id', ($result['clusters'] ?? collect())->pluck('id'))->pluck('id');
|
||||||
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
$result['classification']['targets']['chain'] = collect(StructuredData::collectionItems($result['classification']['targets']['chain']))->whereIn('id', $ids)->values();
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
// Activities are a public classification catalogue, not evidence of
|
||||||
|
// investment availability in a territory or sector.
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $filters
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
private function publicAssociatedIds(array $filters): array
|
private function publicAssociatedIds(array $filters): array
|
||||||
{
|
{
|
||||||
$kinds = ['park_id' => ['park'], 'zee_id' => ['zone'], 'zfi_id' => ['zone'],
|
$kinds = ['park_id' => ['park'], 'zee_id' => ['zone'], 'zfi_id' => ['zone'],
|
||||||
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
|
'cluster_id' => ['cluster'], 'corridor_id' => ['corridor'], 'project_id' => ['project']];
|
||||||
$selected = array_filter(array_intersect_key($filters, $kinds));
|
$selected = array_filter(array_intersect_key($filters, $kinds));
|
||||||
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $key => $category) {
|
foreach (['zee_id' => 'zee', 'zfi_id' => 'zfi', 'park_id' => 'industrial_park'] as $key => $category) {
|
||||||
if (isset($selected[$key]) && ! app(InvestmentZones::class)->visible()->whereKey($selected[$key])->where('category', $category)->exists()) unset($selected[$key]);
|
if (isset($selected[$key]) && ! app(InvestmentZones::class)->visible()->whereKey($selected[$key])->where('category', $category)->exists()) {
|
||||||
|
unset($selected[$key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($selected === []) {
|
||||||
|
return [];
|
||||||
}
|
}
|
||||||
if ($selected === []) return [];
|
|
||||||
$ids = [];
|
$ids = [];
|
||||||
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
|
Opportunity::published()->select('opportunities.*')->chunkById(200, function ($records) use ($selected, $kinds, &$ids) {
|
||||||
foreach ($records as $record) {
|
foreach ($records as $record) {
|
||||||
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
foreach (app(OpportunityClassification::class)->publicRows($record) as $row) {
|
||||||
if (in_array($row['purpose'], ['proximity', 'administrative_boundary'], true) || $row['state'] === 'rejected') continue;
|
if (in_array($row['purpose'], ['proximity', 'administrative_boundary'], true) || $row['state'] === 'rejected') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
foreach ($selected as $field => $target) {
|
foreach ($selected as $field => $target) {
|
||||||
if ($row['target_id'] === $target && in_array($row['target_type'], $kinds[$field], true)) $ids[$field][] = $record->id;
|
if ($row['target_id'] === $target && in_array($row['target_type'], $kinds[$field], true)) {
|
||||||
|
$ids[$field][] = $record->id;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
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;
|
return $ids;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,6 +411,21 @@ class InvestmentCatalogue
|
|||||||
/** @return array<string,mixed> */
|
/** @return array<string,mixed> */
|
||||||
public function context(int $id, bool $management = false): array
|
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(),
|
$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')
|
'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'])];
|
->where('f.opportunity_id', $id)->get(['o.id', 'o.group', 'o.label'])];
|
||||||
@@ -411,7 +529,7 @@ class InvestmentCatalogue
|
|||||||
$located = 0;
|
$located = 0;
|
||||||
foreach ($records as $record) {
|
foreach ($records as $record) {
|
||||||
$properties = ['id' => $record->id, 'title' => $record->title, 'category' => $record->sector?->name,
|
$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) {
|
foreach ($relations as $relation => $groups) {
|
||||||
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
|
$properties[$relation] = ($groups->get($record->id) ?? collect())->pluck('name')->unique()->values()->all();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Http\Controllers\InvestmentPortfolioController;
|
||||||
|
use App\Models\Opportunity;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
/** 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'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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')->whereKey(substr($origin, 10))->firstOrFail();
|
||||||
|
$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()->whereKey($reference['id'])->firstOrFail();
|
||||||
|
$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')) {
|
||||||
|
$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) === 1);
|
||||||
|
$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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $input
|
||||||
|
* @param array<array-key, mixed> $previous
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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 (ModelNotFoundException $e) {
|
||||||
|
if (! $old) {
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
$item = null;
|
||||||
|
} catch (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,125 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Support\StructuredData;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
|
|
||||||
|
/** An identified opportunity within the authorised dossier, never the account's last choice. */
|
||||||
|
final class InvestmentConsumerScope
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $context
|
||||||
|
*/
|
||||||
|
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(StructuredData::collectionItems($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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $context
|
||||||
|
* @param array<array-key, mixed> $payload
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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'] ?? [])];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $context
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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(StructuredData::collectionItems($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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $payload
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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,57 @@
|
|||||||
|
<?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';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $context
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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,99 @@
|
|||||||
|
<?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.
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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();
|
||||||
|
if (! (count($records) === count($entry['provinces']))) {
|
||||||
|
abort(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.
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,24 @@ final class InvestmentGeography
|
|||||||
{
|
{
|
||||||
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
public const FIELDS = ['province_id' => 'province', 'district_id' => 'district', 'admin_post_id' => 'admin_post', 'locality_id' => 'locality'];
|
||||||
|
|
||||||
|
/** Resolve an old province-name search only when the public register has exactly one match.
|
||||||
|
* @param array<array-key, mixed> $filters
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function provinceSearch(array $filters): array
|
||||||
|
{
|
||||||
|
if (empty($filters['province_id']) && is_string($filters['province'] ?? null) && trim($filters['province']) !== '') {
|
||||||
|
$matches = $this->publicReferences()->where('location_type', 'province')
|
||||||
|
->whereRaw('lower(btrim(name)) = ?', [mb_strtolower(trim($filters['province']))])->limit(2)->get(['id']);
|
||||||
|
if ($matches->count() === 1) {
|
||||||
|
$filters['province_id'] = $matches[0]->id;
|
||||||
|
unset($filters['province']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $filters;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Restrict published dossier searches using direct territories and public, validated structure links.
|
* Restrict published dossier searches using direct territories and public, validated structure links.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Services;
|
||||||
|
|
||||||
|
use App\Http\Controllers\InvestmentPortfolioController;
|
||||||
|
use App\Models\Opportunity;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/** Multiple identified references in the existing encrypted investment context. */
|
||||||
|
final class InvestmentOpportunityChoices
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $ids
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
public function portfolioOrigins(array $ids, int $opportunity): array
|
||||||
|
{
|
||||||
|
$origins = [];
|
||||||
|
foreach (array_unique($ids) as $id) {
|
||||||
|
$record = InvestmentPortfolioController::visible()->addSelect('version_no')->whereKey($id)->firstOrFail();
|
||||||
|
$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 !== null, 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.
|
||||||
|
* @param array<array-key, mixed> $entries
|
||||||
|
* @param array<array-key, mixed> $saved
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $choices
|
||||||
|
* @param array<array-key, mixed> $previous
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
|
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::whereKey($ref['id'])->firstOrFail();
|
||||||
|
$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) => 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
namespace App\Services;
|
namespace App\Services;
|
||||||
|
|
||||||
use App\Models\InvestmentZone;
|
use App\Models\InvestmentZone;
|
||||||
|
use App\Support\StructuredData;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
@@ -11,6 +12,7 @@ use Illuminate\Support\Str;
|
|||||||
class InvestmentZoneIntegralDetails
|
class InvestmentZoneIntegralDetails
|
||||||
{
|
{
|
||||||
public const GROUPS = ['titles', 'phases', 'plots', 'occupants', 'observations', 'chains'];
|
public const GROUPS = ['titles', 'phases', 'plots', 'occupants', 'observations', 'chains'];
|
||||||
|
|
||||||
public const EXTRA = [
|
public const EXTRA = [
|
||||||
'titles' => ['kind', 'identifier', 'valid_from', 'valid_until'],
|
'titles' => ['kind', 'identifier', 'valid_from', 'valid_until'],
|
||||||
'phases' => ['code', 'status', 'starts_at', 'ends_at', 'expansion'],
|
'phases' => ['code', 'status', 'starts_at', 'ends_at', 'expansion'],
|
||||||
@@ -19,79 +21,179 @@ class InvestmentZoneIntegralDetails
|
|||||||
'observations' => ['indicator', 'value', 'unit', 'period_start', 'period_end', 'population', 'methodology', 'phase_id', 'plot_id'],
|
'observations' => ['indicator', 'value', 'unit', 'period_start', 'period_end', 'population', 'methodology', 'phase_id', 'plot_id'],
|
||||||
'chains' => ['kind', 'organization_id', 'documentary_name', 'zone_link_id', 'phase_id', 'plot_id'],
|
'chains' => ['kind', 'organization_id', 'documentary_name', 'zone_link_id', 'phase_id', 'plot_id'],
|
||||||
];
|
];
|
||||||
|
|
||||||
public const COMMON = ['id', 'label', 'label_en', 'description', 'description_en', 'knowledge', 'source_reference', 'source_date', 'scope', 'disclosure', 'private_note', 'support_document_ids'];
|
public const COMMON = ['id', 'label', 'label_en', 'description', 'description_en', 'knowledge', 'source_reference', 'source_date', 'scope', 'disclosure', 'private_note', 'support_document_ids'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $before
|
||||||
|
* @param array<array-key, mixed> $input
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function merge(InvestmentZone $zone, array $before, array $input): array
|
public function merge(InvestmentZone $zone, array $before, array $input): array
|
||||||
{
|
{
|
||||||
abort_if(array_diff(array_keys($input), ['schema_version', 'remove_ids', ...self::GROUPS]), 422, 'Campo da ficha integral desconhecido.');
|
abort_if(array_diff(array_keys($input), ['schema_version', 'remove_ids', ...self::GROUPS]) !== [], 422, 'Campo da ficha integral desconhecido.');
|
||||||
$rules = ['schema_version' => 'sometimes|in:1', 'remove_ids' => 'sometimes|array:'.implode(',', self::GROUPS)];
|
$rules = ['schema_version' => 'sometimes|in:1', 'remove_ids' => 'sometimes|array:'.implode(',', self::GROUPS)];
|
||||||
foreach (self::GROUPS as $group) {
|
foreach (self::GROUPS as $group) {
|
||||||
$rules[$group] = 'sometimes|array|max:200';
|
$rules[$group] = 'sometimes|array|max:200';
|
||||||
$rules[$group.'.*'] = 'array:'.implode(',', [...self::COMMON, ...self::EXTRA[$group]]);
|
$rules[$group.'.*'] = 'array:'.implode(',', [...self::COMMON, ...self::EXTRA[$group]]);
|
||||||
foreach (['id'=>'nullable|uuid','label'=>'required|string|max:300','label_en'=>'nullable|string|max:300','description'=>'nullable|string|max:3000','description_en'=>'nullable|string|max:3000','knowledge'=>'required|in:unknown,documented,disputed','source_reference'=>'nullable|string|max:2000','source_date'=>'nullable|date_format:Y-m-d','scope'=>'nullable|string|max:500','disclosure'=>'required|boolean','private_note'=>'nullable|string|max:4000','support_document_ids'=>'sometimes|array|max:20','support_document_ids.*'=>'uuid'] as $key=>$rule) $rules[$group.'.*.'.$key]=$rule;
|
foreach (['id' => 'nullable|uuid', 'label' => 'required|string|max:300', 'label_en' => 'nullable|string|max:300', 'description' => 'nullable|string|max:3000', 'description_en' => 'nullable|string|max:3000', 'knowledge' => 'required|in:unknown,documented,disputed', 'source_reference' => 'nullable|string|max:2000', 'source_date' => 'nullable|date_format:Y-m-d', 'scope' => 'nullable|string|max:500', 'disclosure' => 'required|boolean', 'private_note' => 'nullable|string|max:4000', 'support_document_ids' => 'sometimes|array|max:20', 'support_document_ids.*' => 'uuid'] as $key => $rule) {
|
||||||
foreach (self::EXTRA[$group] as $key) $rules[$group.'.*.'.$key]=match ($key) {
|
$rules[$group.'.*.'.$key] = $rule;
|
||||||
'organization_id','phase_id','plot_id','zone_link_id','geometry_id'=>'nullable|uuid',
|
|
||||||
'area'=>'nullable|numeric|min:0|max:999999999999999',
|
|
||||||
'value'=>'nullable|numeric|between:-999999999999999,999999999999999',
|
|
||||||
'starts_at','ends_at','valid_from','valid_until','period_start','period_end'=>'nullable|date_format:Y-m-d',
|
|
||||||
'expansion'=>'nullable|boolean',
|
|
||||||
default=>'nullable|string|max:2000',
|
|
||||||
};
|
|
||||||
$rules['remove_ids.'.$group]='sometimes|array|max:200';$rules['remove_ids.'.$group.'.*']='uuid';
|
|
||||||
}
|
|
||||||
$rules['plots.*.area_unit']='nullable|in:ha,m2';
|
|
||||||
$rules['plots.*.status']='nullable|in:unknown,planned,available_declared,reserved,occupied,construction,inactive';
|
|
||||||
$rules['phases.*.status']='nullable|in:unknown,planned,construction,operational,suspended,closed';
|
|
||||||
$rules['occupants.*.status']='nullable|in:unknown,approved,construction,installed,inactive';
|
|
||||||
$rules['titles.*.kind']='nullable|in:creation,land_use,licence,special_regime,other';
|
|
||||||
$rules['chains.*.kind']='nullable|in:anchor,supplier,unmet_need,other';
|
|
||||||
$rules['observations.*.indicator']='required|in:employment,investment,production,exports,local_procurement,resource_use,waste,emissions,other';
|
|
||||||
$data=Validator::make($input,$rules)->validate();$result=$before;
|
|
||||||
foreach(self::GROUPS as$group){
|
|
||||||
$rows=collect($before[$group]??[])->keyBy('id')->all();$remove=$data['remove_ids'][$group]??[];$seen=[];
|
|
||||||
foreach($data[$group]??[]as$item){
|
|
||||||
$id=$item['id']??(string)Str::uuid();abort_if(in_array($id,$seen,true)||in_array($id,$remove,true),422,'Identificador repetido ou removido na mesma operação.');$seen[]=$id;
|
|
||||||
$item=[...($rows[$id]??[]),...$item,'id'=>$id];
|
|
||||||
if($item['knowledge']!=='unknown')abort_unless(trim($item['source_reference']??'')!=='',422,'Indique a fonte documental ou preserve como desconhecido.');
|
|
||||||
if($item['knowledge']==='unknown')abort_if(isset($item['value'])||isset($item['area']),422,'Quantidade desconhecida deve permanecer vazia, não zero.');
|
|
||||||
if($item['knowledge']==='unknown'&&!empty($item['status']))abort_unless($item['status']==='unknown',422,'Situação operacional declarada exige fonte ou indicação de divergência.');
|
|
||||||
foreach([['starts_at','ends_at'],['valid_from','valid_until'],['period_start','period_end']]as[$a,$b])if(isset($item[$a],$item[$b]))abort_if($item[$b]<$item[$a],422,'Período final anterior ao início.');
|
|
||||||
if($group==='plots'&&isset($item['area']))abort_unless(!empty($item['area_unit'])&&!empty($item['scope']),422,'Área declarada exige unidade e âmbito.');
|
|
||||||
if($group==='plots'&&($item['status']??'')==='available_declared')abort_unless($item['knowledge']==='documented'&&!empty($item['source_date']),422,'Disponibilidade declarada exige fonte e data; não é disponibilidade em tempo real.');
|
|
||||||
if($group==='observations'&&isset($item['value']))abort_unless(!empty($item['unit'])&&!empty($item['period_start'])&&!empty($item['period_end'])&&!empty($item['scope'])&&!empty($item['population']),422,'Indicador numérico exige unidade, período, âmbito e base/população.');
|
|
||||||
if(!empty($item['organization_id']))abort_unless(DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->exists(),422,'Reutilize uma entidade existente.');
|
|
||||||
if(!empty($item['geometry_id']))abort_unless(DB::table('investment_zone_geometries')->where('zone_id',$zone->id)->where('geometry_id',$item['geometry_id'])->exists(),422,'Geometria deve estar associada a este parque; limite administrativo não é perímetro.');
|
|
||||||
if(!empty($item['zone_link_id']))abort_unless(DB::table('investment_zone_links')->where('zone_id',$zone->id)->where('id',$item['zone_link_id'])->exists(),422,'Relação económica deve pertencer a este parque.');
|
|
||||||
foreach($item['support_document_ids']??[]as$doc)abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d','d.id','=','a.document_id')->where('a.zone_id',$zone->id)->where('d.id',$doc)->whereNull('d.deleted_at')->where('d.status','active')->where('d.malware_scan_status','clean')->whereColumn('d.sha256','d.malware_scanned_sha256')->exists(),422,'Suporte deve estar consultável e associado a este parque.');
|
|
||||||
$rows[$id]=$item;
|
|
||||||
}
|
}
|
||||||
foreach($remove as$id){abort_unless(isset($rows[$id]),422,'O detalhe a remover não pertence ao parque.');unset($rows[$id]);}
|
foreach (self::EXTRA[$group] as $key) {
|
||||||
abort_if(count($rows)>200,422,'Limite de detalhes excedido.');$result[$group]=array_values($rows);
|
$rules[$group.'.*.'.$key] = match ($key) {
|
||||||
|
'organization_id','phase_id','plot_id','zone_link_id','geometry_id' => 'nullable|uuid',
|
||||||
|
'area' => 'nullable|numeric|min:0|max:999999999999999',
|
||||||
|
'value' => 'nullable|numeric|between:-999999999999999,999999999999999',
|
||||||
|
'starts_at','ends_at','valid_from','valid_until','period_start','period_end' => 'nullable|date_format:Y-m-d',
|
||||||
|
'expansion' => 'nullable|boolean',
|
||||||
|
default => 'nullable|string|max:2000',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
$rules['remove_ids.'.$group] = 'sometimes|array|max:200';
|
||||||
|
$rules['remove_ids.'.$group.'.*'] = 'uuid';
|
||||||
|
}
|
||||||
|
$rules['plots.*.area_unit'] = 'nullable|in:ha,m2';
|
||||||
|
$rules['plots.*.status'] = 'nullable|in:unknown,planned,available_declared,reserved,occupied,construction,inactive';
|
||||||
|
$rules['phases.*.status'] = 'nullable|in:unknown,planned,construction,operational,suspended,closed';
|
||||||
|
$rules['occupants.*.status'] = 'nullable|in:unknown,approved,construction,installed,inactive';
|
||||||
|
$rules['titles.*.kind'] = 'nullable|in:creation,land_use,licence,special_regime,other';
|
||||||
|
$rules['chains.*.kind'] = 'nullable|in:anchor,supplier,unmet_need,other';
|
||||||
|
$rules['observations.*.indicator'] = 'required|in:employment,investment,production,exports,local_procurement,resource_use,waste,emissions,other';
|
||||||
|
$data = Validator::make($input, $rules)->validate();
|
||||||
|
$result = $before;
|
||||||
|
foreach (self::GROUPS as $group) {
|
||||||
|
$rows = collect(StructuredData::collectionItems($before[$group] ?? []))->keyBy('id')->all();
|
||||||
|
$remove = $data['remove_ids'][$group] ?? [];
|
||||||
|
$seen = [];
|
||||||
|
foreach ($data[$group] ?? [] as $item) {
|
||||||
|
$id = $item['id'] ?? (string) Str::uuid();
|
||||||
|
abort_if(in_array($id, $seen, true) || in_array($id, $remove, true), 422, 'Identificador repetido ou removido na mesma operação.');
|
||||||
|
$seen[] = $id;
|
||||||
|
$item = [...($rows[$id] ?? []), ...$item, 'id' => $id];
|
||||||
|
if ($item['knowledge'] !== 'unknown') {
|
||||||
|
abort_unless(trim($item['source_reference'] ?? '') !== '', 422, 'Indique a fonte documental ou preserve como desconhecido.');
|
||||||
|
}
|
||||||
|
if ($item['knowledge'] === 'unknown') {
|
||||||
|
abort_if(isset($item['value']) || isset($item['area']), 422, 'Quantidade desconhecida deve permanecer vazia, não zero.');
|
||||||
|
}
|
||||||
|
if ($item['knowledge'] === 'unknown' && ! empty($item['status'])) {
|
||||||
|
abort_unless($item['status'] === 'unknown', 422, 'Situação operacional declarada exige fonte ou indicação de divergência.');
|
||||||
|
}
|
||||||
|
foreach ([['starts_at', 'ends_at'], ['valid_from', 'valid_until'], ['period_start', 'period_end']] as [$a,$b]) {
|
||||||
|
if (isset($item[$a],$item[$b])) {
|
||||||
|
abort_if($item[$b] < $item[$a], 422, 'Período final anterior ao início.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($group === 'plots' && isset($item['area'])) {
|
||||||
|
abort_unless(! empty($item['area_unit']) && ! empty($item['scope']), 422, 'Área declarada exige unidade e âmbito.');
|
||||||
|
}
|
||||||
|
if ($group === 'plots' && ($item['status'] ?? '') === 'available_declared') {
|
||||||
|
abort_unless($item['knowledge'] === 'documented' && ! empty($item['source_date']), 422, 'Disponibilidade declarada exige fonte e data; não é disponibilidade em tempo real.');
|
||||||
|
}
|
||||||
|
if ($group === 'observations' && isset($item['value'])) {
|
||||||
|
abort_unless(! empty($item['unit']) && ! empty($item['period_start']) && ! empty($item['period_end']) && ! empty($item['scope']) && ! empty($item['population']), 422, 'Indicador numérico exige unidade, período, âmbito e base/população.');
|
||||||
|
}
|
||||||
|
if (! empty($item['organization_id'])) {
|
||||||
|
abort_unless(DB::table('organizations')->where('id', $item['organization_id'])->whereNull('deleted_at')->exists(), 422, 'Reutilize uma entidade existente.');
|
||||||
|
}
|
||||||
|
if (! empty($item['geometry_id'])) {
|
||||||
|
abort_unless(DB::table('investment_zone_geometries')->where('zone_id', $zone->id)->where('geometry_id', $item['geometry_id'])->exists(), 422, 'Geometria deve estar associada a este parque; limite administrativo não é perímetro.');
|
||||||
|
}
|
||||||
|
if (! empty($item['zone_link_id'])) {
|
||||||
|
abort_unless(DB::table('investment_zone_links')->where('zone_id', $zone->id)->where('id', $item['zone_link_id'])->exists(), 422, 'Relação económica deve pertencer a este parque.');
|
||||||
|
}
|
||||||
|
foreach ($item['support_document_ids'] ?? [] as $doc) {
|
||||||
|
abort_unless(DB::table('investment_zone_attachments as a')->join('documents as d', 'd.id', '=', 'a.document_id')->where('a.zone_id', $zone->id)->where('d.id', $doc)->whereNull('d.deleted_at')->where('d.status', 'active')->where('d.malware_scan_status', 'clean')->whereColumn('d.sha256', 'd.malware_scanned_sha256')->exists(), 422, 'Suporte deve estar consultável e associado a este parque.');
|
||||||
|
}
|
||||||
|
$rows[$id] = $item;
|
||||||
|
}
|
||||||
|
foreach ($remove as $id) {
|
||||||
|
abort_unless(isset($rows[$id]), 422, 'O detalhe a remover não pertence ao parque.');
|
||||||
|
unset($rows[$id]);
|
||||||
|
}
|
||||||
|
abort_if(count($rows) > 200, 422, 'Limite de detalhes excedido.');
|
||||||
|
$result[$group] = array_values($rows);
|
||||||
}
|
}
|
||||||
// References resolve only inside this park, including new items in the same transaction.
|
// References resolve only inside this park, including new items in the same transaction.
|
||||||
foreach(self::GROUPS as$group)foreach($result[$group]as$item){
|
foreach (self::GROUPS as $group) {
|
||||||
foreach(['phase_id'=>'phases','plot_id'=>'plots']as$key=>$target)if(!empty($item[$key]))abort_unless(in_array($item[$key],array_column($result[$target],'id'),true),422,'Referência interna inexistente ou de outro parque.');
|
foreach ($result[$group] as $item) {
|
||||||
if(!empty($item['phase_id'])&&!empty($item['plot_id'])){$plot=collect($result['plots'])->firstWhere('id',$item['plot_id']);abort_if(!empty($plot['phase_id'])&&$plot['phase_id']!==$item['phase_id'],422,'Lote e fase não correspondem.');}
|
foreach (['phase_id' => 'phases', 'plot_id' => 'plots'] as $key => $target) {
|
||||||
|
if (! empty($item[$key])) {
|
||||||
|
abort_unless(in_array($item[$key], array_column($result[$target], 'id'), true), 422, 'Referência interna inexistente ou de outro parque.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (! empty($item['phase_id']) && ! empty($item['plot_id'])) {
|
||||||
|
$plot = collect($result['plots'])->firstWhere('id', $item['plot_id']);
|
||||||
|
abort_if(! empty($plot['phase_id']) && $plot['phase_id'] !== $item['phase_id'], 422, 'Lote e fase não correspondem.');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
foreach(['phases','plots']as$group){$codes=[];foreach($result[$group]as$item)if(trim($item['code']??'')!==''){$code=mb_strtolower(trim($item['code']));abort_if(in_array($code,$codes,true),422,'Código interno repetido no parque.');$codes[]=$code;}}
|
foreach (['phases', 'plots'] as $group) {
|
||||||
$keys=[];foreach($result['occupants']as$item){$key=implode('|',[$item['organization_id']??$item['documentary_name']??$item['id'],$item['plot_id']??'',$item['valid_from']??'',$item['valid_until']??'']);abort_if(in_array($key,$keys,true),422,'Ocupante/período já registado; reutilize o detalhe.');$keys[]=$key;}
|
$codes = [];
|
||||||
$keys=[];foreach($result['observations']as$item){if(!isset($item['period_start'],$item['period_end']))continue;$key=implode('|',[$item['indicator'],$item['period_start'],$item['period_end'],$item['scope']??'',$item['population']??'',$item['unit']??'',$item['methodology']??'',$item['source_reference']??'',$item['source_date']??'',$item['phase_id']??'',$item['plot_id']??'']);abort_if(in_array($key,$keys,true),422,'A mesma observação/fonte já está registada; altere o detalhe existente para criar a sua nova revisão.');$keys[]=$key;}
|
foreach ($result[$group] as $item) {
|
||||||
return [...$result,'schema_version'=>1];
|
if (trim($item['code'] ?? '') !== '') {
|
||||||
|
$code = mb_strtolower(trim($item['code']));
|
||||||
|
abort_if(in_array($code, $codes, true), 422, 'Código interno repetido no parque.');
|
||||||
|
$codes[] = $code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$keys = [];
|
||||||
|
foreach ($result['occupants'] as $item) {
|
||||||
|
$key = implode('|', [$item['organization_id'] ?? $item['documentary_name'] ?? $item['id'], $item['plot_id'] ?? '', $item['valid_from'] ?? '', $item['valid_until'] ?? '']);
|
||||||
|
abort_if(in_array($key, $keys, true), 422, 'Ocupante/período já registado; reutilize o detalhe.');
|
||||||
|
$keys[] = $key;
|
||||||
|
}
|
||||||
|
$keys = [];
|
||||||
|
foreach ($result['observations'] as $item) {
|
||||||
|
if (! isset($item['period_start'],$item['period_end'])) {
|
||||||
|
continue;
|
||||||
|
}$key = implode('|', [$item['indicator'], $item['period_start'], $item['period_end'], $item['scope'] ?? '', $item['population'] ?? '', $item['unit'] ?? '', $item['methodology'] ?? '', $item['source_reference'] ?? '', $item['source_date'] ?? '', $item['phase_id'] ?? '', $item['plot_id'] ?? '']);
|
||||||
|
abort_if(in_array($key, $keys, true), 422, 'A mesma observação/fonte já está registada; altere o detalhe existente para criar a sua nova revisão.');
|
||||||
|
$keys[] = $key;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...$result, 'schema_version' => 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<array-key, mixed> $fields
|
||||||
|
* @return array<array-key, mixed>
|
||||||
|
*/
|
||||||
public function publicData(array $fields): array
|
public function publicData(array $fields): array
|
||||||
{
|
{
|
||||||
$public=['schema_version'=>1];
|
$public = ['schema_version' => 1];
|
||||||
foreach(self::GROUPS as$group){$public[$group]=[];foreach($fields[$group]??[]as$item){
|
foreach (self::GROUPS as $group) {
|
||||||
if(!($item['disclosure']??false))continue;
|
$public[$group] = [];
|
||||||
$keys=['id','label','label_en','description','description_en','knowledge','source_reference','source_date','scope',...self::EXTRA[$group]];
|
foreach ($fields[$group] ?? [] as $item) {
|
||||||
$visible=array_intersect_key($item,array_flip($keys));unset($visible['organization_id'],$visible['documentary_name'],$visible['geometry_id'],$visible['zone_link_id']);
|
if (! ($item['disclosure'] ?? false)) {
|
||||||
if(in_array($group,['occupants','chains'],true)&&!empty($item['organization_id'])){$org=DB::table('organizations')->where('id',$item['organization_id'])->whereNull('deleted_at')->where('data_classification','public')->first();abort_unless($org&&$item['knowledge']==='documented',422,'Divulgar entidade exige cadastro público e fonte; a menção preliminar permanece privada.');$visible['organization_name']=$org->name;}
|
continue;
|
||||||
if($group==='occupants')abort_unless(!empty($visible['organization_name']),422,'Ocupante por identificar permanece privado.');
|
}
|
||||||
$public[$group][]=$visible;
|
$keys = ['id', 'label', 'label_en', 'description', 'description_en', 'knowledge', 'source_reference', 'source_date', 'scope', ...self::EXTRA[$group]];
|
||||||
}}
|
$visible = array_intersect_key($item, array_flip($keys));
|
||||||
|
unset($visible['organization_id'],$visible['documentary_name'],$visible['geometry_id'],$visible['zone_link_id']);
|
||||||
|
if (in_array($group, ['occupants', 'chains'], true) && ! empty($item['organization_id'])) {
|
||||||
|
$org = DB::table('organizations')->where('id', $item['organization_id'])->whereNull('deleted_at')->where('data_classification', 'public')->first();
|
||||||
|
abort_unless($org && $item['knowledge'] === 'documented', 422, 'Divulgar entidade exige cadastro público e fonte; a menção preliminar permanece privada.');
|
||||||
|
$visible['organization_name'] = $org->name;
|
||||||
|
}
|
||||||
|
if ($group === 'occupants') {
|
||||||
|
abort_unless(! empty($visible['organization_name']), 422, 'Ocupante por identificar permanece privado.');
|
||||||
|
}
|
||||||
|
$public[$group][] = $visible;
|
||||||
|
}
|
||||||
|
}
|
||||||
// A disclosed item must not leak the identifier of an undisclosed phase or plot.
|
// A disclosed item must not leak the identifier of an undisclosed phase or plot.
|
||||||
foreach(self::GROUPS as$group)foreach($public[$group]as&$item)foreach(['phase_id'=>'phases','plot_id'=>'plots']as$key=>$target)if(!empty($item[$key])&&!in_array($item[$key],array_column($public[$target],'id'),true))unset($item[$key]);unset($item);
|
foreach (self::GROUPS as $group) {
|
||||||
|
foreach ($public[$group] as &$item) {
|
||||||
|
foreach (['phase_id' => 'phases', 'plot_id' => 'plots'] as $key => $target) {
|
||||||
|
if (! empty($item[$key]) && ! in_array($item[$key], array_column($public[$target], 'id'), true)) {
|
||||||
|
unset($item[$key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}unset($item);
|
||||||
|
|
||||||
return $public;
|
return $public;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user