Compare commits

...
183 Commits
Author SHA1 Message Date
paulomassigue f1db53fdbf paginacao de 3 em 3 2026-11-18 15:19:58 +02:00
paulomassigue bae996e10d biblioteca e legislacao
tests / ci (push) Waiting to run
2026-11-18 11:05:22 +02:00
paulomassigue 1679b28392 Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2
tests / ci (push) Waiting to run
2026-11-17 14:36:39 +02:00
paulomassigue 50dfec4844 filtros de biblioteca e legislacao 2026-11-17 14:12:02 +02:00
nala 76d8a28eaf Explain inputs on standalone protected confirmation forms
tests / ci (push) Canceled after 0s
2026-11-17 10:16:20 +02:00
nala 953602fb85 Keep contextual filling help within modal form focus scopes
tests / ci (push) Canceled after 0s
2026-11-17 10:08:07 +02:00
nala ded66878af Add contextual filling help across forms and fiscal simulator steps
tests / ci (push) Canceled after 0s
2026-11-17 10:01:43 +02:00
nala c0d62d4e89 Show automatic stage help after native disclosure opens
tests / ci (push) Canceled after 0s
2026-11-17 09:17:14 +02:00
nala e11b5592c7 Add automatic contextual help to adaptive investment stages
tests / ci (push) Canceled after 0s
2026-11-17 08:55:48 +02:00
nala b60c231ddc fix: reconcile accepted source classifications for protected investor aggregates
tests / ci (push) Canceled after 0s
2026-11-15 23:25:51 +02:00
nala c8957ecb9d feat: protect owner-only supply aggregates and record target CAE blocker 2026-11-15 23:10:17 +02:00
nala e0b18413ac docs: record d3067050 sector homologation and preserved access limits 2026-11-15 22:08:03 +02:00
nala d306705027 docs: record five sector QA journeys and the separate translation dependency
tests / ci (push) Canceled after 0s
2026-11-15 20:56:27 +02:00
nala b4ebca049e test: conform affected dossier report tests to the existing typed lint rules 2026-11-15 20:51:10 +02:00
nala 6d97ca77d0 merge: retain installed funding correction alongside isolated sector QA 2026-11-15 20:32:04 +02:00
nala 6e7dfdabd0 feat: preserve grounded sector ideas through private investment dossiers in QA 2026-11-15 20:31:57 +02:00
nala fb23931feb docs: record installed funding location correction and real territorial results 2026-11-15 20:08:23 +02:00
nala 44c3436b19 docs: verify funding location bundle with HTTP and desktop/mobile evidence
tests / ci (push) Canceled after 0s
2026-11-15 19:49:21 +02:00
nala ae3d05305c docs: reconcile four existing matrix entries with verified delivery receipt 2026-11-15 19:39:36 +02:00
nala 7625a138e7 docs: record verified bd000d04 homologation delivery and preserved Ofertas scope 2026-11-15 19:39:35 +02:00
Codex afa02559a1 fix: make financial institution local presence explicit 2026-11-15 19:34:01 +02:00
nala 25d18f51bb docs: reconcile four existing matrix entries with verified delivery receipt 2026-11-15 19:17:48 +02:00
nala c4aa3ac548 docs: record verified bd000d04 homologation delivery and preserved Ofertas scope 2026-11-15 19:17:32 +02:00
nala bd000d04d2 fix: preserve transversal regression contracts and lock budget during confirmation
tests / ci (push) Canceled after 0s
2026-11-15 19:12:36 +02:00
nala fb076c174f Entrega dashboard e correccoes transversais preservando Ofertas instalado
tests / ci (push) Canceled after 0s
2026-11-15 18:56:39 +02:00
nala 1349789226 fix(offers): avoid Wayfinder report form name collision after safe deployment stop
tests / ci (push) Canceled after 0s
2026-11-14 20:10:32 +02:00
nala 9cbd7fb97d docs(offers): record mandatory stop on authorised revision mismatch 2026-11-14 19:47:07 +02:00
nala 2afbc5c9c7 docs(offers): verify live target backup and isolated recovery before install 2026-11-14 19:44:08 +02:00
nala 3558647e8d fix(offers): align private navigation with portal dropdown menus
tests / ci (push) Canceled after 0s
2026-11-14 19:07:14 +02:00
nala d954c83b78 docs(offers): prepare gated homologation readiness and recovery plan 2026-11-14 18:47:11 +02:00
nala 9a01426864 fix(offers): preserve description in authorised investment context 2026-11-14 18:39:25 +02:00
nala ed2fd86f6b audit(offers): record acceptance blockers before homologation 2026-11-14 18:25:09 +02:00
nala 528a2597ed feat(offers): complete phase five operational controls in QA 2026-11-14 18:08:46 +02:00
nala e431de8b42 feat(offers): implement phase four private details and confidentiality in QA 2026-11-14 17:28:12 +02:00
nala 7691cab3bc feat(offers): add gated phase three public catalogue in QA 2026-11-14 16:49:58 +02:00
nala 91c1857368 feat: integrate private offers with existing editorial workflow 2026-11-14 16:20:30 +02:00
nala 6e302db62e docs: confirm private offers QA and plan phase two 2026-11-14 13:58:33 +02:00
nala 1f2990e4da feat: prepare private offers through existing opportunities 2026-11-14 13:41:31 +02:00
nala e8408c27d9 Record verified administration dashboard hierarchy correction 2026-11-14 12:34:05 +02:00
nala 96f510965f Separate dashboard functions from grouped administration operations
tests / ci (push) Canceled after 0s
2026-11-14 12:25:27 +02:00
nala 88f18d0b7e Record verified dashboard HTML recovery dd20e747 2026-11-14 12:13:54 +02:00
nala dd20e74703 Fix authenticated editorial dashboard missing Vite page entry
tests / ci (push) Canceled after 0s
2026-11-14 12:04:52 +02:00
nala 203c8f9193 Record verified dashboard menu deployment 73e1d7b9 2026-11-14 11:59:02 +02:00
nala 73e1d7b964 Group dashboard activities under primary administration and tidy editorial overview
tests / ci (push) Waiting to run
2026-11-14 11:43:56 +02:00
nala ce8b744d1f Record verified grouped dashboard installation a4541298 2026-11-14 11:31:38 +02:00
nala a4541298c0 Complete grouped collaborative editorial queues and native review coverage
tests / ci (push) Canceled after 0s
2026-11-14 11:15:09 +02:00
nala f40924f1be Record authorised grouped editorial installation and preservation receipts 2026-11-14 10:11:23 +02:00
nala d5c960b62f Merge remote-tracking branch 'origin/main' into qa/editorial-fase1-20261113
tests / ci (push) Canceled after 0s
2026-11-14 09:12:25 +02:00
nala fa69884ab0 Integrate authorised editorial package with current homologation changes 2026-11-14 09:11:55 +02:00
nala e473542494 Support documented full annual noncivil PPC PEC estimates and dossier continuity
tests / ci (push) Canceled after 0s
2026-11-14 09:05:33 +02:00
nala b3d4b7abe6 Preserve published territories during private editorial review 2026-11-14 09:03:05 +02:00
nala d3eeb70370 Record authorised period consistency installation and preserved data 2026-11-14 09:02:37 +02:00
nala 3c4c2599f7 feat(editorial): review demographic batches before explicit publication 2026-11-14 08:35:11 +02:00
nala 078f770dea Keep PPC PEC estimates and reports consistent with the prepared L6 period
tests / ci (push) Canceled after 0s
2026-11-14 00:23:46 +02:00
nala e9278ee446 Record authorised grouped PEC installation and preserved data 2026-11-14 00:00:21 +02:00
nala 2459d0ca37 feat(editorial): stage portfolio base data and territory for atomic publication 2026-11-13 23:47:04 +02:00
nala 95b33275aa Integrate monthly PPC PEC cash projections across screen and dossier report
tests / ci (push) Canceled after 0s
2026-11-13 23:32:00 +02:00
nala a045162773 Record authorised grouped PEC installation and preserved data 2026-11-13 23:29:17 +02:00
nala d2c72f5e13 feat(editorial): preserve public portfolio fiches during private review 2026-11-13 23:23:16 +02:00
nala f059c226d2 Group documented prior PEC basis and excess PPC reconciliation for viability
tests / ci (push) Canceled after 0s
2026-11-13 23:14:22 +02:00
nala 1218734eca feat(editorial): separate cluster analysis approval and publication in QA 2026-11-13 23:08:02 +02:00
nala d9f088587b Record authorised observation nature delivery and preserved data 2026-11-13 23:07:27 +02:00
nala b3849d850e feat(editorial): preserve public editions and add QA review workflow 2026-11-13 22:56:44 +02:00
nala 2bad72c042 Expose calendar duration and overlap before comparing territorial observations
tests / ci (push) Canceled after 0s
2026-11-13 22:54:49 +02:00
nala 39bddad091 Record authorised observation nature delivery and preserved data 2026-11-13 22:54:46 +02:00
nala 42b9324acb Classify sourced territorial observations without inferring legacy values
tests / ci (push) Canceled after 0s
2026-11-13 22:44:42 +02:00
nala 7e7bd4fde3 Record authorised territorial comparison delivery and preserved data 2026-11-13 22:09:58 +02:00
nala 1263b4f6b7 Compare sourced territorial observations without inferring statistical equivalence
tests / ci (push) Canceled after 0s
2026-11-13 21:52:38 +02:00
nala 2f1ef2fdfc Align quick search with current financial directory while retaining historical records
tests / ci (push) Canceled after 0s
2026-11-13 21:14:25 +02:00
nala 61b4d9f1f9 Record authorised stage report installation and preservation 2026-11-13 15:19:12 +02:00
nala 1d52c3d8f4 Preserve installed dossier and support presentation while delivering authorised quick search
tests / ci (push) Canceled after 0s
2026-11-13 15:17:26 +02:00
nala 0f79d0d54c Keep institutional contact test independent of CSS module loading in Node CI
tests / ci (push) Canceled after 0s
2026-11-13 15:09:08 +02:00
nala d325b72fad Improve investor quick search with typed counts, product categories and licensing guidance 2026-11-13 15:06:11 +02:00
nala 8854b2928c Allow private stage report preview and explicit Word/HTML download 2026-11-13 15:02:15 +02:00
paulomassigue f53a308327 Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2
tests / ci (push) Canceled after 0s
2026-11-13 14:43:34 +02:00
nala 723ce2a0a4 Record grouped investor reports installed and preservation verified 2026-11-13 14:28:10 +02:00
nala 07182c7c73 Group investor reports and preserved financial copies in their existing dossier
tests / ci (push) Canceled after 0s
2026-11-13 14:09:52 +02:00
nala bb6824d75d Keep concurrent manual additions outside demographic delivery 2026-11-13 14:08:20 +02:00
nala 095280e29d Record demographic matrix status while preserving concurrent additions in working copy 2026-11-13 14:07:52 +02:00
nala e92519dd75 Record HTTP500 correction verified in real PHP-FPM with process execution blocked 2026-11-13 14:06:58 +02:00
nala 4988ca89dc Use verified CLI preparations when web PHP cannot execute processes
tests / ci (push) Canceled after 0s
2026-11-13 13:57:01 +02:00
nala 258c8bd28b Record installed demography access correction and refreshed readiness 2026-11-13 13:49:32 +02:00
nala df543a4414 Recognise designated superusers in authenticated demography installation
tests / ci (push) Canceled after 0s
2026-11-13 13:41:48 +02:00
nala 291a1c420f Record demography code installed in homologation, authenticated data confirmation pending 2026-11-13 13:40:16 +02:00
nala b20068d04b Deliver additive INE demography and authenticated homologation installation
tests / ci (push) Canceled after 0s
2026-11-13 13:27:36 +02:00
paulomassigue eab09dd61e ajuste na pesquisa de informacao, para passar a dar prioridade 2026-11-13 12:07:51 +02:00
paulomassigue 71f2fcbb84 Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2 into front 2026-11-13 09:54:01 +02:00
paulomassigue f6c1b60612 organizao de suporte 2026-11-12 11:26:33 +02:00
nala 880e12890c Record mining and energy reference delivery installed in f2767818 2026-11-11 14:20:23 +02:00
nala f276781876 Keep sector reference byte verification identical across Windows and Git
tests / ci (push) Canceled after 0s
2026-11-11 14:13:51 +02:00
nala 542ac2ff2c Integrate mining and energy references into sector and dossier journeys 2026-11-11 14:10:15 +02:00
nala 4971f8935b Record reconciled profile and six-menu delivery installed in 6d3bf293 2026-11-11 12:39:23 +02:00
nala 6d3bf2937e Merge remote-tracking branch 'origin/main' into entrega/directiva-20261110
tests / ci (push) Canceled after 0s
2026-11-11 12:31:10 +02:00
nala eca6719135 Unify institution profiles and reduce primary menu to six groups 2026-11-11 12:11:52 +02:00
paulomassigue a400802b63 Merge branch 'front' of https://git.tempo.co.mz/nala/Investidor-V2
tests / ci (push) Canceled after 0s
2026-11-11 11:53:57 +02:00
paulomassigue 1b8b9f414a . 2026-11-11 11:53:41 +02:00
paulomassigue 70423474d2 navbar fixa durante a rolagem 2026-11-11 11:46:12 +02:00
nala ee23a2cc2c Record financial editorial a59142ca installation and preservation 2026-11-11 11:39:22 +02:00
nala a59142caa2 Present financial institutions with professional investor-facing descriptions and products
tests / ci (push) Canceled after 0s
2026-11-11 11:19:27 +02:00
nala 8ebe734d0d Record PEC correction 8f295f05 installation and data preservation 2026-11-11 11:03:50 +02:00
nala 8f295f0551 Preserve documented turnover corrections in PEC viability estimates
tests / ci (push) Canceled after 0s
2026-11-11 10:55:53 +02:00
nala a2033dd4a0 Record viability simulation a708f079 installation and data preservation 2026-11-11 10:46:21 +02:00
nala a708f079b3 Clarify viability simulation purpose and preserve PEC cash-flow hypotheses
tests / ci (push) Canceled after 0s
2026-11-11 10:37:33 +02:00
nala aae79c712d Record PEC bcbbe51c installation and verified preservation 2026-11-11 10:28:46 +02:00
nala bcbbe51c2f Prepare PEC obligation total and calendar with private recovery and reports
tests / ci (push) Canceled after 0s
2026-11-11 09:59:54 +02:00
nala e549003e5d Record PPC fbff2660 installation and verified preservation 2026-11-11 09:05:24 +02:00
nala fbff2660f2 Preparar obriga??o PPC ordin?ria com recupera??o e relat?rio no dossier
tests / ci (push) Canceled after 0s
2026-11-11 08:55:14 +02:00
nala 192a7e35e5 Registar retoma educativa instalada em 6805b606 e preservação conferida 2026-11-11 08:46:32 +02:00
nala 6805b606a1 Complete durable private Education review preparation and recovery
tests / ci (push) Canceled after 0s
2026-11-11 08:21:56 +02:00
nala bbc3c1c9bc Registar combinação CBF15 instalada em 9c067d6a e dados preservados 2026-11-11 07:45:02 +02:00
nala 9c067d6ae8 Completar combinação CBF15 com saldos anteriores e conferir PEC residual
tests / ci (push) Canceled after 0s
2026-11-11 07:35:04 +02:00
nala 67cd583b94 Confirmar 270 instituições publicadas e consulta financeira por localização 2026-11-10 22:55:05 +02:00
nala 0f280d2d6d Confirmar acesso ao editor no Edge com a sessão autenticada correcta 2026-11-10 22:12:24 +02:00
nala 0e8da995e0 Diagnosticar recusa do editor em sessão Safari distinta do login Edge 2026-11-10 22:11:07 +02:00
nala ff293940a6 Registar retoma editorial instalada em 4f3dbcf8 e conteúdo ainda por publicar 2026-11-10 22:02:56 +02:00
nala 4f3dbcf864 Conservar progresso editorial entre renovações MFA e tornar a retoma visível
tests / ci (push) Canceled after 0s
2026-11-10 21:55:42 +02:00
nala d830fbca50 Registar instalação ef24cbdc e disponibilização editorial ainda por confirmar 2026-11-10 21:19:01 +02:00
nala ef24cbdc92 Conferir e publicar instituições pelo editor assistido com MFA nativo
tests / ci (push) Canceled after 0s
2026-11-10 21:09:18 +02:00
nala 5a5cc9e815 Integrate supplied institutions by location category and type through investor dossiers 2026-11-10 20:59:24 +02:00
nala 5ff9402fd0 Prepare supplied financial directory with product coverage and native dossier continuity 2026-11-10 18:51:23 +02:00
nala c8e0a7ee39 Record installed APIEX SWOT and prominent Concursos delivery receipt 2026-11-10 18:23:31 +02:00
nala 1c75a30a60 Preserve S08 hash lifecycle while revealing linked SWOT tasks
tests / ci (push) Canceled after 0s
2026-11-10 18:17:13 +02:00
nala c790159250 Restore prominent Concursos dropdown before authorized APIEX and SWOT delivery
tests / ci (push) Canceled after 0s
2026-11-10 18:07:50 +02:00
nala 37854d0231 Complete APIEX documentary preparation and private contextual SWOT in existing dossiers 2026-11-10 18:00:06 +02:00
nala 7476dc3430 feat: carry documented investment credits within original project window
tests / ci (push) Canceled after 0s
2026-11-10 16:17:48 +02:00
nala d216830b06 fix: unify horizontal portal menus and remove discovery duplicates
tests / ci (push) Canceled after 0s
2026-11-10 15:48:23 +02:00
nala d5cb41b111 feat: apply investment credit five-exercise window
tests / ci (push) Canceled after 0s
2026-11-10 15:35:24 +02:00
nala 89e6d72c1e feat: calculate qualified investment credits in annual settlement
tests / ci (push) Canceled after 0s
2026-11-10 15:09:31 +02:00
nala 7c8d4726e9 feat: qualify treaty interest under governmental financing agreements
tests / ci (push) Canceled after 0s
2026-11-10 14:18:47 +02:00
nala b10b35f308 feat: support public-payer treaty exemption and exact economic adjustments
tests / ci (push) Canceled after 0s
2026-11-10 13:54:06 +02:00
nala 60b52fc8c7 feat: derive qualified Portugal treaty credit limits
tests / ci (push) Canceled after 0s
2026-11-10 13:38:56 +02:00
nala ac67f9c13a feat: reconcile L6 economic income and extend L8 credits
tests / ci (push) Canceled after 0s
2026-11-10 13:23:11 +02:00
nala c359364de3 feat(portal): deliver ordinary national credit fraction and education continuity
tests / ci (push) Canceled after 0s
2026-11-10 12:47:57 +02:00
nala ff726e577f docs(portal): diagnose browser bridge and record scoped review
tests / ci (push) Canceled after 0s
2026-11-10 11:11:40 +02:00
nala 03bcaf38cd fix(licensing): keep hash target revealed after next-stage updates 2026-11-10 11:10:53 +02:00
nala 659c039b27 docs(licensing): record S08 coverage and keep visual review and installation separate 2026-11-10 11:01:29 +02:00
nala 6734441855 fix(licensing): simplify S08 and reveal linked stage without losing context 2026-11-10 11:00:56 +02:00
nala 95def7f75e docs(portal): preserve S08 pending scope after owner clarification 2026-11-10 10:52:49 +02:00
nala 786d5f78d1 docs(portal): record Portal V4 source recovery for S08 2026-11-10 10:49:00 +02:00
nala 5e00f1ee9e docs(portal): map scoped commits and preserve S08 and visual pending work 2026-11-10 10:42:40 +02:00
nala 252f38bb0a feat(portal): expose bounded public sitemap 2026-11-10 10:41:50 +02:00
nala 7f13149723 feat(opportunities): curate highlights with native authority and audited confirmation 2026-11-10 10:41:50 +02:00
nala dcecd25102 feat(desk): print authorized saved pre-dossier 2026-11-10 10:41:49 +02:00
nala 4e07557cb1 fix(opportunities): distinguish missing verification and improve metadata 2026-11-10 10:41:48 +02:00
nala 4e61480272 fix(portal): identify operator and institutional support contact 2026-11-10 10:41:47 +02:00
nala 377c40a21a fix(portal): preserve territorial totals and legacy redirect context 2026-11-10 10:41:46 +02:00
paulomassigue 2209b83820 login de cadastro padronizado
tests / ci (push) Canceled after 0s
2026-11-09 15:05:20 +02:00
paulomassigue 67aa015b4c Merge branch 'front' of https://git.tempo.co.mz/nala/Investidor-V2
tests / ci (push) Waiting to run
2026-11-05 14:59:29 +02:00
paulomassigue 4f630b9f2a pesquisa avancada 2026-11-05 14:54:39 +02:00
paulomassigue 5859a9810e Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2
tests / ci (push) Canceled after 0s
2026-11-05 12:21:50 +02:00
paulomassigue dab85aee96 correcao de conflitos 2026-11-05 12:21:25 +02:00
nala 12cecd061b commit de menus
tests / ci (push) Canceled after 0s
2026-11-05 08:36:28 +02:00
paulomassigue 705dc69d68 pesquisa intelignte
tests / ci (push) Canceled after 0s
2026-11-04 15:52:55 +02:00
paulomassigue 6da444ae2e .
tests / ci (push) Canceled after 0s
2026-11-04 15:10:29 +02:00
nala 7e351348af feat: filter public map indicators by indicator and reference period 2026-11-04 12:55:03 +02:00
paulomassigue c5756c0282 pesquisa avancada no portal 2026-11-04 12:38:21 +02:00
nala 3f50f66633 feat: display precise public labour and economic observations in map context
tests / ci (push) Canceled after 0s
2026-11-04 11:45:42 +02:00
nala a9241ff26b feat: add workforce evidence and sourced economic context map layers 2026-11-04 11:27:37 +02:00
nala 21ebad73e7 feat: add public resource and infrastructure evidence layers to catalogue map 2026-11-04 11:16:01 +02:00
nala bbc05f1df6 feat: show immediate administrative subdivisions and map coverage gaps 2026-11-04 10:58:28 +02:00
nala 6dde36b5ca fix: preserve territorial scope in catalogue CSV and record local visual QA 2026-11-04 10:49:22 +02:00
nala dc0bbd74d5 test: verify local main against isolated PostGIS QA 2026-11-04 10:16:58 +02:00
nala 66a5dbf311 docs: record verified local reconciliation integration without push 2026-11-04 09:18:28 +02:00
nala f17e807ce1 fix: resolve reconciliation conflicts preserving catalogue behaviour 2026-11-04 09:07:23 +02:00
nala 4a881252fc commit 23 2026-11-04 08:49:36 +02:00
nala 36c8cadb49 feat: consolidar desenvolvimentos do portal InvestMoz 2026-11-03 23:32:32 +02:00
paulomassigue bf2c054943 Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2 into front 2026-11-03 15:31:43 +02:00
paulomassigue f3455432cf . 2026-11-03 15:31:25 +02:00
nala 1da273f1f3 commit16 2026-11-02 20:31:15 +02:00
paulomassigue 4b3c7e161f resolucoa de conflitos
tests / ci (push) Canceled after 0s
2026-10-30 14:58:36 +02:00
paulomassigue 3a3aba5026 resolucao de conflitos 2026-10-30 14:55:58 +02:00
nala 8ddfa93f45 feat: expose map layer controls and explicit data coverage 2026-10-29 23:15:11 +02:00
nala 87b74f0c2a fix: discard obsolete autosaves and bind acknowledgements to draft sequence 2026-10-29 23:10:29 +02:00
nala ed96fd10b9 fix: preserve large Unicode drafts with bounded keepalive transport 2026-10-29 23:08:09 +02:00
nala fa2ece10de fix: recover saved investment context without resubmitting confirmation 2026-10-29 23:04:25 +02:00
nala 26f6a0d348 fix: reject stale context previews and protect pending edits 2026-10-29 23:01:36 +02:00
nala a10dd83d8d fix: expose document association changes in preparation impact 2026-10-29 22:58:30 +02:00
nala 181a9883b3 feat: prioritise missing preparation documents and retain associations 2026-10-29 22:56:02 +02:00
nala d662e63469 feat: expose adaptive preparation status and next action 2026-10-29 22:51:15 +02:00
nala fb9a363e9e fix: validate dossier scope and accurate directory MFA status 2026-10-29 22:42:22 +02:00
nala 4f72751b8b docs: record authenticated preservation and installer reconciliation 2026-10-29 22:31:49 +02:00
nala 8a8204eb53 docs: record Git delivery and bounded installation prerequisites 2026-10-29 22:04:08 +02:00
paulomassigue 996b5b08cd ajuste da estetica em oportunidades de investimento 2026-10-29 12:48:31 +02:00
1047 changed files with 252565 additions and 8116 deletions
+5
View File
@@ -119,3 +119,8 @@ INVESTMOZ_TAX_RULE_APPROVERS=
INVESTMOZ_TAX_RULE_PUBLISHERS= INVESTMOZ_TAX_RULE_PUBLISHERS=
INVESTMOZ_ZONE_TERRITORY_REVIEWERS= INVESTMOZ_ZONE_TERRITORY_REVIEWERS=
# Local LibreTranslate service and installed language models.
LIBRETRANSLATE_URL=http://127.0.0.1:5000
LIBRETRANSLATE_TIMEOUT=60
LIBRETRANSLATE_API_KEY=
+17
View File
@@ -1,5 +1,22 @@
## Uniformização pública e menu — decisão expressa do proprietário,11/11/2026
Lista e detalhe das instituições financeiras devem usar a mesma apresentação:descrição única,categoria/tipo sem repetição,produtos/serviços,contactos e moradas úteis apenas quando disponíveis. Não apresentar secções vazias,avisos genéricos repetidos,notas de publicação/importação,preços antigos por reconfirmar ou a mesma informação várias vezes. Deduplicar apenas a apresentação,conservando dados e fontes no editor. Usar Quorus e Moza Banco como exemplos de conferência.
Menu principal:Início,Descoberta,Realização,Suporte,Sobre nós,Mais. Descoberta:Concursos e anúncios,Localizações,Instituições financeiras,Catálogos relacionados. Realização:Iniciar investimento,Licenciamento,Acesso à terra. Suporte:Biblioteca,Legislação,Serviços ao investidor,Acompanhamento do projecto,Apoio ao investidor. Preservar conteúdo deSobre nós/Mais,contexto dos dossiers e permissões. Escolha de apresentação:acessos de trabalho antes no nível principal passam paraMais,sem novas concessões.
## Comunicação pública — orientação expressa do proprietário,11/11/2026
Apresentar conteúdos públicos com linguagem profissional,clara e apelativa,centrada na entidade,oportunidade,produtos e serviços úteis ao investidor. Não usar descrições de importação,cadastro,fichas,ficheiros ou documentos geradores como apresentação comercial. Preservar as fontes,versões e rastreabilidade no cadastro/editor;ligações institucionais e datas úteis podem ser consultadas separadamente. Não inventar ofertas,condições,disponibilidade,cobertura ou garantias para preencher lacunas. Esta orientação aplica-se transversalmente aos conteúdos do portal.
## Simulação de viabilidade — clarificação expressa do proprietário,11/11/2026
O InvesteMoz simula impostos para avaliar a viabilidade do negócio; não actua como entidade que executa pagamentos. Apresentar PPC/PEC e distribuição por meses como estimativas fiscais e projecções de tesouraria,com fontes e pressupostos. Montantes já pagos,quando fornecidos,são dados documentais para o cálculo. Não confundir uma hipótese de caixa com pagamento efectuado,declaração submetida ou cumprimento fiscal certificado. Preservar os cálculos,históricos e dados aceites; não criar serviços de cobrança/execução de pagamentos como requisito de conclusão deste simulador.
# Instruções permanentes do projeto InvesteMoz # Instruções permanentes do projeto InvesteMoz
## Encerramento e reabertura do dossier — decisão do proprietário, 03/11/2026
O proprietário definiu expressamente: «o dossier tem um dono, esse é que deve executar essa acção», em resposta a quem pode encerrar e reabrir o dossier completo. Usar o dono registado no dossier e conservar a verificação do acesso efectivo existente, incluindo a representação actual quando pertence a uma organização. A condição de gestor, analista ou outro representante não substitui por inferência esse dono. Registar a decisão, motivo, versão e histórico. Encerrar ou reabrir o dossier não equivale a decidir/aprovar pedidos, conferir pagamentos ou alterar em cascata estados de documentos e tarefas.
## Percurso adaptativo — decisão expressa da Tempo, 23/10/2026 ## 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. 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.
@@ -0,0 +1,25 @@
<?php
namespace App\Console\Commands;
use App\Services\InvestmentOpportunityAlerts;
use Illuminate\Console\Command;
final class DispatchInvestmentAlerts extends Command
{
protected $signature = 'investmoz:dispatch-opportunity-alerts';
protected $description = 'Generate due opt-in alerts from public catalogues, without external messages';
public function handle(InvestmentOpportunityAlerts $alerts): int
{
if (! $alerts->installed()) {
$this->warn('Opportunity alerts schema is not installed.');
return self::SUCCESS;
}
$this->info('Matched public catalogue items: '.$alerts->dispatchDue());
return self::SUCCESS;
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use App\Models\Opportunity;
use App\Services\OfferAvailability;
use App\Services\PrivateOfferOperations;
use Illuminate\Console\Command;
final class ExpirePrivateOffers extends Command
{
protected $signature = 'investmoz:offers-expire {--confirm : Persist the already effective expiry}';
protected $description = 'Conferir expiração de Ofertas sem publicar conteúdos ou alterar o NDA';
public function handle(): int
{
$count = 0;
Opportunity::query()->whereNotNull('workflow_context->private_offer_preparation')->orderBy('id')->chunkById(100, function ($records) use (&$count) {
foreach ($records as $record) {
if (app(OfferAvailability::class)->record($record)['state'] !== 'expired') {
continue;
}
if ($this->option('confirm')) {
if (app(PrivateOfferOperations::class)->expire($record->id)) {
$count++;
}
} else {
$count++;
}
}
});
$this->info(($this->option('confirm') ? 'Expirações registadas: ' : 'Expiradas, sem escrita: ').$count);
return self::SUCCESS;
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Exceptions;
use Illuminate\Http\JsonResponse;
use RuntimeException;
use Throwable;
final class OpportunityWorkflowUnavailable extends RuntimeException
{
public function __construct(public readonly string $reference, public readonly bool $recorded, Throwable $previous)
{
parent::__construct('Opportunity operation result requires verification.', 0, $previous);
}
public function render(): JsonResponse
{
return response()->json(['message' => 'Não foi possível confirmar o resultado. Consulte o estado da oportunidade e dos recursos antes de repetir. '.($this->recorded ? 'Incidente técnico registado. ' : 'Não foi possível guardar o incidente; conserve esta referência. ').'Referência: '.$this->reference,
'reference' => $this->reference, 'incident_recorded' => $this->recorded], 503)->header('Cache-Control', 'private, no-store');
}
}
@@ -0,0 +1,83 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Throwable;
class TranslationApiController extends Controller
{
public function languages(): JsonResponse
{
try {
$response = Http::connectTimeout(2)->timeout(config('services.translation.timeout'))->get($this->url().'/languages');
if ($response->successful() && is_array($response->json())) {
return response()->json($response->json())->header('Cache-Control', 'no-store');
}
} catch (Throwable) {
}
return response()->json(['message' => 'Serviço de tradução temporariamente indisponível.'], 503);
}
public function translate(Request $request): JsonResponse
{
$data = $request->validate([
'text' => is_array($request->input('text'))
? 'required|array|min:1|max:8'
: 'required|string|max:10000',
'text.*' => 'required|string|max:10000',
'source_lang' => 'required|string|max:20',
'target_lang' => 'required|string|max:20',
'is_html' => 'boolean',
]);
$isBatch = is_array($data['text']);
if ($isBatch && mb_strlen(implode('', $data['text'])) > 10000) {
return response()->json(['message' => 'O lote de tradução excede o limite permitido.'], 422);
}
if ($data['source_lang'] === $data['target_lang']) {
return response()->json([
'original_text' => $data['text'],
'translated_text' => $data['text'],
'source_lang' => $data['source_lang'],
'target_lang' => $data['target_lang'],
])->header('Cache-Control', 'no-store');
}
$payload = ['q' => $data['text'], 'source' => $data['source_lang'], 'target' => $data['target_lang'], 'format' => ($data['is_html'] ?? false) ? 'html' : 'text'];
if (config('services.translation.api_key')) {
$payload['api_key'] = config('services.translation.api_key');
}
try {
$response = Http::connectTimeout(2)->timeout(config('services.translation.timeout'))->post($this->url().'/translate', $payload);
$translated = $response->json('translatedText');
$validTranslation = $isBatch
? is_array($translated)
&& count($translated) === count($data['text'])
&& ! array_filter($translated, fn ($text) => ! is_string($text) || $text === '')
: is_string($translated) && $translated !== '';
if ($response->successful() && $validTranslation) {
return response()->json([
'original_text' => $data['text'],
'translated_text' => $translated,
'source_lang' => $data['source_lang'],
'target_lang' => $data['target_lang'],
])->header('Cache-Control', 'no-store');
}
} catch (Throwable) {
}
return response()->json(['message' => 'Serviço de tradução temporariamente indisponível.'], 503)->header('Cache-Control', 'no-store');
}
private function url(): string
{
return rtrim((string) config('services.translation.url'), '/');
}
}
@@ -4,6 +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\Services\InvestmentGeography;
use App\Services\SectorOrganization; use App\Services\SectorOrganization;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -20,8 +21,9 @@ 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_territorial_v2_{$locale}", now()->addMinutes(10), function () {
$sectors = SectorOrganization::catalog(); $sectors = SectorOrganization::catalog();
$statistics = app(InvestmentGeography::class)->opportunityStatistics();
$featured = Opportunity::with('sector:id,name,slug') $featured = Opportunity::with('sector:id,name,slug')
->published()->where('is_featured', true) ->published()->where('is_featured', true)
@@ -48,9 +50,9 @@ class HomeController extends Controller
'url' => "/oportunidades/{$o->slug}", 'url' => "/oportunidades/{$o->slug}",
])->values()->all(), ])->values()->all(),
'stats' => [ 'stats' => [
'opportunities' => Opportunity::published()->count(), 'opportunities' => $statistics['opportunities'],
'sectors' => $sectors->count(), 'sectors' => $sectors->count(),
'provinces' => Opportunity::published()->distinct('province')->count('province'), 'provinces' => $statistics['provinces'],
], ],
]; ];
}); });
@@ -6,6 +6,8 @@ use App\Http\Controllers\Controller;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Services\InvestmentCatalogue; use App\Services\InvestmentCatalogue;
use App\Services\OpportunityMaturity; use App\Services\OpportunityMaturity;
use App\Services\OpportunityTextSearch;
use App\Services\PublicSearchMetrics;
use App\Services\SectorOrganization; use App\Services\SectorOrganization;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -41,16 +43,7 @@ class OpportunityController extends Controller
} }
if (! empty($validated['q'])) { if (! empty($validated['q'])) {
$term = $validated['q']; app(OpportunityTextSearch::class)->constrain($query, $validated['q']);
$query->where(fn ($q) => $q
->whereLike('title', "%{$term}%")
->orWhereLike('description', "%{$term}%")
->orWhereLike('summary', "%{$term}%")
->orWhereLike('reference', "%{$term}%")
->orWhereLike('province', "%{$term}%")
->orWhereHas('sector', fn ($sectorQuery) => $sectorQuery
->whereLike('name', "%{$term}%")
->orWhereLike('slug', "%{$term}%")));
} }
if (! empty($validated['sector'])) { if (! empty($validated['sector'])) {
@@ -71,6 +64,7 @@ class OpportunityController extends Controller
$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);
app(PublicSearchMetrics::class)->candidate($request, 'opportunities_api', $results->total(), $validated);
return response()->json($results->withQueryString()->through(fn ($record) => app(InvestmentCatalogue::class)->presentLocation($record))); return response()->json($results->withQueryString()->through(fn ($record) => app(InvestmentCatalogue::class)->presentLocation($record)));
} }
@@ -19,7 +19,7 @@ final class ClusterCompetitivenessController extends Controller
$data = $request->validate(['expected_version' => 'required|integer|min:0', $data = $request->validate(['expected_version' => 'required|integer|min:0',
'draft' => $action === 'saved' ? 'required|array:version,clusterId,sector,region,forces' : 'prohibited', 'draft' => $action === 'saved' ? 'required|array:version,clusterId,sector,region,forces' : 'prohibited',
'revision' => $action === 'restored' ? 'required|integer|min:1' : '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']); 'reason' => in_array($action, ['saved', 'restored'], true) ? 'nullable|string|max:3000' : 'required|string|min:10|max:3000']);
return response()->json($service->change($cluster, $request->user()->id, (int) $data['expected_version'], $action, $data)) return response()->json($service->change($cluster, $request->user()->id, (int) $data['expected_version'], $action, $data))
->header('Cache-Control', 'private, no-store'); ->header('Cache-Control', 'private, no-store');
@@ -7,6 +7,8 @@ use App\Models\InvestmentGap;
use App\Models\ValueChain; use App\Models\ValueChain;
use App\Models\ValueChainLink; use App\Models\ValueChainLink;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use App\Services\PortalEditorialSubjects;
use App\Services\PortalEditorialWorkflow;
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;
@@ -21,6 +23,17 @@ class ClusterValueChainController extends Controller
'to_value_chain_id' => ['required', 'uuid', 'different:from_value_chain_id', Rule::exists('value_chains', 'id')->where('cluster_id', $cluster->id)->whereNull('deleted_at')], 'to_value_chain_id' => ['required', 'uuid', 'different:from_value_chain_id', Rule::exists('value_chains', 'id')->where('cluster_id', $cluster->id)->whereNull('deleted_at')],
'link_type' => ['required', Rule::in(['supplies', 'processes', 'distributes', 'supports'])], 'link_type' => ['required', Rule::in(['supplies', 'processes', 'distributes', 'supports'])],
]); ]);
if (app(PortalEditorialSubjects::class)->available()) {
$edition = DB::transaction(function () use ($cluster, $data, $request) {
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
$link = ValueChainLink::where($data)->first();
abort_if($link !== null, 409, 'Ligação existente. Abra a edição desse registo para alterar.');
return app(PortalEditorialSubjects::class)->stageModel($request->user(), 'value-chain-links', new ValueChainLink, $data, 0);
});
return redirect('/management/editorial/subjects/value-chain-links/'.$edition->subject_key)->with('success', 'Ligação guardada numa proposta privada.');
}
DB::transaction(function () use ($cluster, $data, $request) { DB::transaction(function () use ($cluster, $data, $request) {
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail(); EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
$link = ValueChainLink::where($data)->first() ?? new ValueChainLink; $link = ValueChainLink::where($data)->first() ?? new ValueChainLink;
@@ -32,6 +45,13 @@ class ClusterValueChainController extends Controller
public function removeLink(Request $request, EconomicCluster $cluster, ValueChainLink $link): RedirectResponse public function removeLink(Request $request, EconomicCluster $cluster, ValueChainLink $link): RedirectResponse
{ {
if (app(PortalEditorialSubjects::class)->writes('value-chain-links', $link->id)) {
abort_unless(ValueChain::where('cluster_id', $cluster->id)->whereIn('id', [$link->from_value_chain_id, $link->to_value_chain_id])->count() === 2, 404);
$workflow = app(PortalEditorialWorkflow::class);
$workflow->saveSubject($request->user(), 'value-chain-links', $link->id, $workflow->subjectVersion('value-chain-links', $link->id), [], false, true);
return redirect('/management/editorial/subjects/value-chain-links/'.$link->id)->with('success', 'Retirada proposta. A ligação actual mantém-se até à publicação da decisão.');
}
DB::transaction(function () use ($cluster, $link, $request) { DB::transaction(function () use ($cluster, $link, $request) {
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail(); EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
abort_unless(ValueChain::where('cluster_id', $cluster->id)->whereIn('id', [$link->from_value_chain_id, $link->to_value_chain_id])->count() === 2, 404); abort_unless(ValueChain::where('cluster_id', $cluster->id)->whereIn('id', [$link->from_value_chain_id, $link->to_value_chain_id])->count() === 2, 404);
@@ -44,6 +64,7 @@ class ClusterValueChainController extends Controller
public function gap(Request $request, EconomicCluster $cluster, ?InvestmentGap $gap = null): RedirectResponse public function gap(Request $request, EconomicCluster $cluster, ?InvestmentGap $gap = null): RedirectResponse
{ {
abort_if($gap && $gap->cluster_id !== $cluster->id, 404); abort_if($gap && $gap->cluster_id !== $cluster->id, 404);
$editorial = $gap ? app(PortalEditorialSubjects::class)->writes('investment-gaps', $gap->id) : app(PortalEditorialSubjects::class)->available();
$data = $request->validate([ $data = $request->validate([
'value_chain_id' => ['required', 'uuid', Rule::exists('value_chains', 'id')->where('cluster_id', $cluster->id)->whereNull('deleted_at')], 'value_chain_id' => ['required', 'uuid', Rule::exists('value_chains', 'id')->where('cluster_id', $cluster->id)->whereNull('deleted_at')],
'title' => ['required', 'string', 'max:200'], 'title' => ['required', 'string', 'max:200'],
@@ -52,7 +73,13 @@ class ClusterValueChainController extends Controller
'rationale' => ['required', 'string', 'min:10', 'max:5000'], 'rationale' => ['required', 'string', 'min:10', 'max:5000'],
'status' => ['required', Rule::in(['identified', 'in_review', 'resolved', 'withdrawn'])], 'status' => ['required', Rule::in(['identified', 'in_review', 'resolved', 'withdrawn'])],
'call_to_action' => ['required', 'string', 'max:2000'], 'call_to_action' => ['required', 'string', 'max:2000'],
...($editorial && $gap ? ['editorial_version' => ['required', 'integer', 'min:1']] : []),
]); ]);
if ($editorial) {
$edition = app(PortalEditorialSubjects::class)->stageModel($request->user(), 'investment-gaps', $gap ?? new InvestmentGap, [...array_diff_key($data, ['editorial_version' => true]), 'cluster_id' => $cluster->id], $gap ? (int) $data['editorial_version'] : 0);
return redirect('/management/editorial/subjects/investment-gaps/'.$edition->subject_key)->with('success', 'Lacuna guardada numa proposta privada.');
}
PortalAudit::save($gap ?? new InvestmentGap, [...$data, 'cluster_id' => $cluster->id], $request->user()->id); PortalAudit::save($gap ?? new InvestmentGap, [...$data, 'cluster_id' => $cluster->id], $request->user()->id);
return back()->with('success', 'Lacuna de investimento guardada.'); return back()->with('success', 'Lacuna de investimento guardada.');
@@ -0,0 +1,33 @@
<?php
namespace App\Http\Controllers;
use App\Services\CompanyComparison;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class CompanyComparisonController extends Controller
{
public function index(Request $request, CompanyComparison $service): Response|JsonResponse
{
$answers = $service->answers($request->all());
$data = ['definition' => $service->definition(), 'answers' => $answers, 'result' => $service->evaluate($answers),
'case' => null, 'saved' => null, 'canWrite' => false, 'history' => [], 'historyNext' => null, 'historical' => false, 'workingCopy' => false];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/company-comparison', $data);
}
public function show(Request $request, string $id, CompanyComparison $service): Response|JsonResponse
{
$data = ['definition' => $service->definition(), ...$service->view($request->user(), $id, $request->all())];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/company-comparison', $data);
}
public function save(Request $request, string $id, CompanyComparison $service): JsonResponse
{
return response()->json($service->save($request->user(), $id, $request->all()));
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers;
use App\Services\CompanyPreparation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class CompanyPreparationController extends Controller
{
public function show(Request $request, string $id, CompanyPreparation $service): Response|JsonResponse
{
$data = $service->view($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/company-preparation', $data);
}
public function save(Request $request, string $id, CompanyPreparation $service): JsonResponse
{
return response()->json($service->save($request->user(), $id, $request->all()));
}
}
+64 -26
View File
@@ -10,9 +10,14 @@ use App\Models\Lead;
use App\Models\User; use App\Models\User;
use App\Services\ConvertInterestToLead; use App\Services\ConvertInterestToLead;
use App\Services\CountryCatalogue; use App\Services\CountryCatalogue;
use App\Services\CrmNextAction;
use App\Services\CrmTaskCreation;
use App\Services\CrmTaskPreparations;
use App\Services\DeclaredOriginStatistics; use App\Services\DeclaredOriginStatistics;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use App\Services\VirtualDesk;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse;
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;
@@ -23,6 +28,12 @@ use Inertia\Response;
class CrmController extends Controller class CrmController extends Controller
{ {
private const VERSION_MESSAGES = [
'version.required' => 'Actualize os dados para recuperar a versão deste registo antes de gravar. As suas edições foram conservadas.',
'version.integer' => 'A versão do registo não foi reconhecida. Recupere os dados actuais.',
'version.min' => 'A versão do registo não foi reconhecida. Recupere os dados actuais.',
];
public function investors(Request $request): Response public function investors(Request $request): Response
{ {
$filters = $request->validate(['q' => ['nullable', 'string', 'max:150']]); $filters = $request->validate(['q' => ['nullable', 'string', 'max:150']]);
@@ -43,10 +54,12 @@ class CrmController extends Controller
public function saveInvestor(Request $request, Investor $investor): RedirectResponse public function saveInvestor(Request $request, Investor $investor): RedirectResponse
{ {
$data = $request->validate(['legal_name' => ['required', 'string', 'max:200'], $data = $request->validate(['version' => 'required|integer|min:1', 'legal_name' => ['required', 'string', 'max:200'],
'investor_type' => ['required', Rule::in(['domestic', 'foreign', 'institutional', 'individual'])], 'investor_type' => ['required', Rule::in(['domestic', 'foreign', 'institutional', 'individual'])],
'status' => ['required', Rule::in(['prospect', 'active', 'inactive'])]]); 'status' => ['required', Rule::in(['prospect', 'active', 'inactive'])]], self::VERSION_MESSAGES);
PortalAudit::save($investor, $data, $request->user()->id); $version = (int) $data['version'];
unset($data['version']);
PortalAudit::save($investor, $data, $request->user()->id, $version);
return back()->with('success', 'Investidor actualizado.'); return back()->with('success', 'Investidor actualizado.');
} }
@@ -54,15 +67,17 @@ class CrmController extends Controller
public function saveContact(Request $request, Investor $investor, Contact $contact): RedirectResponse public function saveContact(Request $request, Investor $investor, Contact $contact): RedirectResponse
{ {
abort_unless(DB::table('investor_contacts')->where('investor_id', $investor->id)->where('contact_id', $contact->id)->exists(), 404); abort_unless(DB::table('investor_contacts')->where('investor_id', $investor->id)->where('contact_id', $contact->id)->exists(), 404);
$data = $request->validate(['full_name' => ['required', 'string', 'max:150'], $data = $request->validate(['version' => 'required|integer|min:1', 'full_name' => ['required', 'string', 'max:150'],
'email' => ['required', 'email:rfc', 'max:150'], 'phone' => ['nullable', 'string', 'max:30']]); 'email' => ['required', 'email:rfc', 'max:150'], 'phone' => ['nullable', 'string', 'max:30']], self::VERSION_MESSAGES);
$data['email'] = strtolower(trim($data['email'])); $data['email'] = strtolower(trim($data['email']));
DB::transaction(function () use ($contact, $data, $request) { $version = (int) $data['version'];
unset($data['version']);
DB::transaction(function () use ($contact, $data, $request, $version) {
DB::select('select pg_advisory_xact_lock(170925, hashtext(?))', [$data['email']]); DB::select('select pg_advisory_xact_lock(170925, hashtext(?))', [$data['email']]);
if (Contact::where('id', '!=', $contact->id)->whereRaw('lower(trim(email)) = ?', [$data['email']])->exists()) { if (Contact::where('id', '!=', $contact->id)->whereRaw('lower(trim(email)) = ?', [$data['email']])->exists()) {
throw ValidationException::withMessages(['email' => 'Já existe outro contacto com este email. Reveja os registos antes de os fundir.']); throw ValidationException::withMessages(['email' => 'Já existe outro contacto com este email. Reveja os registos antes de os fundir.']);
} }
PortalAudit::save($contact, $data, $request->user()->id); PortalAudit::save($contact, $data, $request->user()->id, $version);
}); });
return back()->with('success', 'Contacto actualizado.'); return back()->with('success', 'Contacto actualizado.');
@@ -82,7 +97,7 @@ class CrmController extends Controller
'owner_user_id' => ['nullable', 'integer', 'exists:users,id'], 'owner_user_id' => ['nullable', 'integer', 'exists:users,id'],
'origin' => ['nullable', Rule::in(['unknown', ...array_column(app(CountryCatalogue::class)->all(), 'code')])]]); 'origin' => ['nullable', Rule::in(['unknown', ...array_column(app(CountryCatalogue::class)->all(), 'code')])]]);
$query = Lead::with(['investor:id,legal_name', 'owner:id,name']) $query = Lead::with(['investor:id,legal_name', 'owner:id,name'])
->withCount(['tasks as overdue_tasks_count' => fn ($q) => $q->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())]); ->withCount(['tasks as overdue_tasks_count' => fn ($q) => $q->availableForWork()->where('due_at', '<', now())]);
if ($term = $filters['q'] ?? null) { if ($term = $filters['q'] ?? null) {
$query->where(fn ($q) => $q->whereLike('title', "%{$term}%") $query->where(fn ($q) => $q->whereLike('title', "%{$term}%")
->orWhereHas('investor', fn ($investor) => $investor->whereLike('legal_name', "%{$term}%"))); ->orWhereHas('investor', fn ($investor) => $investor->whereLike('legal_name', "%{$term}%")));
@@ -127,29 +142,37 @@ class CrmController extends Controller
return redirect('/management/crm/leads/'.$lead->id)->with('success', 'Pedido convertido em lead com responsável e próxima acção.'); return redirect('/management/crm/leads/'.$lead->id)->with('success', 'Pedido convertido em lead com responsável e próxima acção.');
} }
public function show(Lead $lead): Response public function show(Request $request, Lead $lead): Response
{ {
$lead->load(['investor', 'owner:id,name', 'tasks' => fn ($q) => $q->orderBy('due_at')]); $lead->load(['investor', 'owner:id,name', 'tasks' => fn ($q) => $q->orderBy('due_at')]);
$caseIds = $lead->tasks->pluck('desk_case_id')->filter();
$closedCases = $caseIds->isEmpty() ? [] : DB::table('desk_cases')->whereIn('id', $caseIds)->whereNotNull('closed_at')->pluck('id')->all();
foreach ($lead->tasks as $task) {
$task->setAttribute('can_update', ! in_array($task->getAttribute('desk_case_id'), $closedCases, true));
}
$contacts = DB::table('investor_contacts')->join('contacts', 'contacts.id', '=', 'investor_contacts.contact_id') $contacts = DB::table('investor_contacts')->join('contacts', 'contacts.id', '=', 'investor_contacts.contact_id')
->where('investor_id', $lead->investor_id)->whereNull('contacts.deleted_at')->get(['contacts.id', 'full_name', 'email', 'phone']); ->where('investor_id', $lead->investor_id)->whereNull('contacts.deleted_at')->get(['contacts.id', 'full_name', 'email', 'phone']);
return Inertia::render('crm/lead', ['lead' => $lead, 'contacts' => $contacts, 'owners' => $this->owners()]); return Inertia::render('crm/lead', ['lead' => $lead, 'contacts' => $contacts, 'owners' => $this->owners(), 'taskCreation' => app(CrmTaskCreation::class)->context($request->user(), $lead),
'nextAction' => ['future_tasks' => app(CrmNextAction::class)->future($lead)->count()]]);
} }
public function update(Request $request, Lead $lead): RedirectResponse public function update(Request $request, Lead $lead): RedirectResponse
{ {
$data = $request->validate(['owner_user_id' => ['required', 'integer', Rule::in($this->owners()->pluck('id'))], $data = $request->validate(['version' => 'required|integer|min:1', 'owner_user_id' => ['required', 'integer', Rule::in($this->owners()->pluck('id'))],
'status' => ['required', Rule::in(['new', 'qualified', 'disqualified'])], 'status' => ['required', Rule::in(['new', 'qualified', 'disqualified'])],
'qualification_reason' => ['required', 'string', 'min:10', 'max:2000']]); 'qualification_reason' => ['required', 'string', 'min:10', 'max:2000']], self::VERSION_MESSAGES);
DB::transaction(function () use ($lead, $data, $request) { $version = (int) $data['version'];
unset($data['version']);
DB::transaction(function () use ($lead, $data, $request, $version) {
$lead = Lead::lockForUpdate()->findOrFail($lead->id); $lead = Lead::lockForUpdate()->findOrFail($lead->id);
if ($lead->status === 'converted') { if ($lead->status === 'converted') {
throw ValidationException::withMessages(['status' => 'O lead já foi convertido numa negociação.']); throw ValidationException::withMessages(['status' => 'O lead já foi convertido numa negociação.']);
} }
if ($data['status'] !== 'disqualified' && ! $lead->tasks()->whereIn('status', ['open', 'in_progress'])->where('due_at', '>', now())->exists()) { if ($data['status'] !== 'disqualified' && ! app(CrmNextAction::class)->future($lead)->exists()) {
throw ValidationException::withMessages(['status' => 'Registe uma próxima acção com prazo futuro antes de activar ou qualificar o lead.']); throw ValidationException::withMessages(['status' => 'Registe uma próxima acção com prazo futuro antes de activar ou qualificar o lead.']);
} }
PortalAudit::save($lead, $data, $request->user()->id); PortalAudit::save($lead, $data, $request->user()->id, $version);
}); });
return back()->with('success', 'Lead actualizado.'); return back()->with('success', 'Lead actualizado.');
@@ -157,24 +180,39 @@ class CrmController extends Controller
public function task(Request $request, Lead $lead): RedirectResponse public function task(Request $request, Lead $lead): RedirectResponse
{ {
$data = $request->validate(['title' => ['required', 'string', 'max:200'], 'due_at' => ['required', 'date', 'after:now'], $result = app(CrmTaskCreation::class)->create($request->user(), $lead, $request->all(), $this->owners()->pluck('id')->all());
'assignee_user_id' => ['required', 'integer', Rule::in($this->owners()->pluck('id'))]]);
PortalAudit::save(new CrmTask, [...$data, 'lead_id' => $lead->id, 'status' => 'open'], $request->user()->id);
return back()->with('success', 'Tarefa criada.'); return redirect('/management/crm/leads/'.$lead->id)->with('success', $result['replayed'] ? 'A tarefa já tinha sido registada. A criação não foi repetida.' : 'Tarefa criada.');
}
public function taskPreparation(Request $request, Lead $lead): JsonResponse
{
// Preserve the user's partial text; business validation still occurs only on task creation.
$input = json_decode($request->getContent(), true);
if (! is_array($input)) {
throw ValidationException::withMessages(['snapshot' => 'A preparação deve ser enviada em JSON.']);
}
return response()->json(app(CrmTaskPreparations::class)->save($request->user(), $lead, $input));
} }
public function updateTask(Request $request, Lead $lead, CrmTask $task): RedirectResponse public function updateTask(Request $request, Lead $lead, CrmTask $task): RedirectResponse
{ {
abort_unless($task->lead_id === $lead->id, 404); abort_unless($task->lead_id === $lead->id, 404);
$data = $request->validate(['status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])]]); $data = $request->validate(['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])]], self::VERSION_MESSAGES);
DB::transaction(function () use ($lead, $task, $data, $request) { $version = (int) $data['version'];
$lead = Lead::lockForUpdate()->findOrFail($lead->id); unset($data['version']);
if (in_array($lead->status, ['new', 'qualified'], true) && in_array($data['status'], ['done', 'cancelled'], true) DB::transaction(function () use ($lead, $task, $data, $request, $version) {
&& ! $lead->tasks()->where('id', '!=', $task->id)->whereIn('status', ['open', 'in_progress'])->where('due_at', '>', now())->exists()) { if ($task->getAttribute('desk_case_id')) {
throw ValidationException::withMessages(['status' => 'Crie a próxima acção antes de encerrar a última tarefa de um lead activo.']); $case = DB::table('desk_cases')->where('id', $task->getAttribute('desk_case_id'))->lockForUpdate()->first();
abort_unless($case !== null, 404);
app(VirtualDesk::class)->assertOpen($case);
} }
PortalAudit::save($task, $data, $request->user()->id); $lead = Lead::lockForUpdate()->findOrFail($lead->id);
$task = CrmTask::lockForUpdate()->findOrFail($task->id);
abort_unless($task->lead_id === $lead->id, 404);
app(CrmNextAction::class)->assertMayFinish($lead, $task, $data['status']);
PortalAudit::save($task, $data, $request->user()->id, $version);
}); });
return back()->with('success', 'Tarefa actualizada.'); return back()->with('success', 'Tarefa actualizada.');
+11 -3
View File
@@ -5,7 +5,9 @@ namespace App\Http\Controllers;
use App\Models\InterestRequest; use App\Models\InterestRequest;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Models\Sector; use App\Models\Sector;
use App\Services\DashboardWorkQueue;
use App\Services\InvestorPath; use App\Services\InvestorPath;
use App\Services\PortalEditorialWorkflow;
use App\Services\PortalProfileAccess; use App\Services\PortalProfileAccess;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
@@ -16,12 +18,18 @@ class DashboardController extends Controller
{ {
public function __invoke(Request $request): Response public function __invoke(Request $request): Response
{ {
if (! $request->user()->can('manage-portal')) { $validated = $request->validate(['interests_page' => 'sometimes|integer|min:1', 'desk_page' => 'sometimes|integer|min:1', 'crm_tasks_page' => 'sometimes|integer|min:1']);
$pages = [];
foreach (['interests_page', 'desk_page', 'crm_tasks_page'] as $key) {
$pages[$key] = (int) ($validated[$key] ?? 1);
}
$workQueue = app(DashboardWorkQueue::class)->forActor($request->user(), $pages);
if (! $request->user()->can('manage-portal') || app(PortalProfileAccess::class)->has($request->user(), 'auditor')) {
$path = app(InvestorPath::class); $path = app(InvestorPath::class);
$contexts = $path->contexts($request->user()); $contexts = $path->contexts($request->user());
$current = $contexts ? $path->view($request->user(), $contexts[0]['id']) : null; $current = $contexts ? $path->view($request->user(), $contexts[0]['id']) : null;
return Inertia::render('dashboard', ['summary' => null, 'investorPath' => $path->available() ? [ return Inertia::render('dashboard', ['editorialQueue' => app(PortalEditorialWorkflow::class)->dashboard($request->user()), 'summary' => null, 'workQueue' => $workQueue, 'investorPath' => $path->available() ? [
'contexts' => $contexts, 'contexts' => $contexts,
'current' => $current ? ['id' => $current['case']['id'], 'next' => $current['next'], 'current' => $current ? ['id' => $current['case']['id'], 'next' => $current['next'],
'pending' => count(array_filter($current['steps'], fn ($step) => ! in_array($step['state'], ['completed', 'approved', 'dispensed'], true))), 'pending' => count(array_filter($current['steps'], fn ($step) => ! in_array($step['state'], ['completed', 'approved', 'dispensed'], true))),
@@ -36,7 +44,7 @@ class DashboardController extends Controller
$drafts = app(PortalProfileAccess::class)->scope($drafts, $request->user()); $drafts = app(PortalProfileAccess::class)->scope($drafts, $request->user());
} }
return Inertia::render('dashboard', ['summary' => [ return Inertia::render('dashboard', ['editorialQueue' => app(PortalEditorialWorkflow::class)->dashboard($request->user()), 'workQueue' => $workQueue, 'summary' => [
'canCreateOpportunity' => app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()), 'canCreateOpportunity' => app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()),
'requestsByStatus' => collect(['received', 'in_review', 'contacted', 'closed']) 'requestsByStatus' => collect(['received', 'in_review', 'contacted', 'closed'])
->mapWithKeys(fn ($status) => [$status => (int) ($counts[$status] ?? 0)]), ->mapWithKeys(fn ($status) => [$status => (int) ($counts[$status] ?? 0)]),
@@ -0,0 +1,87 @@
<?php
namespace App\Http\Controllers;
use App\Services\DemographicEvidence;
use App\Services\DemographicImport;
use App\Services\DemographicInstallation;
use App\Services\PortalEditorialWorkflow;
use App\Services\SectorContentAnalysis;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inertia\Inertia;
use Inertia\Response;
final class DemographyController extends Controller
{
public function index(Request $request, DemographicEvidence $service): Response|JsonResponse
{
$data = $request->validate(['territories' => 'nullable|array|max:4', 'territories.*' => 'required|uuid|distinct',
'start_year' => 'nullable|integer|between:1900,2100', 'end_year' => 'nullable|integer|between:1900,2100|gte:start_year',
'sector' => 'nullable|in:'.implode(',', array_keys(DemographicEvidence::sectors())), 'edition' => 'nullable|uuid', 'investment_context' => 'nullable|boolean']);
$start = (int) ($data['start_year'] ?? date('Y'));
$end = (int) ($data['end_year'] ?? $start);
abort_unless($end >= $start && $end - $start <= 50, 422, 'Escolha um horizonte até 50 anos.');
$evidence = $service->analyse($data['territories'] ?? [], $start, $end, $data['sector'] ?? 'general', $data['edition'] ?? null);
if (! empty($data['investment_context']) && count($data['territories'] ?? []) === 1) {
$evidence = $service->investmentContext($data['territories'][0], $start, $end, $data['sector'] ?? 'general', $data['edition'] ?? null);
}
if ($request->expectsJson()) {
return response()->json($evidence);
}
$territories = $service->territories()->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']);
return Inertia::render('investment/demography', ['sectorReadings' => app(SectorContentAnalysis::class)->forTerritories($data['territories'] ?? []), 'evidence' => $evidence, 'filters' => $data, 'territories' => $territories, 'sectors' => DemographicEvidence::sectors()]);
}
public function management(Request $request, DemographicImport $service): Response|RedirectResponse
{
if (! Schema::hasTable('demographic_imports')) {
return redirect('/management/demography/install');
}
$service->authorize($request->user());
$data = $request->validate(['batch' => 'nullable|uuid']);
$workflow = app(PortalEditorialWorkflow::class);
$editorial = $workflow->demographyAvailable();
return Inertia::render('management/demography', ['editorialEnabled' => $editorial, 'editorialRevision' => $editorial && isset($data['batch']) ? (int) ($workflow->latestDemography($data['batch'])->revision_no ?? 0) : 0, 'qa' => ! app(DemographicInstallation::class)->activeTarget(), 'batches' => DB::table('demographic_imports')->orderByDesc('created_at')->get(['id', 'file_name', 'publication_version', 'status', 'created_at']),
'preview' => isset($data['batch']) ? $service->preview($request->user(), $data['batch']) : null]);
}
public function installation(Request $request, DemographicInstallation $service): Response
{
return Inertia::render('management/demography-install', ['plan' => $service->preview($request->user())]);
}
public function install(Request $request, DemographicInstallation $service): JsonResponse
{
return response()->json($service->apply($request->user(), $request->all()));
}
public function prepare(Request $request, DemographicImport $service): JsonResponse
{
$data = $request->validate(['file' => 'required|file|mimes:xlsx|max:19531', 'publication_version' => 'required|string|max:255', 'baseline_year' => 'nullable|integer|between:1900,2100']);
$file = $request->file('file');
return response()->json($service->prepare($request->user(), $file->getRealPath(), $file->getClientOriginalName(), $data['publication_version'], isset($data['baseline_year']) ? (int) $data['baseline_year'] : null));
}
public function confirm(Request $request, string $id, DemographicImport $service): JsonResponse
{
$data = $request->validate(['sha256' => 'required|string|size:64', 'mapping' => 'present|array', 'mapping.*' => 'required|uuid', 'reason' => 'required|string|min:10|max:2000']);
return response()->json($service->confirm($request->user(), $id, $data['sha256'], $data['mapping'], $data['reason']));
}
public function transition(Request $request, string $id, DemographicImport $service): JsonResponse
{
$data = $request->validate(['action' => 'required|in:approved,disabled', 'reason' => 'required|string|min:10|max:2000']);
$service->transition($request->user(), $id, $data['action'], $data['reason']);
return response()->json(['id' => $id, 'status' => $data['action']]);
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Controllers;
use App\Services\DeskRequestCheckpoints;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class DeskRequestCheckpointController extends Controller
{
public function show(Request $request, string $id, DeskRequestCheckpoints $checkpoints): JsonResponse
{
return response()->json($checkpoints->show($request->user(), $id));
}
public function save(Request $request, string $id, DeskRequestCheckpoints $checkpoints): JsonResponse
{
return response()->json($checkpoints->save($request->user(), $id, $request->all()));
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Http\Controllers;
use App\Services\DeskServiceAvailability;
use App\Services\DeskServiceEditor;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class DeskServiceEditorController extends Controller
{
public function index(Request $request, DeskServiceEditor $editor): Response|JsonResponse
{
$data = ['services' => $editor->listing(), 'schedulingAvailable' => app(DeskServiceAvailability::class)->scheduled(), 'today' => now()->toDateString(), 'calendarTimezone' => config('app.timezone')];
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/service-editor', $data);
}
public function publish(Request $request, DeskServiceEditor $editor, string $code): JsonResponse|RedirectResponse
{
$row = $editor->publish($request->user(), $code, $request->all());
return $request->expectsJson() ? response()->json(['id' => $row->id, 'version' => $row->version, 'effective_from' => $row->effective_from ?? null], 201)
: back()->with('success', 'Versão publicada'.(($row->effective_from ?? null) ? ' com entrada em vigor em '.$row->effective_from : '').'. Os pedidos existentes conservam a sua versão.');
}
public function history(Request $request, DeskServiceEditor $editor, string $code): JsonResponse
{
$data = $request->validate(['page' => ['nullable', 'integer', 'min:1']]);
return response()->json($editor->history($code, (int) ($data['page'] ?? 1)));
}
}
@@ -2,28 +2,28 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware; use App\Services\Malware\DocumentScanRetry;
use App\Services\DocumentManagementAccess; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DocumentMalwareController extends Controller class DocumentMalwareController extends Controller
{ {
public function retry(Request $request, string $id): RedirectResponse public function retry(Request $request, string $id): RedirectResponse|JsonResponse
{ {
DB::transaction(function () use ($id, $request): void { $result = app(DocumentScanRetry::class)->request($request->user(), $id);
$document = app(DocumentManagementAccess::class)->documents($request->user())->where('id', $id)->lockForUpdate()->first(); $message = match ($result['outcome']) {
abort_unless($document && $document->status !== 'deleted' && $document->deleted_at === null, 404); 'accepted' => 'Pedido de análise aceite pelo serviço de envio. Acompanhe o estado do ficheiro até haver resultado.',
abort_unless(in_array($document->malware_scan_status, ['pending', 'inconclusive', 'failed'], true), 422, 'duplicate' => 'Já existe uma reserva de análise para este ficheiro. Não foi enviado outro pedido. Acompanhe o estado antes de repetir.',
'Só é possível repetir uma análise pendente, inconclusiva ou falhada. Para substituir um ficheiro, carregue uma nova versão.'); 'stale' => 'O ficheiro ou o seu acesso mudou. Actualize a página para consultar o estado antes de repetir.',
'unconfirmed' => 'Não foi possível confirmar o envio da análise. Consulte o estado antes de repetir. Referência: '.$result['reference'],
default => 'Pedido preparado para envio após a confirmação da gravação. Acompanhe o estado do ficheiro.',
};
DB::table('documents')->where('id', $id)->update([ if ($request->expectsJson()) {
'status' => 'quarantined', 'malware_scan_status' => 'pending', 'malware_failure_reason' => null, 'updated_at' => now(), return response()->json([...$result, 'message' => $message], $result['outcome'] === 'unconfirmed' ? 503 : 200)->header('Cache-Control', 'no-store, private');
]); }
ScanDocumentForMalware::dispatch($id)->afterCommit();
});
return back()->with('success', 'Nova análise colocada na fila. O ficheiro permanece privado até haver resultado.'); return back()->with($result['outcome'] === 'accepted' ? 'success' : 'warning', $message);
} }
} }
@@ -5,6 +5,7 @@ namespace App\Http\Controllers;
use App\Services\DocumentManagementAccess; use App\Services\DocumentManagementAccess;
use App\Services\EditorialInstallation; use App\Services\EditorialInstallation;
use App\Services\EditorialReading; use App\Services\EditorialReading;
use App\Services\PortalEditorialWorkflow;
use App\Services\PortalProfileAccess; use App\Services\PortalProfileAccess;
use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\Builder;
@@ -97,11 +98,17 @@ class EditorialArticleController extends Controller
app(DocumentManagementAccess::class)->assertEditableResource(request()->user(), $id); app(DocumentManagementAccess::class)->assertEditableResource(request()->user(), $id);
$r = DB::table('portal_resources')->where('id', $id)->first(); $r = DB::table('portal_resources')->where('id', $id)->first();
abort_unless($r instanceof \stdClass, 404); abort_unless($r instanceof \stdClass, 404);
$workflow = app(PortalEditorialWorkflow::class);
if ($workflow->enabled()) {
$workflow->authorize(request()->user(), $id);
$r = $workflow->workingResource($r);
}
$reading = app(EditorialReading::class); $reading = app(EditorialReading::class);
$original = $reading->original($r); $original = $reading->original($r);
$content = $reading->content($r, $original); $content = $reading->content($r, $original);
return tap(Inertia::render('portal/article-editor', ['resource' => ['id' => $r->id, 'title' => $r->title, 'metadata_version' => $r->metadata_version, 'published' => (bool) $r->published], return tap(Inertia::render('portal/article-editor', ['resource' => ['id' => $r->id, 'title' => $r->title, 'metadata_version' => $r->metadata_version, 'published' => (bool) $r->published],
'workflowEnabled' => $workflow->enabled(), 'workflow' => $workflow->latest($id),
'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']), 'content' => $content, 'source' => $original ? array_intersect_key($original, array_flip(['source_url', 'published_at', 'modified_at', 'legacy_id', 'image_source_url'])) : null, 'images' => $this->publicResources()->whereIn('d.media_type', ['image/png', 'image/jpeg', 'image/webp'])->get(['r.id', 'r.title']),
'revisions' => DB::table('portal_resource_revisions')->where('resource_id', $id)->orderByDesc('revision_no')->get(['revision_no', 'change_type', 'created_at'])])->toResponse(request()), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store')); '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'));
} }
@@ -114,7 +121,9 @@ class EditorialArticleController extends Controller
$r = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first(); $r = DB::table('portal_resources')->where('id', $id)->lockForUpdate()->first();
abort_unless($r !== null, 404); abort_unless($r !== null, 404);
app(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.'); $workflow = app(PortalEditorialWorkflow::class);
$current = $workflow->enabled() ? $workflow->workingResource($r) : $r;
abort_unless((int) $current->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.');
} }
@@ -122,7 +131,13 @@ 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 = $this->edition($r, $data); $workflow = app(PortalEditorialWorkflow::class);
$content = $this->edition($workflow->enabled() ? $workflow->workingResource($r) : $r, $data);
if ($workflow->enabled()) {
$workflow->save($request->user(), $id, (int) $data['metadata_version'], ['editorial_content' => json_encode($content, JSON_THROW_ON_ERROR)]);
return;
}
$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')->where('id', $id)->first(); $resource = DB::table('portal_resources')->where('id', $id)->first();
@@ -165,6 +180,11 @@ class EditorialArticleController extends Controller
app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id); app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
$resource = DB::table('portal_resources')->where('id', $id)->first(); $resource = DB::table('portal_resources')->where('id', $id)->first();
abort_unless($resource instanceof \stdClass, 404); abort_unless($resource instanceof \stdClass, 404);
$workflow = app(PortalEditorialWorkflow::class);
if ($workflow->enabled()) {
$workflow->authorize(request()->user(), $id);
$resource = $workflow->workingResource($resource);
}
return tap(Inertia::render('portal/article', ['article' => app(EditorialReading::class)->reading($resource, null, true)]) return tap(Inertia::render('portal/article', ['article' => app(EditorialReading::class)->reading($resource, null, true)])
->toResponse($request), static function (Response $response): void { ->toResponse($request), static function (Response $response): void {
@@ -179,6 +199,11 @@ class EditorialArticleController extends Controller
app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id); app(DocumentManagementAccess::class)->assertEditableResource($request->user(), $id);
$resource = DB::table('portal_resources')->where('id', $id)->first(); $resource = DB::table('portal_resources')->where('id', $id)->first();
abort_unless($resource instanceof \stdClass, 404); abort_unless($resource instanceof \stdClass, 404);
$workflow = app(PortalEditorialWorkflow::class);
if ($workflow->enabled()) {
$workflow->authorize($request->user(), $id);
$resource = $workflow->workingResource($resource);
}
$data = $this->validateContent($request); $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.'); abort_unless((int) $resource->metadata_version === (int) $data['metadata_version'], 409, 'A revisão mudou; recupere antes de rever a prévia.');
+127 -44
View File
@@ -11,28 +11,45 @@ use App\Models\Sector;
use App\Models\Skill; use App\Models\Skill;
use App\Models\TrainingCapacity; use App\Models\TrainingCapacity;
use App\Models\TrainingProvider; use App\Models\TrainingProvider;
use App\Models\User;
use App\Services\EducationAccess;
use App\Services\EducationDeclarationDrafts;
use App\Services\EducationDeclarationRules;
use App\Services\EducationGapCalculator; use App\Services\EducationGapCalculator;
use App\Services\EducationReviews;
use App\Services\EducationWorkQueue;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
class EducationController extends Controller class EducationController extends Controller
{ {
public function index(Request $request): Response public function index(Request $request): \Symfony\Component\HttpFoundation\Response
{ {
$filters = $request->validate([ app(EducationAccess::class)->authorize($request->user());
'q' => ['nullable', 'string', 'max:150'], $filters = $this->filters($request);
'status' => ['nullable', Rule::in(['submitted', 'reviewed', 'rejected', 'expired'])], if (($filters['scope'] ?? 'all') === 'review') {
'geo_location_id' => ['nullable', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')], unset($filters['status']);
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'], }
'demand_page' => ['nullable', 'integer', 'min:1'], $draftService = app(EducationDeclarationDrafts::class);
'capacity_page' => ['nullable', 'integer', 'min:1'], $draftsAvailable = $draftService->installed();
]); $selectedDraft = null;
if (! empty($filters['draft'])) {
abort_unless($draftsAvailable, 404);
$kind = DB::table('education_declaration_drafts')->where('id', $filters['draft'])->where('owner_user_id', $request->user()->id)->value('kind');
abort_unless($kind !== null, 404);
$selectedDraft = $draftService->show($request->user(), $kind, $filters['draft']);
}
Inertia::encryptHistory();
$demands = LabourDemand::query(); $demands = LabourDemand::query();
$capacities = TrainingCapacity::query(); $capacities = TrainingCapacity::query();
$territoryIds = []; $territoryIds = [];
@@ -53,20 +70,36 @@ class EducationController extends Controller
} }
} }
// Viewing one's work must not remove existing territorial catalogue evidence.
$territorialCapacities = clone $capacities; $territorialCapacities = clone $capacities;
foreach ([$demands, $capacities] as $query) {
if (($filters['scope'] ?? 'all') === 'mine') {
$query->where('submitted_by', $request->user()->id);
} elseif (($filters['scope'] ?? 'all') === 'review') {
$query->where('submitted_by', '<>', $request->user()->id)->where('status', 'submitted')->where('valid_until', '>=', now()->toDateString());
}
}
$providers = TrainingProvider::where('status', '!=', 'inactive'); $providers = TrainingProvider::where('status', '!=', 'inactive');
$courses = Course::where('status', '!=', 'retired') $courses = Course::where('status', '!=', 'retired')
->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id')); ->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id'));
if ($territoryIds !== []) { if ($territoryIds !== []) {
// Provider and course location is evidenced by their submitted training capacity.
// Do not infer locations from provider names, addresses, or unrelated records.
$courses->whereIn('id', $territorialCapacities->select('course_id')); $courses->whereIn('id', $territorialCapacities->select('course_id'));
$providers->whereIn('id', (clone $courses)->select('provider_id')); $providers->whereIn('id', (clone $courses)->select('provider_id'));
} }
return Inertia::render('education/index', [ return tap(Inertia::render('education/index', [
'demands' => $demands->latest()->orderBy('id')->paginate(20, ['*'], 'demand_page')->withQueryString(), 'workQueue' => app(EducationWorkQueue::class)->summary($request->user()),
'capacities' => $capacities->latest()->orderBy('id')->paginate(20, ['*'], 'capacity_page')->withQueryString(), 'draftsAvailable' => $draftsAvailable, 'selectedDraft' => $selectedDraft,
'ownDrafts' => $draftsAvailable ? DB::table('education_declaration_drafts')->where('owner_user_id', $request->user()->id)
->orderByDesc('updated_at')->orderBy('id')->paginate(20, ['id', 'kind', 'version_no', 'state', 'updated_at', 'payload'], 'draft_page')->withQueryString()
->through(function ($row) {
$payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
return ['id' => $row->id, 'kind' => $row->kind, 'version_no' => (int) $row->version_no, 'state' => $row->state,
'updated_at' => CarbonImmutable::parse($row->updated_at)->toIso8601String(), 'label' => $payload['qualification'] ?? null];
}) : null,
'demands' => $demands->latest()->orderBy('id')->paginate(20, ['*'], 'demand_page')->withQueryString()->through(fn (LabourDemand $row) => $this->listing($row, 'demands', $request, $filters)),
'capacities' => $capacities->latest()->orderBy('id')->paginate(20, ['*'], 'capacity_page')->withQueryString()->through(fn (TrainingCapacity $row) => $this->listing($row, 'capacities', $request, $filters)),
'filters' => $filters, 'filters' => $filters,
'indicators' => [ 'indicators' => [
'demand_records' => LabourDemand::count(), 'demand_records' => LabourDemand::count(),
@@ -83,9 +116,63 @@ class EducationController extends Controller
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality']) ->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])
->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']), ->orderBy('name')->get(['id', 'name', 'parent_id', 'location_type']),
'today' => now()->toDateString(), 'today' => now()->toDateString(),
])->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
/** @return array<string,mixed> */
private function filters(Request $request): array
{
return $request->validate([
'q' => ['nullable', 'string', 'max:150'],
'status' => ['nullable', Rule::in(['submitted', 'reviewed', 'rejected', 'expired'])],
'geo_location_id' => ['nullable', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
'demand_page' => ['nullable', 'integer', 'min:1'],
'capacity_page' => ['nullable', 'integer', 'min:1'],
'draft' => ['nullable', 'uuid'], 'draft_page' => ['nullable', 'integer', 'min:1'],
'scope' => ['nullable', Rule::in(['all', 'mine', 'review'])],
]); ]);
} }
/** @param array<string,mixed> $filters
* @return array<string,mixed> */
private function listing(LabourDemand|TrainingCapacity $record, string $kind, Request $request, array $filters): array
{
$unavailable = $record->getAttribute('valid_until') < now()->toDateString() ? 'expired' : ((int) $record->getAttribute('submitted_by') === $request->user()->id ? 'self' : null);
return [...$record->toArray(), 'can_review' => $unavailable === null, 'review_unavailable' => $unavailable,
'details_url' => route('management.education.declaration', ['kind' => $kind, 'id' => $record->id, ...$filters], false)];
}
public function declaration(Request $request, string $kind, string $id): \Symfony\Component\HttpFoundation\Response
{
app(EducationAccess::class)->authorize($request->user());
$model = match ($kind) {
'demands' => LabourDemand::class,'capacities' => TrainingCapacity::class,default => abort(404)
};
$record = $model::findOrFail($id);
$filters = $this->filters($request);
$request->validate(['history_page' => ['nullable', 'integer', 'min:1']]);
$row = $this->listing($record, $kind, $request, $filters);
$row['review_context'] = app(EducationReviews::class)->context($request->user(), $record);
$row['submitted_by_name'] = User::whereKey($record->getAttribute('submitted_by'))->value('name');
$row['reviewed_by_name'] = $record->getAttribute('reviewed_by') ? User::whereKey($record->getAttribute('reviewed_by'))->value('name') : null;
$references = ['occupation' => Occupation::whereKey($record->getAttribute('occupation_id'))->value('name'),
'skill' => Skill::whereKey($record->getAttribute('skill_id'))->value('name'),
'location' => collect(app(InvestmentGeography::class)->path($record->getAttribute('geo_location_id'), true))->pluck('name')->implode(' › ')];
if ($kind === 'demands') {
$references['project'] = Project::whereKey($record->getAttribute('project_id'))->value('name');
} else {
$references['course'] = Course::whereKey($record->getAttribute('course_id'))->value('title');
}
Inertia::encryptHistory();
return tap(Inertia::render('education/declaration', ['declaration' => $row, 'kind' => $kind, 'actorId' => $request->user()->id, 'today' => now()->toDateString(),
'preparation' => app(EducationReviews::class)->preparation($request->user(), $record),
'history' => app(EducationReviews::class)->history($request->user(), $record),
'backUrl' => route('management.education.index', $filters, false), 'references' => $references])->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function catalog(Request $request, string $kind): RedirectResponse public function catalog(Request $request, string $kind): RedirectResponse
{ {
$model = match ($kind) { $model = match ($kind) {
@@ -112,45 +199,41 @@ class EducationController extends Controller
public function store(Request $request, string $kind): RedirectResponse public function store(Request $request, string $kind): RedirectResponse
{ {
$demand = $kind === 'demands'; $demand = $kind === 'demands';
$data = $request->validate([ $data = $request->validate(EducationDeclarationRules::forKind($kind));
'occupation_id' => ['required', 'uuid', Rule::exists('occupations', 'id')->whereNull('deleted_at')],
'skill_id' => ['required', 'uuid', Rule::exists('skills', 'id')->whereNull('deleted_at')],
'geo_location_id' => ['required', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])],
$demand ? 'project_id' : 'course_id' => ['required', 'uuid', $demand
? Rule::exists('projects', 'id')->whereNull('deleted_at')
: Rule::exists('courses', 'id')->whereNull('deleted_at')->whereNot('status', 'retired')
->where(fn ($query) => $query->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id')))],
'employer' => [$demand ? 'required' : 'exclude', 'string', 'max:200'],
'qualification' => ['required', 'string', 'max:150'],
'quantity' => ['required', 'integer', 'min:1', 'max:10000000'],
'period_start' => ['required', 'date_format:Y-m-d'],
'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
'source' => ['required', 'string', 'min:10', 'max:5000'],
'reference_date' => ['required', 'date_format:Y-m-d', 'before_or_equal:today'],
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:reference_date'],
]);
PortalAudit::save($demand ? new LabourDemand : new TrainingCapacity, PortalAudit::save($demand ? new LabourDemand : new TrainingCapacity,
[...$data, 'submitted_by' => $request->user()->id, 'status' => 'submitted'], $request->user()->id); [...$data, 'submitted_by' => $request->user()->id, 'status' => 'submitted'], $request->user()->id);
return back()->with('success', 'Declaração registada para revisão independente.'); return back()->with('success', 'Declaração registada para revisão independente.');
} }
public function reviewPreparation(Request $request, string $kind, string $id): JsonResponse
{
$service = app(EducationReviews::class);
app(EducationAccess::class)->authorize($request->user());
if ($request->isMethod('POST')) {
// Like CRM preparations, retain partial text before business validation.
$input = json_decode($request->getContent(), true);
if (! is_array($input)) {
throw ValidationException::withMessages(['snapshot' => 'A preparação deve ser enviada em JSON.']);
}
$view = $service->savePreparation($request->user(), $kind, $id, $input);
} else {
$expected = $request->validate(['actor_id' => 'sometimes|required|integer|min:1']);
abort_if(isset($expected['actor_id']) && (int) $expected['actor_id'] !== $request->user()->id, 409, 'A conta mudou. Actualize a entrada antes de recuperar.');
$record = match ($kind) {
'demands' => LabourDemand::findOrFail($id), 'capacities' => TrainingCapacity::findOrFail($id), default => abort(404)
};
$view = $service->preparation($request->user(), $record);
}
return response()->json($view)->header('Cache-Control', 'private, no-store');
}
public function review(Request $request, string $kind, string $id): RedirectResponse public function review(Request $request, string $kind, string $id): RedirectResponse
{ {
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], $result = app(EducationReviews::class)->decide($request->user(), $kind, $id, $request->all());
'status' => ['required', 'in:reviewed,rejected'], 'review_reason' => ['required', 'string', 'min:15', 'max:3000']]);
$model = $kind === 'demands' ? LabourDemand::class : TrainingCapacity::class;
DB::transaction(function () use ($model, $id, $data, $request) {
$record = $model::whereKey($id)->lockForUpdate()->firstOrFail();
abort_if((int) $record->getAttribute('submitted_by') === $request->user()->id, 403, 'Outro gestor deve efectuar a revisão.');
abort_if((int) $record->getAttribute('version_no') !== $data['version_no'], 409, 'A versão foi alterada. Recarregue antes de decidir.');
abort_if($record->getAttribute('valid_until') < now()->toDateString(), 422, 'A fonte expirou.');
PortalAudit::save($record, [...$data, 'version_no' => $data['version_no'] + 1,
'reviewed_by' => $request->user()->id], $request->user()->id);
});
return back()->with('success', 'Revisão interna registada; não substitui decisão institucional.'); return back()->with('success', $result['replayed'] ? 'A revisão já tinha sido registada.' : 'Revisão interna registada; não substitui decisão institucional.');
} }
public function analysis(string $id, EducationGapCalculator $calculator): Response public function analysis(string $id, EducationGapCalculator $calculator): Response
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Controllers;
use App\Services\EducationDeclarationDrafts;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
final class EducationDeclarationDraftController extends Controller
{
public function index(Request $request, string $kind, EducationDeclarationDrafts $drafts): JsonResponse
{
$drafts->guard($request->user(), $kind);
return response()->json(DB::table('education_declaration_drafts')->where('owner_user_id', $request->user()->id)->where('kind', $kind)
->orderByDesc('updated_at')->orderBy('id')->paginate(20, ['id', 'kind', 'version_no', 'state', 'updated_at']))->header('Cache-Control', 'private, no-store');
}
public function show(Request $request, string $kind, string $id, EducationDeclarationDrafts $drafts): JsonResponse
{
return response()->json($drafts->show($request->user(), $kind, $id))->header('Cache-Control', 'private, no-store');
}
public function save(Request $request, string $kind, EducationDeclarationDrafts $drafts, ?string $id = null): JsonResponse
{
return response()->json($drafts->save($request->user(), $kind, $id, $request->all()))->header('Cache-Control', 'private, no-store');
}
public function submit(Request $request, string $kind, string $id, EducationDeclarationDrafts $drafts): JsonResponse
{
return response()->json($drafts->submit($request->user(), $kind, $id, $request->all()))->header('Cache-Control', 'private, no-store');
}
}
@@ -7,6 +7,7 @@ use App\Models\ExistingBusinessObject;
use App\Models\Sector; use App\Models\Sector;
use App\Policies\ExistingBusinessPolicy; use App\Policies\ExistingBusinessPolicy;
use App\Services\BusinessFormSchema; use App\Services\BusinessFormSchema;
use App\Services\BusinessPointPublication;
use App\Services\CountryCatalogue; use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessDrafts; use App\Services\ExistingBusinessDrafts;
use App\Services\ExistingBusinessIntake; use App\Services\ExistingBusinessIntake;
@@ -69,6 +70,7 @@ class ExistingBusinessController extends Controller
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' => 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),
'pointPublicationAvailable' => app(BusinessPointPublication::class)->available(), 'registeredLocation' => app(BusinessPointPublication::class)->registered($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,251 @@
<?php
namespace App\Http\Controllers;
use App\Models\Sector;
use App\Services\DocumentManagementAccess;
use App\Services\FundingDossierPreparation;
use App\Services\FundingInstitutionClassification;
use App\Services\FundingInstitutionDetails;
use App\Services\FundingProgrammeReferences;
use App\Services\FundingProgrammes;
use App\Services\InvestmentGeography;
use App\Services\InvestorContext;
use App\Services\InvestorPath;
use App\Services\Procurement;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
final class FundingProgrammeController extends Controller
{
public function reference(Request $request, string $code, FundingProgrammeReferences $references): \Symfony\Component\HttpFoundation\Response
{
$plan = $references->preview($request->user(), $code);
if ($request->expectsJson()) {
return response()->json($plan)->header('Cache-Control', 'private, no-store');
}
return tap(Inertia::render('funding/reference', ['reference' => $plan])->toResponse($request),
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function prepareReference(Request $request, string $code, FundingProgrammeReferences $references): RedirectResponse|JsonResponse
{
$data = $request->validate(['hash' => 'required|string|size:64']);
$result = $references->prepare($request->user(), $code, $data['hash']);
if ($request->expectsJson()) {
$reference = $references->preview($request->user(), $code);
$service = app(FundingProgrammes::class);
$matches = $service->matchesReference($request->user(), $result['id'], $reference['draft']);
$publication = $matches ? $service->preview($request->user(), $result['id']) : null;
return response()->json([...$result, 'matches_reference' => $matches, 'publication' => $publication ? ['version' => $publication['version'], 'hash' => $publication['hash']] : null])->header('Cache-Control', 'private, no-store');
}
return redirect('/management/fundos/'.$result['id'])->with('success', $result['created']
? 'Rascunho preparado com as fontes indicadas. Ainda não está publicado.'
: 'Esta referência já tem ficha. Aberta a versão existente, sem substituir alterações ou acrescentar chamadas.');
}
public function assisted(Request $request, FundingProgrammeReferences $references): \Symfony\Component\HttpFoundation\Response
{
return tap(Inertia::render('funding/assisted', ['batch' => $references->assisted($request->user())])->toResponse($request), static fn ($response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function manage(Request $request, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
{
$service->guard($request->user());
$items = DB::table('funding_programmes')->orderByDesc('updated_at')->paginate(20);
$items->through(fn ($row) => ['id' => $row->id, 'title' => json_decode($row->draft, true)['title'] ?? 'Rascunho sem título',
'version' => (int) $row->version, 'published' => $row->published_version_id !== null]);
return tap(Inertia::render('funding/manage', ['items' => $items, 'references' => app(FundingProgrammeReferences::class)->choices($request->user())])->toResponse($request),
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function edit(Request $request, FundingProgrammes $service, ?string $id = null): \Symfony\Component\HttpFoundation\Response
{
$service->guard($request->user());
$row = $id ? DB::table('funding_programmes')->where('id', $id)->firstOrFail() : null;
$editable = app(DocumentManagementAccess::class)->documents($request->user())->select('id');
$references = ['organizations' => DB::table('organizations')->whereNull('deleted_at')->orderBy('name')->get(['id', 'name']),
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name']),
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name']),
'documents' => DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->whereNull('d.deleted_at')->where(fn ($q) => $q->whereIn('d.id', $editable)
->orWhereIn('r.id', app(Procurement::class)->publicDocuments()->select('r.id')))
->orderBy('r.title')->get(['r.id', 'r.title'])];
return tap(Inertia::render('funding/edit', ['record' => $row ? ['id' => $row->id, 'code' => $row->code, 'version' => (int) $row->version,
'draft' => json_decode($row->draft, true), 'published' => $row->published_version_id !== null] : null,
'references' => Arr::only($references, ['organizations', 'sectors', 'territories', 'documents']),
'categories' => FundingInstitutionClassification::CATEGORIES, 'institutionTypes' => FundingInstitutionClassification::TYPES, 'institutionNatures' => FundingInstitutionDetails::NATURES, 'needs' => FundingInstitutionDetails::NEEDS,
'kinds' => FundingProgrammes::KINDS, 'windowModes' => FundingProgrammes::WINDOWS,
'history' => $id ? DB::table('funding_programme_versions')->where('programme_id', $id)->orderByDesc('version')->get(['version', 'reason', 'published_at']) : []])->toResponse($request),
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function save(Request $request, FundingProgrammes $service, ?string $id = null): RedirectResponse
{
$id = $service->save($request->user(), $id, $request->all());
return redirect('/management/fundos/'.$id)->with('success', 'Rascunho guardado. Confira a prévia antes de publicar.');
}
public function preview(Request $request, string $id, FundingProgrammes $service): JsonResponse
{
return response()->json($service->preview($request->user(), $id))->header('Cache-Control', 'private, no-store');
}
public function publish(Request $request, string $id, FundingProgrammes $service): RedirectResponse|JsonResponse
{
$versionId = $service->publish($request->user(), $id, $request->all());
if ($request->expectsJson()) {
return response()->json(['id' => $id, 'version_id' => $versionId, 'published' => true])->header('Cache-Control', 'private, no-store');
}
return back()->with('success', 'Nova versão publicada. Os interesses anteriores conservam a versão guardada.');
}
public function withdraw(Request $request, string $id, FundingProgrammes $service): RedirectResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'reason' => 'required|string|min:20|max:2000']);
$service->withdraw($request->user(), $id, $data['version'], $data['reason']);
return back()->with('success', 'Publicação retirada. Versões e interesses preservados.');
}
public function saved(Request $request, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
{
abort_unless($service->installed(), 404);
$items = DB::table('funding_programme_interests as i')
->join('funding_programme_versions as v', fn ($join) => $join->on('v.id', '=', 'i.version_id')->on('v.programme_id', '=', 'i.programme_id'))
->join('funding_programmes as p', 'p.id', '=', 'i.programme_id')
->where('i.user_id', $request->user()->id)->whereNull('i.removed_at')
->orderByDesc('i.saved_at')->orderBy('i.programme_id')
->paginate(20, ['i.programme_id', 'i.saved_at', 'v.version', 'v.payload', 'p.published_version_id'])->withQueryString();
$items->through(function ($row) use ($service) {
$current = $service->publicQuery()->where('p.id', $row->programme_id)->first(['v.version']);
$snapshot = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
return ['id' => $row->programme_id, 'title' => $snapshot['title'], 'saved_version' => (int) $row->version,
'saved_at' => $row->saved_at, 'available' => $current !== null, 'current_version' => $current ? (int) $current->version : null];
});
return tap(Inertia::render('funding/saved', ['items' => $items])->toResponse($request),
static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function index(Request $request, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
{
$filters = $request->validate(['q' => 'nullable|string|max:150', 'kind' => 'nullable|in:institution,fund,programme,incentive',
'category' => ['nullable', Rule::in(array_keys(FundingInstitutionClassification::CATEGORIES))], 'institution_type' => ['nullable', Rule::in(array_keys(FundingInstitutionClassification::TYPES))], 'location_mode' => 'nullable|in:physical,coverage', 'include_historical' => 'nullable|boolean',
'need' => ['nullable', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))],
'context' => 'nullable|uuid', 'opportunity' => 'nullable|string|max:150',
'province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid',
'territory' => ['nullable', 'uuid', Rule::in(app(InvestmentGeography::class)->publicReferences()->pluck('id')->all())],
'sector' => ['nullable', 'integer', Rule::in(Sector::choices()->whereNotNull('published_at')->pluck('id')->all())],
'certainty' => 'nullable|in:include_unknown,documented', 'state' => 'nullable|in:open,closed,upcoming,unknown']);
$filters = array_filter($filters, fn ($value) => $value !== null && $value !== '');
// A local search excludes unlocated records unless explicitly requested.
if (($filters['location_mode'] ?? '') === 'physical' && ! isset($filters['certainty'])) {
$filters['certainty'] = 'documented';
}
$dossier = $request->user() && ! empty($filters['context']) ? app(FundingDossierPreparation::class)->context($request->user(), $filters['context'], $filters['opportunity'] ?? null) : null;
$explicitLocation = $request->hasAny(['territory', 'province_id', 'district_id', 'admin_post_id', 'locality_id']);
if ($dossier && ! $explicitLocation && empty($filters['territory']) && $dossier['territory']) {
$filters['territory'] = $dossier['territory'];
}
$geography = app(InvestmentGeography::class);
$criteriaErrors = [];
$territorySelection = [];
try {
$filters = $geography->interestSelection($filters);
$territorySelection = ! empty($filters['territory']) ? $geography->path($filters['territory']) : [];
$query = $service->catalogueQuery($filters);
$items = $query->orderByDesc('v.published_at')->orderBy('p.id')->paginate(20, ['p.id', 'p.code', 'v.id as version_id', 'v.version', 'v.payload', 'v.published_at'])->withQueryString();
} catch (\Illuminate\Validation\ValidationException $error) {
if ($request->expectsJson()) throw $error;
$criteriaErrors = $error->errors();
$items = new \Illuminate\Pagination\LengthAwarePaginator([], 0, 20, 1, ['path' => '/fundos', 'query' => $request->query()]);
}
$items->through(function ($row) use ($service, $filters) {
$record = $service->present($row);
return [...$record, 'filter_explanation' => $service->filterExplanation($record, $filters)];
});
return tap(Inertia::render('funding/index', ['criteriaErrors' => $criteriaErrors, 'territorySelection' => $territorySelection, 'categoryTypes' => FundingInstitutionClassification::CATEGORY_TYPES, 'items' => $items, 'filters' => $filters, 'categories' => FundingInstitutionClassification::CATEGORIES, 'institutionTypes' => FundingInstitutionClassification::TYPES, 'kinds' => FundingProgrammes::KINDS, 'needs' => FundingInstitutionDetails::NEEDS, 'dossier' => $dossier,
'options' => ['territories' => $territorySelection,
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['id', 'name'])], 'management' => $service->access($request->user())])
->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function show(Request $request, string $id, FundingProgrammes $service): \Symfony\Component\HttpFoundation\Response
{
$request->validate(['context' => 'nullable|uuid', 'opportunity' => 'nullable|string|max:150', 'need' => ['nullable', Rule::in(array_keys(FundingInstitutionDetails::NEEDS))], 'territory' => 'nullable|uuid', 'category' => 'nullable|string|max:80', 'institution_type' => 'nullable|string|max:80', 'location_mode' => 'nullable|in:physical,coverage']);
$dossier = $request->user() && $request->filled('context') ? app(FundingDossierPreparation::class)->context($request->user(), $request->string('context')->toString(), $request->query('opportunity')) : null;
if ($dossier && ! $request->has('territory') && $dossier['territory']) {
$request->merge(['territory' => $dossier['territory']]);
}
$record = $service->published($id);
$destinations = [];
if ($request->user()) {
foreach (app(InvestorPath::class)->contexts($request->user()) as $item) {
$case = app(VirtualDesk::class)->case($request->user(), $item['id']);
$state = app(InvestorContext::class)->state($case);
$choices = $state['opportunity_choices'] ?? [];
if ($choices === []) {
$destinations[] = ['id' => $item['id'], 'opportunity' => null, 'title' => $item['title']];
}
foreach ($choices as $choice) {
$destinations[] = ['id' => $item['id'], 'opportunity' => $choice['opportunity']['key'], 'title' => $item['title'].' — '.$choice['opportunity']['title']];
}
}
}
$saved = $request->user() ? DB::table('funding_programme_interests as i')->join('funding_programme_versions as v', 'v.id', '=', 'i.version_id')
->where('i.programme_id', $id)->where('i.user_id', $request->user()->id)->whereNull('i.removed_at')->first(['v.version', 'i.saved_at']) : null;
return tap(Inertia::render('funding/show', ['record' => $record, 'saved' => $saved, 'authenticated' => $request->user() !== null, 'dossier' => $dossier, 'selection' => [...$request->only(['q', 'kind', 'sector', 'certainty', 'state', 'include_historical', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'page', 'need', 'territory', 'context', 'opportunity', 'category', 'institution_type', 'location_mode']), 'territory_label' => app(InvestmentGeography::class)->publicReferences()->where('id', $request->query('territory'))->value('name') ?? 'Local por seleccionar'], 'needs' => FundingInstitutionDetails::NEEDS, 'destinations' => $destinations])
->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function dossier(Request $request, string $id, FundingDossierPreparation $service): JsonResponse
{
return response()->json($service->save($request->user(), $id, $request->all()))->header('Cache-Control', 'private, no-store');
}
public function assess(Request $request, string $id, FundingProgrammes $service): JsonResponse
{
return response()->json($service->assess($id, $request->all()))->header('Cache-Control', 'private, no-store');
}
public function saveInterest(Request $request, string $id, FundingProgrammes $service): RedirectResponse
{
$data = $request->validate(['version_id' => 'required|uuid', 'consent' => 'required|accepted']);
$service->saveInterest($request->user(), $id, $data['version_id'], true);
return back()->with('success', 'Programa guardado na sua área privada. Consulte a versão indicada na ficha.');
}
public function removeInterest(Request $request, string $id, FundingProgrammes $service): RedirectResponse
{
abort_unless($service->installed(), 404);
$service->removeInterest($request->user(), $id);
return back()->with('success', 'Interesse removido da sua lista.');
}
public function download(string $id, string $version, int $resource, FundingProgrammes $service): Response|BinaryFileResponse
{
return $service->download($id, $version, $resource);
}
}
@@ -0,0 +1,319 @@
<?php
namespace App\Http\Controllers;
use App\Models\ExistingBusiness;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\CorridorAgribusinessOpportunities;
use App\Services\EditorialReading;
use App\Services\FederatedSearch;
use App\Services\FundingInstitutionDetails;
use App\Services\FundingProgrammes;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentGeography;
use App\Services\InvestmentZones;
use App\Services\LegacyContent;
use App\Services\SearchTerms;
use App\Services\SectorOrganization;
use App\Services\SectorResourceReferences;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class GlobalSearchController extends Controller
{
public function __invoke(Request $request, InvestmentCatalogue $catalogue, SearchTerms $search, FederatedSearch $federated): Response
{
$input = $request->validate(['q' => ['nullable', 'string', 'max:120'], 'page' => ['nullable', 'integer', 'min:1'], 'category' => ['nullable', 'in:all,physical,financial']]);
$original = trim($input['q'] ?? '');
$intent = $search->requestIntent($original);
if (isset($input['category']) && ($intent === null || $intent['type'] === 'products')) {
$intent = ['type' => 'products', 'label' => 'Produtos e localização', 'kind' => null,
'filter' => $intent['filter'] ?? $original,
'category' => match ($input['category']) {
'physical' => 'Produtos e localizações', 'financial' => 'Produtos financeiros', default => null,
}];
}
$term = $intent['filter'] ?? $original;
$tokens = $search->tokens($term);
$results = ['data' => [], 'total' => 0, 'current_page' => 1, 'last_page' => 1, 'per_page' => 5, 'unavailable' => []];
if ($tokens !== [] || $intent !== null) {
$factories = [
'Produtos e localizações' => function () use ($search, $tokens, $term) {
try {
return $this->productReferences($search, $tokens, $term);
} catch (\RuntimeException $exception) {
throw new HttpException(503, 'Referências de produtos temporariamente indisponíveis.', $exception);
}
},
'Produtos financeiros' => function () use ($search, $tokens, $term) {
$service = app(FundingProgrammes::class);
if (! $service->installed()) {
return ['count' => 0, 'fetch' => fn ($offset, $limit) => []];
}
$query = $service->catalogueQuery([])->select('p.id', 'v.payload')->selectRaw("v.payload->>'title' AS title");
foreach ($tokens as $token) {
$query->where(function ($match) use ($search, $token) {
$search->orFields($match, ["(v.payload->>'title')",
"(SELECT string_agg(product->>'title', ' ') FROM jsonb_array_elements(COALESCE(v.payload->'products','[]'::jsonb)) product)",
"(SELECT string_agg(place->>'location_text', ' ') FROM jsonb_array_elements(COALESCE(v.payload->'locations','[]'::jsonb)) place)",
"(SELECT string_agg(node->>'name', ' ') FROM jsonb_path_query(v.payload,'$.locations[*].territory_path[*]') node)",
"(SELECT string_agg(node->>'name', ' ') FROM jsonb_path_query(v.payload,'$.products[*].territory_paths[*][*]') node)"], $token);
foreach (FundingInstitutionDetails::NEEDS as $code => $label) {
$text = in_array($code, ['investment', 'working_capital'], true) ? 'Financiamento '.$label : $label;
if ($search->matches($text, [$token])) {
$match->orWhereJsonContains('v.payload->institution_services', $code)->orWhereJsonContains('v.payload->funding_needs', $code)
->orWhereRaw("EXISTS (SELECT 1 FROM jsonb_array_elements(COALESCE(v.payload->'products','[]'::jsonb)) product WHERE product->'needs' @> ?::jsonb)", [json_encode([$code], JSON_THROW_ON_ERROR)]);
}
}
foreach (FundingInstitutionDetails::NATURES as $code => $label) {
if ($search->matches($label, [$token])) {
$match->orWhere('v.payload->institution_nature', $code);
}
}
});
}
return $this->source($query, $search, $term, $tokens, "(v.payload->>'title')", 'p.id', function ($row) {
$p = json_decode($row->payload, true, 512, JSON_THROW_ON_ERROR);
$products = array_values(array_unique(array_filter(array_column($p['products'] ?? [], 'title'))));
$services = array_values(array_intersect_key(FundingInstitutionDetails::NEEDS, array_flip($p['institution_services'] ?? [])));
$places = [];
foreach ($p['locations'] ?? [] as $location) {
if (! empty($location['location_text'])) {
$places[] = $location['location_text'];
}
foreach ($location['territory_path'] ?? [] as $node) {
if ($node['type'] !== 'country') {
$places[] = $node['name'];
}
}
}
$national = array_any($p['products'] ?? [], fn ($product) => ($product['coverage'] ?? '') === 'national');
return ['title' => $row->title, 'description' => implode(' · ', $products ?: $services) ?: 'Instituição financeira.',
'location' => $places === [] ? null : 'Presença física: '.implode(' · ', array_unique($places)),
'coverage' => $national ? 'Existe produto com cobertura nacional indicada; consulte as condições.' : 'Cobertura financeira: consultar cada produto.',
'url' => '/fundos/'.$row->id];
});
},
'Páginas e serviços' => function () use ($search, $tokens, $term) {
$pages = array_values(array_filter($this->pages(), fn ($page) => $search->matches(implode(' ', $page), $tokens)));
usort($pages, fn ($a, $b) => $search->score($b['title'], $term, $tokens) <=> $search->score($a['title'], $term, $tokens)
?: strcmp($a['title'], $b['title']) ?: strcmp($a['url'], $b['url']));
return ['count' => count($pages), 'fetch' => fn ($offset, $limit) => array_slice($pages, $offset, $limit)];
},
'Oportunidades' => function () use ($catalogue, $search, $tokens, $term) {
$query = $catalogue->query(['include_national' => true]);
foreach ($tokens as $token) {
$query->where(function ($match) use ($catalogue, $search, $token) {
$search->orFields($match, ['opportunities.title', 'opportunities.summary', 'opportunities.description', 'opportunities.reference', 'opportunities.province'], $token);
$match->orWhereHas('sector', fn ($sector) => $search->constrain($sector, ['name'], [$token]));
$match->orWhereExists(fn ($location) => $location->selectRaw('1')->from('geo_locations as search_location')
->whereIn('search_location.id', app(InvestmentGeography::class)->publicReferences()->select('id'))
->where(fn ($name) => $search->orFields($name, ['search_location.name'], $token))
->where(fn ($direct) => $direct->whereColumn('search_location.id', 'opportunities.primary_territory_id')
->orWhereExists(fn ($link) => $link->selectRaw('1')->from('opportunity_locations as search_link')
->whereColumn('search_link.opportunity_id', 'opportunities.id')->whereColumn('search_link.geo_location_id', 'search_location.id'))));
if (preg_match('/^[a-z0-9]+$/', $token)) {
$match->orWhereIn('opportunities.id', $catalogue->query(['q' => $token, 'include_national' => true])->reorder()->select('opportunities.id'));
}
});
}
return $this->source($query, $search, $term, $tokens, 'opportunities.title', 'opportunities.id',
fn ($r) => ['title' => $r->title, 'description' => $r->summary, 'url' => '/oportunidades/'.rawurlencode($r->slug)]);
},
'Negócios' => function () use ($search, $tokens, $term) {
$query = ExistingBusiness::query()->published();
$search->constrain($query, ['public_title', 'activity_code', 'objective'], $tokens);
return $this->source($query, $search, $term, $tokens, 'public_title', 'existing_businesses.id',
fn ($r) => ['title' => $r->public_title, 'description' => $r->objective, 'url' => '/negocios/'.rawurlencode($r->public_slug)]);
},
'Carteira: projectos, clusters e corredores' => function () use ($search, $tokens, $term, $intent) {
$query = InvestmentPortfolioController::visible();
$search->constrain($query, ['investment_dossiers.title', 'investment_dossiers.content'], $tokens);
if ($intent !== null && $intent['kind'] !== null) {
[$column, $table] = ['corridor' => ['corridor_id', 'development_corridors'], 'cluster' => ['cluster_id', 'economic_clusters'], 'project' => ['project_id', 'projects']][$intent['kind']];
$query->whereNotNull($column)->whereExists(fn ($entity) => $entity->selectRaw('1')->from($table)
->whereColumn($table.'.id', 'investment_dossiers.'.$column)->whereNull($table.'.deleted_at'));
// The existing unique entity key already prevents duplicate dossiers.
}
return $this->source($query, $search, $term, $tokens, 'investment_dossiers.title', 'investment_dossiers.id',
fn ($r) => ['title' => $r->title, 'description' => $r->corridor_id ? 'Corredor' : ($r->cluster_id ? 'Cluster' : 'Projecto âncora'), 'url' => '/carteira/'.$r->id]);
},
'Documentos e legislação' => function () use ($search, $tokens, $term) {
$query = DB::table('portal_resources as r')->join('documents as d', 'd.id', '=', 'r.document_id')
->where('r.published', true)->where('r.rights_status', '!=', 'restricted')->where('d.rights_status', '!=', 'restricted')
->where('d.status', 'active')->where('d.data_classification', 'public')->whereNull('d.deleted_at')
->where('d.malware_scan_status', 'clean')->whereColumn('d.malware_scanned_sha256', 'd.sha256');
$search->constrain($query, ['r.title', 'r.description', 'r.document_number', 'd.issuer', 'r.source_reference', 'r.category', 'r.topic'], $tokens);
$query->select('r.id', 'r.title', 'r.description');
return $this->source($query, $search, $term, $tokens, 'r.title', 'r.id',
fn ($r) => ['title' => $r->title, 'description' => $r->description, 'url' => '/documentos/'.$r->id]);
},
'Artigos' => function () use ($search, $tokens, $term) {
if (! Schema::hasColumn('portal_resources', 'editorial_content')) {
return ['count' => 0, 'fetch' => fn ($offset, $limit) => []];
}
$query = app(EditorialReading::class)->publicResources()
->whereRaw("nullif(btrim(r.editorial_content->>'body'), '') is not null");
$search->constrain($query, ['r.title', "(r.editorial_content->>'body')"], $tokens);
$query->select('r.id', 'r.title')->selectRaw("r.editorial_content->>'body' as body");
return $this->source($query, $search, $term, $tokens, 'r.title', 'r.id',
fn ($r) => ['title' => $r->title, 'description' => Str::limit(trim(strip_tags($r->body)), 220), 'url' => '/artigos/'.$r->id]);
},
'Sectores' => function () use ($search, $tokens, $term) {
$query = Sector::query()->where('is_active', true)->whereNotNull('published_at');
$search->constrain($query, ['name', 'description', 'short_description'], $tokens);
return $this->source($query, $search, $term, $tokens, 'name', 'sectors.id',
fn ($r) => ['title' => $r->name, 'description' => $r->short_description, 'url' => SectorOrganization::href($r->slug)]);
},
'Localizações' => function () use ($search, $tokens, $term) {
$query = app(InvestmentGeography::class)->publicReferences()
->whereIn('location_type', ['province', 'district', 'admin_post', 'locality']);
$search->constrain($query, ['geo_locations.name', 'geo_locations.source_code'], $tokens);
$query->select('geo_locations.id', 'geo_locations.name', 'geo_locations.location_type');
return $this->source($query, $search, $term, $tokens, 'geo_locations.name', 'geo_locations.id',
fn ($r) => ['title' => $r->name, 'description' => ['province' => 'Província', 'district' => 'Distrito', 'admin_post' => 'Posto administrativo', 'locality' => 'Localidade'][$r->location_type],
'url' => '/oportunidades?'.http_build_query([$r->location_type.'_id' => $r->id])]);
},
'Zonas de investimento' => function () use ($search, $tokens, $term) {
$query = app(InvestmentZones::class)->visible();
$search->constrain($query, ['name', 'code'], $tokens);
return $this->source($query, $search, $term, $tokens, 'name', 'investment_zones.id',
fn ($r) => ['title' => $r->name, 'description' => $r->code, 'url' => '/zonas/'.$r->id]);
},
'Parcerias' => function () use ($search, $tokens, $term) {
$query = DB::table('portal_partnerships as p')->where('p.status', 'published');
$search->constrain($query, ['p.title', 'p.sector', 'p.province'], $tokens);
$query->select('p.id', 'p.title', 'p.sector', 'p.province');
return $this->source($query, $search, $term, $tokens, 'p.title', 'p.id',
fn ($r) => ['title' => $r->title, 'description' => implode(' · ', array_filter([$r->sector, $r->province])), 'url' => '/parcerias/'.$r->id]);
},
];
if ($intent !== null) {
$categories = $intent['category'] === null ? ['Produtos e localizações', 'Produtos financeiros'] : [$intent['category']];
$factories = array_intersect_key($factories, array_flip($categories));
}
$results = $federated->page($factories, (int) ($input['page'] ?? 1), 5,
fn ($item) => $search->score($item['title'], $term, $tokens));
}
$answer = $intent === null ? null : ['type' => $intent['type'], 'label' => $intent['label'], 'filter' => $term,
'count' => $results['unavailable'] === [] ? $results['total'] : null];
if ($answer !== null && $intent['type'] === 'products') {
$answer['category'] = match ($intent['category']) {
'Produtos e localizações' => 'physical', 'Produtos financeiros' => 'financial', default => 'all',
};
}
return Inertia::render('portal/search', ['query' => $original, 'results' => $results, 'answer' => $answer]);
}
/** @param list<string> $tokens
* @return array{count:int,fetch:callable(int,int):iterable<array<string,mixed>>}
*/
private function productReferences(SearchTerms $search, array $tokens, string $term): array
{
$rows = [];
foreach (['mineracao', 'energia-especifica'] as $sector) {
if (! Sector::where('slug', $sector)->where('is_active', true)->whereNotNull('published_at')->exists()) {
continue;
}
$data = app(SectorResourceReferences::class)->view($sector);
foreach ($data['groups'] as $group) {
$locations = array_values(array_filter($group['location_labels'], fn ($name) => $search->matches($term, $search->tokens($name))));
$rows[] = ['title' => $group['name'], 'description' => $sector === 'mineracao' ? 'Referência mineral; não identifica uma concessão ou produção disponível.' : 'Segmento energético e cadeia de valor.',
'location' => $group['locations_text'], 'url' => '/sectores/'.$sector.'?'.http_build_query(['resource_group' => $group['id'],
...(count($locations) === 1 ? ['resource_location' => $locations[0]] : [])])];
}
}
if (app(LegacyContent::class)->available() && Sector::where('slug', 'agronegocio')->where('is_active', true)->whereNotNull('published_at')->exists()) {
try {
app(LegacyContent::class)->article('agronegocio', false);
$entries = app(CorridorAgribusinessOpportunities::class)->entries();
$published = Opportunity::published()->whereIn('management_creation_key', array_column($entries, 'key'))->pluck('slug', 'management_creation_key');
foreach ($entries as $entry) {
if (! isset($published[$entry['key']])) {
continue;
}
$rows[] = ['title' => $entry['chain'], 'description' => 'Cadeia agrícola: '.$entry['summary'], 'location' => 'Enquadramento territorial: '.$entry['corridor'],
'url' => '/oportunidades/'.rawurlencode($published[$entry['key']])];
}
} catch (HttpException $exception) {
if ($exception->getStatusCode() !== 404) {
throw $exception;
}
}
}
$rows = array_values(array_filter($rows, fn ($row) => $search->matches(implode(' ', $row), $tokens)));
usort($rows, fn ($a, $b) => $search->score($b['title'], $term, $tokens) <=> $search->score($a['title'], $term, $tokens) ?: strcmp($a['title'], $b['title']));
return ['count' => count($rows), 'fetch' => fn ($offset, $limit) => array_slice($rows, $offset, $limit)];
}
/** @param \Illuminate\Database\Eloquent\Builder<*>|\Illuminate\Database\Query\Builder $query
* @param list<string> $tokens
* @param callable(mixed):array<string,mixed> $present
* @param literal-string $title
* @param literal-string $id
* @return array{count:int,fetch:callable(int,int):iterable<array<string,mixed>>}
*/
private function source($query, SearchTerms $search, string $term, array $tokens, string $title, string $id, callable $present): array
{
$count = (clone $query)->reorder()->count();
$query->reorder();
$search->orderByRelevance($query, $title, $term, $tokens, $id);
return ['count' => $count, 'fetch' => fn ($offset, $limit) => (clone $query)->offset($offset)->limit($limit)->get()->map($present)->all()];
}
/** Public service entry points and terms used to find them.
* @return list<array{title:string,description:string,url:string}>
*/
private function pages(): array
{
return [
['title' => 'Licenciamento da empresa', 'description' => 'Roteiro de constituição e licenciamento conforme a actividade e localização.', 'url' => '/como-investir#planeamento'],
['title' => 'Preparar licenciamento no dossier', 'description' => 'Continuar a preparação na etapa de licenciamento prévio.', 'url' => '/investimentos/iniciar?step=S08'],
['title' => 'Como investir em Moçambique', 'description' => 'Procedimentos e etapas para investir', 'url' => '/como-investir'],
['title' => 'Iniciar ou continuar investimento', 'description' => 'Preparar uma ideia e dossier de investimento', 'url' => '/investimentos/iniciar'],
['title' => 'Oportunidades de investimento', 'description' => 'Pesquisar por sector, localização e maturidade', 'url' => '/oportunidades'],
['title' => 'Carteira de investimento', 'description' => 'Projectos âncora, clusters e corredores', 'url' => '/carteira'],
['title' => 'Negócios existentes', 'description' => 'Compra, venda e participação em negócios', 'url' => '/negocios'],
['title' => 'Sectores de investimento', 'description' => 'Actividades económicas e sectores prioritários', 'url' => '/sectores'],
['title' => 'Zonas de investimento', 'description' => 'Zonas económicas especiais, ZEE, ZFI e parques industriais', 'url' => '/zonas'],
['title' => 'Contextos de investimento', 'description' => 'Formas de iniciar e preparar um investimento', 'url' => '/contextos-de-investimento'],
['title' => 'Documentos e formulários', 'description' => 'Acervo documental e formulários para investidores e empresas', 'url' => '/documentos'],
['title' => 'Formulário do investidor', 'description' => 'Dados e contacto para investir', 'url' => '/formularios/investidor'],
['title' => 'Formulário de empresa', 'description' => 'Dados e contacto para empresas', 'url' => '/formularios/empresa'],
['title' => 'Legislação e incentivos', 'description' => 'Leis, decretos, benefícios e enquadramento legal', 'url' => '/legislacao'],
['title' => 'Simulador fiscal', 'description' => 'Simular impostos e cenários fiscais de investimento', 'url' => '/simulador-fiscal'],
['title' => 'Formulários fiscais', 'description' => 'Preparação dos formulários IVA e IRPC', 'url' => '/formularios/fiscais'],
['title' => 'Terra e DUAT', 'description' => 'Apoio ao uso e aproveitamento da terra', 'url' => '/terra-duat'],
['title' => 'Bolsa de parcerias', 'description' => 'Encontrar parceiros e propostas', 'url' => '/parcerias'],
['title' => 'Apoio ao investidor', 'description' => 'Contactos e pedido de apoio', 'url' => '/apoio'],
['title' => 'Educação para investimento', 'description' => 'Conteúdos educativos e orientação', 'url' => '/educacao'],
['title' => 'Sobre o InvesteMoz', 'description' => 'Informação institucional do portal', 'url' => '/sobre'],
['title' => 'Contacto', 'description' => 'Contactar o portal InvesteMoz', 'url' => '/contacto'],
['title' => 'Política de privacidade', 'description' => 'Privacidade e tratamento de dados pessoais', 'url' => '/politica-de-privacidade'],
['title' => 'Termos de uso', 'description' => 'Condições de utilização do portal', 'url' => '/termos-de-uso'],
];
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentOpportunityAlerts;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
final class InvestmentAlertPreferencesController extends Controller
{
public function save(Request $request, InvestmentOpportunityAlerts $alerts): JsonResponse|RedirectResponse
{
$preferences = $alerts->save($request->user(), $request->all());
return $request->expectsJson() ? response()->json($preferences) : back()->with('success', $preferences['enabled']
? 'Preferências guardadas. O acompanhamento considera novas disponibilizações nos catálogos escolhidos.'
: 'Alertas dos catálogos cancelados. As notificações anteriores foram conservadas.');
}
}
@@ -9,8 +9,12 @@ use App\Services\CorridorAgribusinessOpportunities;
use App\Services\InvestmentCatalogue; use App\Services\InvestmentCatalogue;
use App\Services\InvestmentComplements; use App\Services\InvestmentComplements;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\InvestmentMapIndicators;
use App\Services\InvestmentZoneOperationalDetails;
use App\Services\InvestmentZones; use App\Services\InvestmentZones;
use App\Services\OpportunityCorridorExplorer; use App\Services\OpportunityCorridorExplorer;
use App\Services\OpportunityTextSearch;
use App\Services\PublicSearchMetrics;
use App\Services\SectorInvestment; use App\Services\SectorInvestment;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -29,12 +33,21 @@ class InvestmentDiscoveryController extends Controller
if ($request->routeIs('investment.education')) { if ($request->routeIs('investment.education')) {
$filters['education'] = true; $filters['education'] = true;
} }
$results = $catalogue->query($filters)->paginate(12)->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record));
$relatedQuery = $results->total() === 0 ? app(OpportunityTextSearch::class)->relatedQuery($filters['q'] ?? '') : null;
$relatedFilters = [...Arr::except($filters, ['page', 'q']), 'q' => $relatedQuery];
$related = $relatedQuery === null ? null : [
'query' => $filters['q'], 'subject' => $relatedQuery,
'href' => ($request->routeIs('investment.education') ? '/educacao' : '/oportunidades').'?'.http_build_query($relatedFilters),
'items' => $catalogue->query($relatedFilters)->limit(6)->get()->map(fn ($record) => $catalogue->presentLocation($record)),
];
app(PublicSearchMetrics::class)->candidate($request, $request->routeIs('investment.education') ? 'education_page' : 'opportunities_page', $results->total(), $request->routeIs('investment.education') ? Arr::except($filters, ['education']) : $filters);
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) : [], 'corridorGroups' => ($filters['view'] ?? '') === 'corridors' ? app(OpportunityCorridorExplorer::class)->groups($filters) : [],
'territorySelection' => app(InvestmentGeography::class)->selection($filters), 'territorySelection' => app(InvestmentGeography::class)->selection($filters),
'guides' => app(SectorInvestment::class)->guides(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()->through(fn ($record) => $catalogue->presentLocation($record)), 'results' => $results, 'relatedSearch' => $related,
'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)]);
} }
@@ -79,7 +92,11 @@ 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()->through(fn ($record) => $catalogue->presentLocation($record))); $filters = $catalogue->filters($request);
$results = $catalogue->query($filters)->paginate($request->integer('per_page', 12))->withQueryString()->through(fn ($record) => $catalogue->presentLocation($record));
app(PublicSearchMetrics::class)->candidate($request, 'opportunities_api', $results->total(), $filters);
return response()->json($results);
} }
public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse public function references(Request $request, InvestmentCatalogue $catalogue): JsonResponse
@@ -140,6 +157,7 @@ class InvestmentDiscoveryController extends Controller
$filters = $catalogue->filters($request); $filters = $catalogue->filters($request);
$context = $this->territorial($filters)->map(fn ($d) => ['id' => 'dossier:'.$d->id, 'title' => $d->title, 'kind' => $d->cluster_id ? 'Cluster' : ($d->corridor_id ? 'Corredor' : 'Projeto âncora'), 'url' => '/carteira/'.$d->id]); $context = $this->territorial($filters)->map(fn ($d) => ['id' => 'dossier:'.$d->id, 'title' => $d->title, 'kind' => $d->cluster_id ? 'Cluster' : ($d->corridor_id ? 'Corredor' : 'Projeto âncora'), 'url' => '/carteira/'.$d->id]);
$opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []); $opportunityOnlyFilters = array_filter(Arr::only($filters, ['association_type', 'association_target', 'association_state', 'association_purpose', 'authority_id', 'chain_id', 'subsector_id', 'category', 'publication_state', 'education', 'sector', 'facets', 'project_id', 'cluster_id', 'corridor_id', 'min_amount', 'max_amount', 'currency', 'before', 'maturity_level', 'preparation']), fn ($value) => $value !== null && $value !== '' && $value !== false && $value !== []);
$quantitative = ['state' => 'not_included', 'records' => [], 'truncated' => false];
if ($opportunityOnlyFilters === [] && ! in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) { if ($opportunityOnlyFilters === [] && ! in_array($filters['dimension'] ?? null, ['cluster', 'corridor'], true)) {
$zoneFilters = $filters; $zoneFilters = $filters;
if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) { if (in_array($filters['dimension'] ?? null, ['zee', 'zfi'], true)) {
@@ -151,10 +169,12 @@ class InvestmentDiscoveryController extends Controller
$zones->where('id', $filters[$key]); $zones->where('id', $filters[$key]);
} }
} }
$context = $context->concat($zones->orderBy('name')->limit(30)->get(['id', 'name', 'category'])->map(fn ($z) => ['id' => 'zone:'.$z->id, 'title' => $z->name, 'kind' => ['zee' => 'ZEE', 'zfi' => 'ZFI', 'industrial_park' => 'Parque industrial'][$z->category] ?? $z->category, 'url' => '/zonas/'.$z->id])); $zoneRows = $zones->orderBy('name')->orderBy('id')->limit(31)->get(['id', 'name', 'category', 'version_no', ...(app(InvestmentZoneOperationalDetails::class)->installed() ? ['operational_details'] : [])]);
$quantitative = app(InvestmentMapIndicators::class)->forZones($zoneRows->take(30)->values(), $zoneRows->count() > 30);
$context = $context->concat($zoneRows->take(30)->map(fn ($z) => ['id' => 'zone:'.$z->id, 'title' => $z->name, 'kind' => ['zee' => 'ZEE', 'zfi' => 'ZFI', 'industrial_park' => 'Parque industrial'][$z->category] ?? $z->category, 'url' => '/zonas/'.$z->id]));
} }
return response()->json([...$catalogue->map($filters), 'territorial_context' => $context->values(), 'context_limit_per_collection' => 30]); return response()->json([...$catalogue->map($filters), 'territorial_context' => $context->values(), 'quantitative_context' => $quantitative, 'context_limit_per_collection' => 30]);
} }
public function compare(Request $request, InvestmentCatalogue $catalogue): JsonResponse public function compare(Request $request, InvestmentCatalogue $catalogue): JsonResponse
@@ -184,15 +204,16 @@ class InvestmentDiscoveryController extends Controller
{ {
$records = $catalogue->query($catalogue->filters($request))->limit(1000)->get(); $records = $catalogue->query($catalogue->filters($request))->limit(1000)->get();
return response()->streamDownload(function () use ($records) { return response()->streamDownload(function () use ($records, $catalogue) {
$stream = fopen('php://output', 'w'); $stream = fopen('php://output', 'w');
if ($stream === false) { if ($stream === false) {
return; return;
} }
fwrite($stream, "\xEF\xBB\xBF"); fwrite($stream, "\xEF\xBB\xBF");
fputcsv($stream, ['Referência', 'Título', 'Sector', 'Província', 'Montante', 'Moeda', 'Maturidade', 'URL'], ';', '"', ''); fputcsv($stream, ['Referência', 'Título', 'Sector', 'Província', 'Montante', 'Moeda', 'Maturidade', 'URL', 'Localização e âmbito'], ';', '"', '');
foreach ($records as $r) { foreach ($records as $r) {
$fields = [$r->reference, $r->title, $r->sector?->name, $r->province, $r->estimated_investment_amount, $r->estimated_investment_currency, $r->maturity_label, url('/oportunidades/'.$r->slug)]; $location = $catalogue->locationPresentation($r);
$fields = [$r->reference, $r->title, $r->sector?->name, implode(' / ', $location['provinces']), $r->estimated_investment_amount, $r->estimated_investment_currency, $r->maturity_label, url('/oportunidades/'.$r->slug), $location['summary']];
fputcsv($stream, array_map(fn ($v) => preg_match('/^[\s]*[=+@-]/u', (string) $v) ? "'".$v : $v, $fields), ';', '"', ''); fputcsv($stream, array_map(fn ($v) => preg_match('/^[\s]*[=+@-]/u', (string) $v) ? "'".$v : $v, $fields), ';', '"', '');
} }
fclose($stream); fclose($stream);
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentGuides;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class InvestmentGuideController extends Controller
{
public function index(Request $request, string $slug, InvestmentGuides $guides): Response|JsonResponse
{
$data = $guides->publicView($slug, $request->all());
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/guide', $data);
}
public function show(Request $request, string $id, string $slug, InvestmentGuides $guides): Response|JsonResponse
{
$data = $guides->view($request->user(), $id, $slug, $request->all());
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/guide', $data);
}
public function save(Request $request, string $id, string $slug, InvestmentGuides $guides): JsonResponse
{
return response()->json($guides->save($request->user(), $id, $slug, $request->all()));
}
}
@@ -13,6 +13,8 @@ use App\Services\InvestmentGeography;
use App\Services\InvestmentRelations; use App\Services\InvestmentRelations;
use App\Services\InvestmentZones; use App\Services\InvestmentZones;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use App\Services\PortalEditorialWorkflow;
use App\Services\PublicSearchMetrics;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -85,7 +87,12 @@ class InvestmentPortfolioController extends Controller
app(InvestmentGeography::class)->constrainDossiersToTerritories($query, $territoryIds); app(InvestmentGeography::class)->constrainDossiersToTerritories($query, $territoryIds);
} }
return Inertia::render('portfolio/index', ['records' => $query->orderBy('title')->paginate(30)->withQueryString(), $results = $query->orderBy('title')->paginate(30)->withQueryString();
if (! $management) {
app(PublicSearchMetrics::class)->candidate($request, 'portfolio', $results->total(), $filters);
}
return Inertia::render('portfolio/index', ['records' => $results,
'management' => $management, 'filters' => $filters, 'sectors' => $sectorOptions, 'territorySelection' => $territorySelection]); 'management' => $management, 'filters' => $filters, 'sectors' => $sectorOptions, 'territorySelection' => $territorySelection]);
} }
@@ -93,6 +100,10 @@ class InvestmentPortfolioController extends Controller
{ {
$management = $request->routeIs('management.portfolio*'); $management = $request->routeIs('management.portfolio*');
$record = ($management ? InvestmentDossier::query() : self::visible())->findOrFail($id); $record = ($management ? InvestmentDossier::query() : self::visible())->findOrFail($id);
$editorial = $management && app(PortalEditorialWorkflow::class)->portfolioEnabled();
if ($editorial) {
$record = app(PortalEditorialWorkflow::class)->workingPortfolio($record);
}
$relatedIds = []; $relatedIds = [];
foreach ([['corridor_projects', 'corridor_id', 'project_id'], ['corridor_clusters', 'corridor_id', 'cluster_id'], ['cluster_projects', 'cluster_id', 'project_id']] as [$table, $left, $right]) { foreach ([['corridor_projects', 'corridor_id', 'project_id'], ['corridor_clusters', 'corridor_id', 'cluster_id'], ['cluster_projects', 'cluster_id', 'project_id']] as [$table, $left, $right]) {
foreach ([[$left, $right], [$right, $left]] as [$origin, $destination]) { foreach ([[$left, $right], [$right, $left]] as [$origin, $destination]) {
@@ -141,7 +152,7 @@ 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', ['complements' => $management ? [] : app(InvestmentComplements::class)->options('portfolio:'.$record->id), 'record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones, return Inertia::render('portfolio/show', ['editorialEnabled' => $editorial, '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, '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),
@@ -161,6 +172,11 @@ class InvestmentPortfolioController extends Controller
$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'],
'content' => ['required', 'array:name,description,location,region,sector,promotion,facts,partners,cta,anchors,gaps,priority,clusters,focus,notice,code'], 'content' => ['required', 'array:name,description,location,region,sector,promotion,facts,partners,cta,anchors,gaps,priority,clusters,focus,notice,code'],
'content.*' => ['nullable', 'string', 'max:15000']]); 'content.*' => ['nullable', 'string', 'max:15000']]);
if (app(PortalEditorialWorkflow::class)->portfolioWrites($dossier->id)) {
app(PortalEditorialWorkflow::class)->savePortfolio($request->user(), $dossier, (int) $data['version_no'], $data);
return back()->with('success', 'Edição privada guardada. A publicação anterior permanece disponível; continue no circuito editorial.');
}
DB::transaction(function () use ($request, $dossier, $data) { DB::transaction(function () use ($request, $dossier, $data) {
$dossier = InvestmentDossier::whereKey($dossier->id)->lockForUpdate()->firstOrFail(); $dossier = InvestmentDossier::whereKey($dossier->id)->lockForUpdate()->firstOrFail();
abort_if($dossier->version_no !== (int) $data['version_no'], 409, 'A ficha foi alterada. Recarregue a página e reveja a versão actual antes de guardar.'); abort_if($dossier->version_no !== (int) $data['version_no'], 409, 'A ficha foi alterada. Recarregue a página e reveja a versão actual antes de guardar.');
@@ -173,6 +189,7 @@ class InvestmentPortfolioController extends Controller
public function publish(Request $request, InvestmentDossier $dossier): RedirectResponse public function publish(Request $request, InvestmentDossier $dossier): RedirectResponse
{ {
abort_if(app(PortalEditorialWorkflow::class)->portfolioWrites($dossier->id), 409, 'Use a aprovação e publicação separadas da edição no circuito editorial.');
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'approval_evidence' => ['required', 'string', 'min:15', 'max:3000']]); $data = $request->validate(['version_no' => ['required', 'integer', 'min:1'], 'approval_evidence' => ['required', 'string', 'min:15', 'max:3000']]);
DB::transaction(function () use ($request, $dossier, $data) { DB::transaction(function () use ($request, $dossier, $data) {
$dossier = InvestmentDossier::whereKey($dossier->id)->lockForUpdate()->firstOrFail(); $dossier = InvestmentDossier::whereKey($dossier->id)->lockForUpdate()->firstOrFail();
@@ -0,0 +1,50 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentPreparationWorkspace;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class InvestmentPreparationController extends Controller
{
public function show(Request $request, string $id, InvestmentPreparationWorkspace $workspace): JsonResponse|Response
{
$request->validate(['opportunity' => 'nullable|string|max:150', 'history_scope' => 'nullable|in:dossier', 'history_before' => 'nullable|integer|min:1']);
$data = $workspace->view($request->user(), $id, $request->query('opportunity'), $request->filled('history_before') ? $request->integer('history_before') : null, $request->query('history_scope') === 'dossier');
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/preparation', ['workspace' => $data]);
}
public function change(Request $request, string $id, InvestmentPreparationWorkspace $workspace): JsonResponse
{
return response()->json($workspace->change($request->user(), $id, $request->all()));
}
public function preview(Request $request, string $id, InvestmentPreparationWorkspace $workspace): \Illuminate\Http\Response
{
$request->validate(['opportunity' => 'nullable|string|max:150', 'history_scope' => 'nullable|in:dossier']);
$data = $workspace->view($request->user(), $id, $request->query('opportunity'), null, $request->query('history_scope') === 'dossier');
return response()->view('investments.preparation-index', ['workspace' => $data, 'manifest' => null])->header('Content-Security-Policy', "sandbox; default-src 'none'; style-src 'unsafe-inline'")->header('X-Content-Type-Options', 'nosniff');
}
public function download(Request $request, string $id, string $exportId, InvestmentPreparationWorkspace $workspace): \Illuminate\Http\Response
{
$request->validate(['opportunity' => 'nullable|string|max:150', 'history_scope' => 'nullable|in:dossier']);
$bundle = $workspace->bundle($request->user(), $id, $request->query('opportunity'), $exportId, $request->query('history_scope') === 'dossier');
return response($bundle['bytes'], 200, ['Content-Type' => 'application/zip', 'Content-Disposition' => 'attachment; filename="preparacao-apiex-'.$id.'.zip"', 'X-Export-Id' => $exportId, 'X-Content-Type-Options' => 'nosniff']);
}
public function export(Request $request, string $id, InvestmentPreparationWorkspace $workspace): \Illuminate\Http\Response
{
$body = [...$request->all(), 'action' => 'apiex_export'];
$state = $workspace->change($request->user(), $id, $body);
$bundle = $workspace->bundle($request->user(), $id, $state['opportunity'], $body['operation_key']);
return response($bundle['bytes'], 200, ['Content-Type' => 'application/zip', 'Content-Disposition' => 'attachment; filename="preparacao-apiex-'.$id.'.zip"', 'X-Export-Id' => $bundle['export_id'], 'X-Content-Type-Options' => 'nosniff']);
}
}
@@ -11,6 +11,8 @@ use App\Models\ValueChain;
use App\Services\ClusterCompetitiveness; use App\Services\ClusterCompetitiveness;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\PortalAudit; use App\Services\PortalAudit;
use App\Services\PortalEditorialSubjects;
use App\Services\PortalEditorialWorkflow;
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;
@@ -31,19 +33,35 @@ class InvestmentStructureController extends Controller
}); });
} }
return Inertia::render('structures/index', ['structure' => $structure, 'filters' => $filters, $records = $query->orderBy('name')->orderBy('id')->paginate(20)->withQueryString();
'records' => $query->orderBy('name')->orderBy('id')->paginate(20)->withQueryString()]); if ($structure === 'clusters' && app(ClusterCompetitiveness::class)->editorialEnabled()) {
$records->through(function ($record) {
$analysis = app(ClusterCompetitiveness::class)->current($record->id);
$record->setAttribute('editorial_state', $analysis['workflow']['state'] ?? ($analysis['approved'] ? 'legacy_published' : 'not_started'));
return $record;
});
}
return Inertia::render('structures/index', ['structure' => $structure, 'filters' => $filters, 'records' => $records]);
} }
public function edit(Request $request, string $structure, ?string $id = null): Response public function edit(Request $request, string $structure, ?string $id = null): Response
{ {
$model = $this->model($structure); $model = $this->model($structure);
$record = $id ? $model::findOrFail($id) : null; $record = $id ? $model::findOrFail($id) : null;
$editorialDossier = $id ? app(PortalEditorialWorkflow::class)->structureDossier($structure, $id) : null;
if ($record && $editorialDossier) {
$record = app(PortalEditorialWorkflow::class)->workingStructure($record, $editorialDossier);
} elseif ($record && app(PortalEditorialSubjects::class)->available()) {
$record = clone $record;
$record->forceFill(get_object_vars(app(PortalEditorialSubjects::class)->working($structure, (object) $record->getAttributes())));
}
return Inertia::render('structures/editor', ['structure' => $structure, 'record' => $record, return Inertia::render('structures/editor', ['editorialDossier' => $editorialDossier?->id, 'editorialSubject' => ! $editorialDossier && $record && app(PortalEditorialSubjects::class)->available() ? '/management/editorial/subjects/'.$structure.'/'.$id : null, 'structuralEditorial' => app(PortalEditorialSubjects::class)->available(), 'structure' => $structure, 'record' => $record,
'projects' => $structure === 'clusters' && $id ? Project::orderBy('name')->get(['id', 'name', 'code']) : [], 'projects' => $structure === 'clusters' && $id ? Project::orderBy('name')->get(['id', 'name', 'code']) : [],
'chains' => $structure === 'clusters' && $id ? ValueChain::where('cluster_id', $id)->orderBy('code')->get() : [], 'chains' => $structure === 'clusters' && $id ? ValueChain::where('cluster_id', $id)->orderBy('code')->get()->map(fn ($row) => app(PortalEditorialSubjects::class)->available() ? app(PortalEditorialSubjects::class)->working('value-chains', (object) $row->getAttributes()) : $row) : [],
'gaps' => $structure === 'clusters' && $id ? InvestmentGap::where('cluster_id', $id)->orderBy('created_at')->get() : [], 'gaps' => $structure === 'clusters' && $id ? InvestmentGap::where('cluster_id', $id)->orderBy('created_at')->get()->map(fn ($row) => app(PortalEditorialSubjects::class)->available() ? app(PortalEditorialSubjects::class)->working('investment-gaps', (object) $row->getAttributes()) : $row) : [],
'chainLinks' => $structure === 'clusters' && $id ? DB::table('value_chain_links') 'chainLinks' => $structure === 'clusters' && $id ? DB::table('value_chain_links')
->join('value_chains as origins', 'origins.id', '=', 'value_chain_links.from_value_chain_id') ->join('value_chains as origins', 'origins.id', '=', 'value_chain_links.from_value_chain_id')
->join('value_chains as destinations', 'destinations.id', '=', 'value_chain_links.to_value_chain_id') ->join('value_chains as destinations', 'destinations.id', '=', 'value_chain_links.to_value_chain_id')
@@ -56,7 +74,7 @@ class InvestmentStructureController extends Controller
'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')
->where('cluster_id', $id)->whereNull('cluster_projects.deleted_at')->whereNull('projects.deleted_at') ->where('cluster_id', $id)->whereNull('cluster_projects.deleted_at')->whereNull('projects.deleted_at')
->orderBy('projects.name')->get(['cluster_projects.id', 'cluster_projects.project_id', 'cluster_projects.role', 'cluster_projects.association_type', 'cluster_projects.source_reference', 'cluster_projects.evidence_reference', 'cluster_projects.valid_from', 'cluster_projects.valid_until', 'cluster_projects.validation_status', 'cluster_projects.version_no', 'cluster_projects.editor_id', 'projects.name']) : [], ->orderBy('projects.name')->get(['cluster_projects.id', 'cluster_projects.project_id', 'cluster_projects.role', 'cluster_projects.association_type', 'cluster_projects.source_reference', 'cluster_projects.evidence_reference', 'cluster_projects.valid_from', 'cluster_projects.valid_until', 'cluster_projects.validation_status', 'cluster_projects.version_no', 'cluster_projects.editor_id', 'projects.name'])->map(fn ($row) => app(PortalEditorialSubjects::class)->working('cluster-project', $row)) : [],
]); ]);
} }
@@ -67,11 +85,16 @@ class InvestmentStructureController extends Controller
$isCorridor = $structure === 'corridors'; $isCorridor = $structure === 'corridors';
$model = $this->model($structure); $model = $this->model($structure);
$record = $id ? $model::findOrFail($id) : new $model; $record = $id ? $model::findOrFail($id) : new $model;
$editorialDossier = $id ? app(PortalEditorialWorkflow::class)->structureDossier($structure, $id, true) : null;
$subjectWrites = ! $editorialDossier && ($id ? app(PortalEditorialSubjects::class)->writes($structure, $id) : app(PortalEditorialSubjects::class)->available());
$rules = [ $rules = [
'code' => ['required', 'string', 'max:100', Rule::unique($record->getTable(), 'code')->whereNull('deleted_at')->ignore($record->getKey())], 'code' => ['required', 'string', 'max:100', Rule::unique($record->getTable(), 'code')->whereNull('deleted_at')->ignore($record->getKey())],
'name' => ['required', 'string', 'max:200'], 'name' => ['required', 'string', 'max:200'],
'status' => ['required', Rule::in($isProject ? ['draft', 'planned', 'active', 'suspended', 'completed', 'cancelled'] : ($isCluster ? ['planned', 'active', 'inactive'] : ['proposed', 'active', 'closed']))], 'status' => ['required', Rule::in($isProject ? ['draft', 'planned', 'active', 'suspended', 'completed', 'cancelled'] : ($isCluster ? ['planned', 'active', 'inactive'] : ['proposed', 'active', 'closed']))],
]; ];
if ($editorialDossier || ($subjectWrites && $id)) {
$rules['editorial_version'] = ['required', 'integer', 'min:1'];
}
if ($isProject || $isCorridor) { if ($isProject || $isCorridor) {
$rules['description'] = ['nullable', 'string', 'max:10000']; $rules['description'] = ['nullable', 'string', 'max:10000'];
} }
@@ -96,6 +119,22 @@ class InvestmentStructureController extends Controller
$data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id; $data['primary_territory_id'] = $path === [] ? null : $path[array_key_last($path)]->id;
$data['territory_version'] = $path === [] ? 0 : 1; $data['territory_version'] = $path === [] ? 0 : 1;
} }
if ($editorialDossier) {
app(PortalEditorialWorkflow::class)->saveStructure($request->user(), $record, $editorialDossier, (int) $data['editorial_version'], $data);
return redirect('/management/'.$structure.'/'.$record->getKey().'/edit')->with('success', 'Dados-base guardados numa edição privada da carteira. A publicação anterior está preservada.');
}
if ($subjectWrites) {
DB::transaction(function () use ($request, $record, $structure, $id, $data): void {
$fields = array_diff_key($data, ['editorial_version' => true]);
if (! $id) {
PortalAudit::save($record, $fields, $request->user()->id);
}
app(PortalEditorialWorkflow::class)->saveSubject($request->user(), $structure, (string) $record->getKey(), $id ? (int) $data['editorial_version'] : 0, $fields, ! $id);
});
return redirect('/management/'.$structure.'/'.$record->getKey().'/edit')->with('success', 'Proposta privada guardada. Reveja a edição antes de publicar as alterações.');
}
PortalAudit::save($record, $data, $request->user()->id); PortalAudit::save($record, $data, $request->user()->id);
return redirect('/management/'.$structure.'/'.$record->getKey().'/edit')->with('success', 'Registo guardado.'); return redirect('/management/'.$structure.'/'.$record->getKey().'/edit')->with('success', 'Registo guardado.');
@@ -114,6 +153,7 @@ class InvestmentStructureController extends Controller
public function linkProject(Request $request, EconomicCluster $cluster): RedirectResponse public function linkProject(Request $request, EconomicCluster $cluster): RedirectResponse
{ {
$editorial = app(PortalEditorialSubjects::class)->available();
$data = $request->validate(['project_id' => ['required', 'uuid', Rule::exists('projects', 'id')->whereNull('deleted_at')], $data = $request->validate(['project_id' => ['required', 'uuid', Rule::exists('projects', 'id')->whereNull('deleted_at')],
'version_no' => ['required', 'integer', 'min:0'], 'version_no' => ['required', 'integer', 'min:0'],
'role' => ['required', Rule::in(['anchor', 'complementary', 'supporting'])], 'role' => ['required', Rule::in(['anchor', 'complementary', 'supporting'])],
@@ -121,10 +161,21 @@ class InvestmentStructureController extends Controller
'source_reference' => ['required', 'string', 'min:10', 'max:2000'], 'source_reference' => ['required', 'string', 'min:10', 'max:2000'],
'evidence_reference' => ['required', 'string', 'min:3', 'max:2000'], 'evidence_reference' => ['required', 'string', 'min:3', 'max:2000'],
'valid_from' => ['required', 'date_format:Y-m-d'], 'valid_from' => ['required', 'date_format:Y-m-d'],
'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from']]); 'valid_until' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:valid_from'],
DB::transaction(function () use ($cluster, $data, $request) { ...($editorial ? ['editorial_version' => ['required', 'integer', 'min:0']] : [])]);
DB::transaction(function () use ($cluster, $data, $request, $editorial) {
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail(); EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
$link = ClusterProject::where('cluster_id', $cluster->id)->where('project_id', $data['project_id'])->whereNull('deleted_at')->lockForUpdate()->first(); $link = ClusterProject::where('cluster_id', $cluster->id)->where('project_id', $data['project_id'])->whereNull('deleted_at')->lockForUpdate()->first();
if ($editorial || ($link && app(PortalEditorialSubjects::class)->writes('cluster-project', $link->id))) {
abort_unless((int) $data['version_no'] === ($link ? (int) $link->version_no : 0), 409, 'A associação foi alterada. Confira a versão actual.');
$fields = [...array_diff_key($data, ['version_no' => true, 'editorial_version' => true]), 'cluster_id' => $cluster->id];
if (! $link) {
$fields += ['validation_status' => 'pending', 'editor_id' => $request->user()->id, 'validator_id' => null, 'version_no' => 1];
}
app(PortalEditorialSubjects::class)->stageModel($request->user(), 'cluster-project', $link ?? new ClusterProject, $fields, (int) $data['editorial_version']);
return;
}
if ($link) { if ($link) {
abort_if((int) $link->version_no !== (int) $data['version_no'], 409, 'Versao da associacao alterada.'); abort_if((int) $link->version_no !== (int) $data['version_no'], 409, 'Versao da associacao alterada.');
$changed = false; $changed = false;
@@ -155,10 +206,17 @@ class InvestmentStructureController extends Controller
public function saveChain(Request $request, EconomicCluster $cluster, ?ValueChain $chain = null): RedirectResponse public function saveChain(Request $request, EconomicCluster $cluster, ?ValueChain $chain = null): RedirectResponse
{ {
abort_if($chain && $chain->cluster_id !== $cluster->id, 404); abort_if($chain && $chain->cluster_id !== $cluster->id, 404);
$editorial = $chain ? app(PortalEditorialSubjects::class)->writes('value-chains', $chain->id) : app(PortalEditorialSubjects::class)->available();
$data = $request->validate(['code' => ['required', 'string', 'max:100', $data = $request->validate(['code' => ['required', 'string', 'max:100',
Rule::unique('value_chains', 'code')->where('cluster_id', $cluster->id)->whereNull('deleted_at')->ignore($chain?->id)], Rule::unique('value_chains', 'code')->where('cluster_id', $cluster->id)->whereNull('deleted_at')->ignore($chain?->id)],
'name' => ['required', 'string', 'max:200'], 'name' => ['required', 'string', 'max:200'],
'stage' => ['required', Rule::in(['input', 'production', 'processing', 'logistics', 'market'])]]); 'stage' => ['required', Rule::in(['input', 'production', 'processing', 'logistics', 'market'])],
...($editorial && $chain ? ['editorial_version' => ['required', 'integer', 'min:1']] : [])]);
if ($editorial) {
$edition = app(PortalEditorialSubjects::class)->stageModel($request->user(), 'value-chains', $chain ?? new ValueChain, [...array_diff_key($data, ['editorial_version' => true]), 'cluster_id' => $cluster->id], $chain ? (int) $data['editorial_version'] : 0);
return redirect('/management/editorial/subjects/value-chains/'.$edition->subject_key)->with('success', 'Etapa guardada numa proposta privada.');
}
PortalAudit::save($chain ?? new ValueChain, [...$data, 'cluster_id' => $cluster->id], $request->user()->id); PortalAudit::save($chain ?? new ValueChain, [...$data, 'cluster_id' => $cluster->id], $request->user()->id);
return back()->with('success', 'Etapa da cadeia de valor guardada.'); return back()->with('success', 'Etapa da cadeia de valor guardada.');
@@ -2,6 +2,8 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Services\PortalEditorialSubjects;
use App\Services\PortalEditorialWorkflow;
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;
@@ -30,7 +32,8 @@ class InvestmentStructureRelationController extends Controller
...($kind === 'cluster-project' ? ['role' => ['required', Rule::in(['anchor', 'complementary', 'supporting'])]] : []), ...($kind === 'cluster-project' ? ['role' => ['required', Rule::in(['anchor', 'complementary', 'supporting'])]] : []),
]); ]);
DB::transaction(function () use ($data, $table, $left, $right, $leftTable, $request): void { $proposal = null;
DB::transaction(function () use ($data, $table, $left, $right, $leftTable, $request, $kind, &$proposal): void {
DB::table($leftTable)->where('id', $data[$left])->lockForUpdate()->firstOrFail(); DB::table($leftTable)->where('id', $data[$left])->lockForUpdate()->firstOrFail();
$existing = DB::table($table)->where($left, $data[$left])->where($right, $data[$right])->whereNull('deleted_at')->lockForUpdate()->first(); $existing = DB::table($table)->where($left, $data[$left])->where($right, $data[$right])->whereNull('deleted_at')->lockForUpdate()->first();
abort_if($existing !== null, 409, 'Associacao ja registada.'); abort_if($existing !== null, 409, 'Associacao ja registada.');
@@ -40,8 +43,15 @@ class InvestmentStructureRelationController extends Controller
$id = (string) Str::uuid(); $id = (string) Str::uuid();
DB::table($table)->insert([...$values, 'id' => $id, 'source_system' => 'portal-management']); DB::table($table)->insert([...$values, 'id' => $id, 'source_system' => 'portal-management']);
$this->audit($request, $table, $id, 'submitted', 1); $this->audit($request, $table, $id, 'submitted', 1);
if (app(PortalEditorialSubjects::class)->available()) {
$proposal = app(PortalEditorialWorkflow::class)->saveSubject($request->user(), $kind, $id, 0, $data, true);
}
}); });
if ($proposal) {
return redirect('/management/editorial/subjects/'.$kind.'/'.$proposal->subject_key)->with('success', 'Associação guardada numa proposta privada.');
}
return back()->with('success', 'Associacao submetida para revisao independente.'); return back()->with('success', 'Associacao submetida para revisao independente.');
} }
@@ -50,6 +60,12 @@ class InvestmentStructureRelationController extends Controller
abort_unless(in_array($action, ['validate', 'revoke'], true), 404); abort_unless(in_array($action, ['validate', 'revoke'], true), 404);
[$table] = $this->definition($kind); [$table] = $this->definition($kind);
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]); $data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
if (app(PortalEditorialSubjects::class)->writes($kind, $id)) {
app(PortalEditorialSubjects::class)->authorize($request->user(), $kind, $id, true);
abort_if($request->expectsJson(), 409, 'Continue em /management/editorial/subjects/'.$kind.'/'.$id.' para rever a edição e publicar a decisão separadamente.');
return redirect('/management/editorial/subjects/'.$kind.'/'.$id)->with('success', 'Prepare ou confira a edição antes de decidir. Para retirar, marque a proposta de retirada.');
}
DB::transaction(function () use ($request, $table, $id, $action, $data): void { DB::transaction(function () use ($request, $table, $id, $action, $data): void {
$relation = DB::table($table)->where('id', $id)->lockForUpdate()->first(); $relation = DB::table($table)->where('id', $id)->lockForUpdate()->first();
@@ -2,8 +2,16 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\DevelopmentCorridor;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\InvestmentZone;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Models\Project;
use App\Services\InvestmentZoneOperationalProfile;
use App\Services\InvestmentZones; use App\Services\InvestmentZones;
use App\Services\PortalEditorialSubjects;
use App\Services\PortalEditorialWorkflow;
use App\Services\PortalProfileAccess; use App\Services\PortalProfileAccess;
use App\Services\TerritoryGeometry; use App\Services\TerritoryGeometry;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -16,7 +24,7 @@ class InvestmentTerritoryController extends Controller
{ {
public function geometries(Request $request): JsonResponse public function geometries(Request $request): JsonResponse
{ {
$data = $request->validate(['territory_id' => ['required', 'uuid']]); $data = $request->validate(['territory_id' => ['required', 'uuid'], 'include_children' => ['sometimes', 'boolean']]);
$profile = $request->is('minhas-oportunidades/*'); $profile = $request->is('minhas-oportunidades/*');
$management = $request->is('management/*') || $profile; $management = $request->is('management/*') || $profile;
$actor = $request->user(); $actor = $request->user();
@@ -31,7 +39,7 @@ class InvestmentTerritoryController extends Controller
} }
return response()->json([ return response()->json([
...app(TerritoryGeometry::class)->context($data['territory_id'], $internal), ...app(TerritoryGeometry::class)->context($data['territory_id'], $internal, $request->boolean('include_children')),
'geometry_scope' => $internal ? 'authorized_internal' : 'public', 'geometry_scope' => $internal ? 'authorized_internal' : 'public',
])->header('Cache-Control', 'private, no-store'); ])->header('Cache-Control', 'private, no-store');
} }
@@ -82,6 +90,18 @@ class InvestmentTerritoryController extends Controller
$table = self::TABLES[$kind] ?? abort(404); $table = self::TABLES[$kind] ?? abort(404);
$record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->first(); $record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->first();
abort_unless($record !== null, 404); abort_unless($record !== null, 404);
if ($dossier = app(PortalEditorialWorkflow::class)->structureDossier($kind, $id)) {
$model = ['projects' => Project::class, 'clusters' => EconomicCluster::class, 'corridors' => DevelopmentCorridor::class][$kind] ?? abort(404);
$working = app(PortalEditorialWorkflow::class)->workingStructure($model::findOrFail($id), $dossier);
$record->primary_territory_id = $working->getAttribute('primary_territory_id');
$record->territory_version = $working->getAttribute('territory_version');
} elseif (in_array($kind, ['projects', 'clusters', 'corridors'], true) && app(PortalEditorialSubjects::class)->available()) {
$record = app(PortalEditorialSubjects::class)->working($kind, $record);
} elseif ($kind === 'zones' && app(InvestmentZoneOperationalProfile::class)->installed()) {
$working = app(InvestmentZoneOperationalProfile::class)->management(InvestmentZone::findOrFail($id));
$record->primary_territory_id = $working['primary_territory_id'];
$record->territory_version = $working['territory_version'];
}
$path = []; $path = [];
$current = $record->primary_territory_id; $current = $record->primary_territory_id;
for ($i = 0; $current && $i < 5; $i++) { for ($i = 0; $current && $i < 5; $i++) {
@@ -93,7 +113,7 @@ class InvestmentTerritoryController extends Controller
$current = $location->parent_id; $current = $location->parent_id;
} }
return response()->json(['version' => $record->territory_version, 'path' => $path]); return response()->json(['version' => $record->territory_version, 'path' => $path])->header('Cache-Control', 'private, no-store');
} }
public function save(Request $request, string $kind, string $id): JsonResponse public function save(Request $request, string $kind, string $id): JsonResponse
@@ -103,11 +123,29 @@ class InvestmentTerritoryController extends Controller
abort_unless($request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403); abort_unless($request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403);
} }
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'path' => ['present', 'array', 'max:4'], 'path.*' => ['required', 'uuid', 'distinct']]); $data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'path' => ['present', 'array', 'max:4'], 'path.*' => ['required', 'uuid', 'distinct']]);
$version = DB::transaction(function () use ($request, $table, $id, $data) { $dossier = app(PortalEditorialWorkflow::class)->structureDossier($kind, $id, true);
$structural = ! $dossier && in_array($kind, ['projects', 'clusters', 'corridors'], true) && app(PortalEditorialSubjects::class)->writes($kind, $id);
$version = DB::transaction(function () use ($request, $table, $id, $data, $dossier, $kind, $structural) {
if ($dossier) {
$dossier = InvestmentDossier::whereKey($dossier->id)->lockForUpdate()->firstOrFail();
}
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)'); DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
if ($structural) {
app(PortalEditorialSubjects::class)->lock($kind, $id, ['primary_territory_id' => $data['path'] === [] ? null : $data['path'][array_key_last($data['path'])]]);
}
$record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first(); $record = DB::table($table)->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
abort_unless($record !== null, 404); abort_unless($record !== null, 404);
abort_unless((int) $record->territory_version === $data['version'], 409, 'Localização alterada. Recarregue a ficha.'); $effectiveVersion = (int) $record->territory_version;
if ($dossier) {
$model = ['projects' => Project::class, 'clusters' => EconomicCluster::class, 'corridors' => DevelopmentCorridor::class][$kind] ?? abort(404);
$effectiveVersion = (int) app(PortalEditorialWorkflow::class)->workingStructure($model::findOrFail($id), $dossier)->getAttribute('territory_version');
} elseif ($structural) {
$effectiveVersion = (int) app(PortalEditorialSubjects::class)->working($kind, $record)->territory_version;
} elseif ($kind === 'zones' && app(InvestmentZoneOperationalProfile::class)->installed()) {
$working = app(InvestmentZoneOperationalProfile::class)->management(InvestmentZone::findOrFail($id));
$effectiveVersion = (int) $working['territory_version'];
}
abort_unless($effectiveVersion === $data['version'], 409, 'Localização alterada. Recarregue a ficha.');
$parent = null; $parent = null;
$names = []; $names = [];
foreach (array_values($data['path']) as $index => $locationId) { foreach (array_values($data['path']) as $index => $locationId) {
@@ -119,13 +157,26 @@ class InvestmentTerritoryController extends Controller
$names[] = $location->name; $names[] = $location->name;
} }
$version = $data['version'] + 1; $version = $data['version'] + 1;
if ($dossier) {
$workflow = app(PortalEditorialWorkflow::class);
$workflow->saveStructure($request->user(), $model::findOrFail($id), $dossier, (int) $workflow->workingPortfolio($dossier)->getAttribute('version_no'), ['primary_territory_id' => $parent, 'territory_version' => $version]);
return $version;
}
if ($structural) {
$workflow = app(PortalEditorialWorkflow::class);
$workflow->saveSubject($request->user(), $kind, $id, $workflow->subjectVersion($kind, $id), ['primary_territory_id' => $parent, 'territory_version' => $version]);
return $version;
}
$changes = ['primary_territory_id' => $parent, 'territory_version' => $version, 'updated_at' => now()]; $changes = ['primary_territory_id' => $parent, 'territory_version' => $version, 'updated_at' => now()];
if (in_array($table, ['opportunities', 'investment_zones'], true)) { if (in_array($table, ['opportunities', 'investment_zones'], true)) {
$changes['province'] = $names[0] ?? null; $changes['province'] = $names[0] ?? null;
$changes['district'] = $names[1] ?? null; $changes['district'] = $names[1] ?? null;
} }
if ($table === 'investment_zones') { if ($table === 'investment_zones') {
app(InvestmentZones::class)->save($id, [...$changes, 'version_no' => $record->version_no], $request->user()->id); $workingVersion = app(InvestmentZoneOperationalProfile::class)->workingVersion(InvestmentZone::findOrFail($id));
app(InvestmentZones::class)->save($id, [...$changes, 'version_no' => $workingVersion], $request->user()->id);
} else { } else {
DB::table($table)->where('id', $id)->update($changes); DB::table($table)->where('id', $id)->update($changes);
} }
@@ -136,6 +187,8 @@ class InvestmentTerritoryController extends Controller
return $version; return $version;
}); });
return response()->json(['version' => $version]); $zoneDraft = $kind === 'zones' && (app(InvestmentZoneOperationalProfile::class)->editorialEnabled() || DB::table('investment_zones')->where('id', $id)->value('category') === 'industrial_park');
return response()->json(['version' => $version, 'pending_publication' => $dossier !== null || $structural || $zoneDraft]);
} }
} }
@@ -3,10 +3,19 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\InvestmentSubmission; use App\Models\InvestmentSubmission;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User; use App\Models\User;
use App\Services\CountryCatalogue; use App\Services\CountryCatalogue;
use App\Services\FundingProgrammes;
use App\Services\InvestmentGeography;
use App\Services\InvestmentOpportunityAlerts;
use App\Services\InvestmentProfileCommands;
use App\Services\InvestmentWorkspace; use App\Services\InvestmentWorkspace;
use App\Services\VirtualDesk;
use App\Services\OpportunityManagement;
use App\Services\OrganizationCountry; use App\Services\OrganizationCountry;
use App\Services\Procurement;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -18,9 +27,11 @@ use Inertia\Response;
class InvestmentWorkspaceController extends Controller class InvestmentWorkspaceController extends Controller
{ {
public function profile(Request $request, InvestmentWorkspace $workspace): Response|JsonResponse public function profile(Request $request, InvestmentWorkspace $workspace): \Symfony\Component\HttpFoundation\Response
{ {
$data = ['organizationCountryAvailable' => app(OrganizationCountry::class)->available(), 'organizations' => app(OrganizationCountry::class)->represented($request->user()), 'countries' => app(CountryCatalogue::class)->all(), 'account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations') $entry = $request->validate(['dossier' => 'nullable|uuid']);
$continuation = ! empty($entry['dossier']) ? app(VirtualDesk::class)->case($request->user(), $entry['dossier']) : null;
$data = ['actorId' => $request->user()->id, 'organizationCountryAvailable' => app(OrganizationCountry::class)->available(), 'organizations' => app(OrganizationCountry::class)->represented($request->user()), 'countries' => app(CountryCatalogue::class)->all(), 'account' => $workspace->account($request->user()->id), 'companies' => DB::table('investment_company_declarations')
->where('user_id', $request->user()->id)->orderByDesc('created_at')->get(['id', 'version', 'payload'])->map(function ($company) { ->where('user_id', $request->user()->id)->orderByDesc('created_at')->get(['id', 'version', 'payload'])->map(function ($company) {
$company->payload = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR); $company->payload = json_decode(Crypt::decryptString($company->payload), true, 512, JSON_THROW_ON_ERROR);
$company->countrySource = $company->payload['organization_country_snapshot'] ?? null; $company->countrySource = $company->payload['organization_country_snapshot'] ?? null;
@@ -28,12 +39,24 @@ class InvestmentWorkspaceController extends Controller
return $company; return $company;
})]; })];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/profile', $data); $data['continuation'] = $continuation ? ['id' => $continuation->id, 'title' => $continuation->title, 'href' => '/investimentos/'.$continuation->id.'#entidade-promotora'] : null;
$forms = config('company-comparison.forms');
abort_unless(is_array($forms), 503, 'As formas jurídicas estão temporariamente indisponíveis.');
$data['legalForms'] = [];
foreach ($forms as $code => $form) {
$data['legalForms'][] = ['value' => $code, 'label' => $form['title']];
}
Inertia::encryptHistory();
$response = $request->expectsJson() ? response()->json($data) : Inertia::render('investment/profile', $data)->toResponse($request);
$response->headers->set('Cache-Control', 'no-store, private');
return $response;
} }
public function saveProfile(Request $request): RedirectResponse|JsonResponse public function saveProfile(Request $request): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], $data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'operation_key' => ['sometimes', 'required', 'uuid'],
'payload' => ['required', 'array:phone,country,residence_country_code,sector,experience,investment_capacity'], 'payload' => ['required', 'array:phone,country,residence_country_code,sector,experience,investment_capacity'],
'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'payload.residence_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => ['nullable', 'string', 'max:100'], 'payload.phone' => ['nullable', 'string', 'max:30'], 'payload.country' => ['nullable', 'string', 'max:100'],
@@ -41,12 +64,19 @@ class InvestmentWorkspaceController extends Controller
'payload.investment_capacity' => ['nullable', 'string', 'max:1000']]); 'payload.investment_capacity' => ['nullable', 'string', 'max:1000']]);
$version = DB::transaction(function () use ($request, $data) { $version = DB::transaction(function () use ($request, $data) {
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail(); DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail();
$commands = app(InvestmentProfileCommands::class);
$command = ['kind' => 'account', 'target_id' => null, 'version' => (int) $data['version'], 'payload' => $data['payload']];
$replay = $commands->replay($request->user(), $data['operation_key'] ?? null, $command);
if ($replay !== null) {
return $replay['version'];
}
$row = DB::table('investment_accounts')->where('user_id', $request->user()->id)->first(); $row = DB::table('investment_accounts')->where('user_id', $request->user()->id)->first();
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'Perfil alterado. Recarregue.'); abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'Perfil alterado. Recarregue.');
$version = (int) $data['version'] + 1; $version = (int) $data['version'] + 1;
DB::table('investment_accounts')->updateOrInsert(['user_id' => $request->user()->id], ['version' => $version, DB::table('investment_accounts')->updateOrInsert(['user_id' => $request->user()->id], ['version' => $version,
'payload' => Crypt::encryptString(json_encode($data['payload'], JSON_THROW_ON_ERROR)), 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]); 'payload' => Crypt::encryptString(json_encode($data['payload'], JSON_THROW_ON_ERROR)), 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
$this->audit($request, 'profile_saved', 'investment_accounts', null, ['version' => $version]); $this->audit($request, 'profile_saved', 'investment_accounts', null, ['version' => $version]);
$commands->record($request->user(), $data['operation_key'] ?? null, $command, ['version' => $version]);
return $version; return $version;
}); });
@@ -56,8 +86,9 @@ class InvestmentWorkspaceController extends Controller
public function company(Request $request, ?string $id = null): RedirectResponse|JsonResponse public function company(Request $request, ?string $id = null): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => ['required', 'integer', 'min:0'], $data = $request->validate(['version' => ['required', 'integer', 'min:0'], 'operation_key' => ['sometimes', 'required', 'uuid'],
'payload' => ['required', 'array:name,country,incorporation_country_code,registration,sector,role,description'], 'payload' => ['required', 'array:name,country,incorporation_country_code,registration,legal_form,sector,role,description'],
'payload.legal_form' => ['nullable', \Illuminate\Validation\Rule::in(array_keys(config('company-comparison.forms')))],
'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()], 'payload.incorporation_country_code' => ['nullable', 'string', app(CountryCatalogue::class)->rule()],
'payload.name' => ['required', 'string', 'min:2', 'max:200'], 'payload.country' => ['required_without:payload.incorporation_country_code', 'nullable', 'string', 'max:100'], 'payload.name' => ['required', 'string', 'min:2', 'max:200'], 'payload.country' => ['required_without:payload.incorporation_country_code', 'nullable', 'string', 'max:100'],
'payload.registration' => ['nullable', 'string', 'max:100'], 'payload.sector' => ['nullable', 'string', 'max:150'], 'payload.registration' => ['nullable', 'string', 'max:100'], 'payload.sector' => ['nullable', 'string', 'max:150'],
@@ -66,6 +97,12 @@ class InvestmentWorkspaceController extends Controller
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail(); DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail();
$row = $id ? DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $request->user()->id)->first() : null; $row = $id ? DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $request->user()->id)->first() : null;
abort_if($id && ! $row, 404); abort_if($id && ! $row, 404);
$commands = app(InvestmentProfileCommands::class);
$command = ['kind' => 'company', 'target_id' => $id, 'version' => (int) $data['version'], 'payload' => $data['payload']];
$replay = $commands->replay($request->user(), $data['operation_key'] ?? null, $command);
if ($replay !== null) {
return $replay;
}
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'Declaração alterada. Recarregue.'); abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'Declaração alterada. Recarregue.');
abort_if(! $id && DB::table('investment_company_declarations')->where('user_id', $request->user()->id)->count() >= 20, 422, 'Máximo de vinte empresas declaradas.'); abort_if(! $id && DB::table('investment_company_declarations')->where('user_id', $request->user()->id)->count() >= 20, 422, 'Máximo de vinte empresas declaradas.');
$id ??= (string) Str::uuid(); $id ??= (string) Str::uuid();
@@ -79,6 +116,7 @@ class InvestmentWorkspaceController extends Controller
DB::table('investment_company_declarations')->updateOrInsert(['id' => $id], ['user_id' => $request->user()->id, 'version' => $version, DB::table('investment_company_declarations')->updateOrInsert(['id' => $id], ['user_id' => $request->user()->id, 'version' => $version,
'payload' => $encrypted, 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]); 'payload' => $encrypted, 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
$this->audit($request, 'company_declared', 'investment_company_declarations', $id, ['version' => $version, 'before_payload' => $row?->payload, 'after_payload' => $encrypted]); $this->audit($request, 'company_declared', 'investment_company_declarations', $id, ['version' => $version, 'before_payload' => $row?->payload, 'after_payload' => $encrypted]);
$commands->record($request->user(), $data['operation_key'] ?? null, $command, ['id' => $id, 'version' => $version]);
return ['id' => $id, 'version' => $version]; return ['id' => $id, 'version' => $version];
}); });
@@ -95,13 +133,25 @@ class InvestmentWorkspaceController extends Controller
public function reuseOrganizationCountry(Request $request, string $id, OrganizationCountry $service): RedirectResponse|JsonResponse public function reuseOrganizationCountry(Request $request, string $id, OrganizationCountry $service): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => 'required|integer|min:1', 'organization_id' => 'required|uuid', 'organization_version' => 'required|integer|min:1']); $data = $request->validate(['version' => 'required|integer|min:1', 'organization_id' => 'required|uuid', 'organization_version' => 'required|integer|min:1', 'operation_key' => ['sometimes', 'required', 'uuid']]);
$result = DB::transaction(function () use ($request, $id, $data, $service) { $result = DB::transaction(function () use ($request, $id, $data, $service) {
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->firstOrFail();
$row = DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $request->user()->id)->lockForUpdate()->first(); $row = DB::table('investment_company_declarations')->where('id', $id)->where('user_id', $request->user()->id)->lockForUpdate()->first();
abort_unless($row !== null, 404); abort_unless($row !== null, 404);
$snapshot = $service->readableSnapshot($request->user(), $data['organization_id']);
$commands = app(InvestmentProfileCommands::class);
$command = ['kind' => 'organization_country_reuse', 'target_id' => $row->id, 'version' => (int) $data['version'], 'payload' => ['organization_id' => $snapshot['organization_id'], 'organization_version' => (int) $data['organization_version']]];
$replay = $commands->replay($request->user(), $data['operation_key'] ?? null, $command);
if ($replay !== null) {
if (! isset($replay['country'])) {
throw new \LogicException('Stored country reuse receipt unavailable.');
}
return ['version' => $replay['version'], 'country' => $replay['country']];
}
abort_unless((int) $row->version === (int) $data['version'], 409, 'Declaração alterada. Recarregue.'); abort_unless((int) $row->version === (int) $data['version'], 409, 'Declaração alterada. Recarregue.');
$snapshot = $service->snapshot($request->user(), $data['organization_id']);
abort_unless((int) $snapshot['organization_version'] === (int) $data['organization_version'], 409, 'País mestre alterado. Recarregue.'); abort_unless((int) $snapshot['organization_version'] === (int) $data['organization_version'], 409, 'País mestre alterado. Recarregue.');
abort_unless($snapshot['country'] !== null, 422, 'País de constituição não informado no cadastro mestre.');
$payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR); $payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
$payload['incorporation_country_code'] = $snapshot['country']; $payload['incorporation_country_code'] = $snapshot['country'];
$payload['organization_country_snapshot'] = $snapshot; $payload['organization_country_snapshot'] = $snapshot;
@@ -109,24 +159,49 @@ class InvestmentWorkspaceController extends Controller
DB::table('investment_company_declarations')->where('id', $id)->update(['payload' => $encrypted, 'version' => $row->version + 1, 'updated_at' => now()]); DB::table('investment_company_declarations')->where('id', $id)->update(['payload' => $encrypted, 'version' => $row->version + 1, 'updated_at' => now()]);
$this->audit($request, 'organization_country_reused', 'investment_company_declarations', $id, ['version' => $row->version + 1, $this->audit($request, 'organization_country_reused', 'investment_company_declarations', $id, ['version' => $row->version + 1,
'before_payload' => $row->payload, 'after_payload' => $encrypted, 'organization_id' => $data['organization_id'], 'organization_version' => $snapshot['organization_version']]); 'before_payload' => $row->payload, 'after_payload' => $encrypted, 'organization_id' => $data['organization_id'], 'organization_version' => $snapshot['organization_version']]);
$commands->record($request->user(), $data['operation_key'] ?? null, $command, ['version' => $row->version + 1, 'country' => $snapshot['country']]);
return ['version' => $row->version + 1, 'country' => $snapshot['country']]; return ['version' => $row->version + 1, 'country' => $snapshot['country']];
}); });
return $request->expectsJson() ? response()->json($result) : back()->with('success', 'País mestre reutilizado nesta declaração; manifestações anteriores não alteradas.'); return $request->expectsJson() ? response()->json($result)->header('Cache-Control', 'no-store, private') : back()->with('success', 'País mestre reutilizado nesta declaração; manifestações anteriores não alteradas.');
} }
public function notifications(Request $request): Response|JsonResponse public function notifications(Request $request): Response|JsonResponse
{ {
$query = DB::table('investment_notifications')->where('user_id', $request->user()->id); $query = DB::table('investment_notifications')->where('user_id', $request->user()->id);
if (! $request->user()->can('manage-portal')) { $alerts = app(InvestmentOpportunityAlerts::class);
$available = $alerts->installed();
if ($available) {
$query->where(function ($sources) use ($request, $alerts) {
$sources->whereIn('opportunity_id', Opportunity::published()->select('id'))
->orWhere(function ($legacy) use ($request) {
$legacy->whereNotNull('submission_id');
if (! $request->user()->can('manage-portal')) {
$legacy->whereIn('submission_id', InvestmentSubmission::where('user_id', $request->user()->id)->select('id'));
}
});
if ($alerts->tendersAvailable()) {
$sources->orWhereIn('tender_version_id', app(Procurement::class)->readableVersions()->select('id'));
}
if ($alerts->fundingAvailable()) {
$sources->orWhereIn('funding_version_id', app(FundingProgrammes::class)->readableVersions()->select('id'));
}
});
} elseif (! $request->user()->can('manage-portal')) {
$query->whereIn('submission_id', InvestmentSubmission::where('user_id', $request->user()->id)->select('id')); $query->whereIn('submission_id', InvestmentSubmission::where('user_id', $request->user()->id)->select('id'));
} }
$data = ['unread' => (clone $query)->whereNull('read_at')->count(), 'notifications' => $query->orderByDesc('created_at')->paginate(20)->through(function ($row) { $data = ['alertPreferences' => $available ? $alerts->preferences($request->user()->id) : null,
$row->payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR); 'alertOptions' => $available ? ['frequencies' => InvestmentOpportunityAlerts::FREQUENCIES,
'sectors' => Sector::choices()->whereNotNull('published_at')->orderBy('name')->get(['slug', 'name']),
'provinces' => app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->orderBy('name')->get(['id', 'name']),
'categories' => OpportunityManagement::CATEGORIES, 'tendersAvailable' => $alerts->tendersAvailable(), 'fundingAvailable' => $alerts->fundingAvailable(),
'tenderRegimes' => config('procurement.regimes'), 'tenderActs' => config('procurement.acts')] : null,
'unread' => (clone $query)->whereNull('read_at')->count(), 'notifications' => $query->orderByDesc('created_at')->orderByDesc('id')->paginate(20)->through(function ($row) {
$row->payload = json_decode(Crypt::decryptString($row->payload), true, 512, JSON_THROW_ON_ERROR);
return $row; return $row;
})]; })];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/notifications', $data); return $request->expectsJson() ? response()->json($data) : Inertia::render('investment/notifications', $data);
} }
@@ -135,7 +210,17 @@ class InvestmentWorkspaceController extends Controller
{ {
$row = DB::table('investment_notifications')->where('id', $id)->where('user_id', $request->user()->id)->first(); $row = DB::table('investment_notifications')->where('id', $id)->where('user_id', $request->user()->id)->first();
abort_unless($row !== null, 404); abort_unless($row !== null, 404);
$this->submission($request, $row->submission_id); if ($row->opportunity_id ?? null) {
abort_unless(Opportunity::published()->whereKey($row->opportunity_id)->exists(), 404);
} elseif ($row->tender_version_id ?? null) {
abort_unless(app(InvestmentOpportunityAlerts::class)->tendersAvailable()
&& app(Procurement::class)->readableVersions()->where('id', $row->tender_version_id)->exists(), 404);
} elseif ($row->funding_version_id ?? null) {
abort_unless(app(InvestmentOpportunityAlerts::class)->fundingAvailable()
&& app(FundingProgrammes::class)->readableVersions()->where('id', $row->funding_version_id)->exists(), 404);
} else {
$this->submission($request, $row->submission_id);
}
DB::table('investment_notifications')->where('id', $id)->whereNull('read_at')->update(['read_at' => now()]); DB::table('investment_notifications')->where('id', $id)->whereNull('read_at')->update(['read_at' => now()]);
return $request->expectsJson() ? response()->json(['read' => true]) : back(); return $request->expectsJson() ? response()->json(['read' => true]) : back();
@@ -16,8 +16,11 @@ 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 App\Services\InvestmentZones;
use App\Services\PublicSearchMetrics;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
@@ -108,6 +111,9 @@ class InvestmentZoneController extends Controller
$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();
if (! $management) {
app(PublicSearchMetrics::class)->candidate($request, 'zones', $rows->total(), $filters);
}
$rows->getCollection()->transform(function (InvestmentZone $zone) use ($management) { $rows->getCollection()->transform(function (InvestmentZone $zone) use ($management) {
$territoryPath = app(InvestmentGeography::class)->path($zone->primary_territory_id, $management); $territoryPath = app(InvestmentGeography::class)->path($zone->primary_territory_id, $management);
$zone->setAttribute('province', collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province); $zone->setAttribute('province', collect($territoryPath)->firstWhere('location_type', 'province')->name ?? $zone->province);
@@ -287,6 +293,13 @@ class InvestmentZoneController extends Controller
return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved)); return response()->json(app(InvestmentZoneOperationalProfile::class)->management($saved));
} }
public function editorialReview(Request $request, string $id, string $action): JsonResponse
{
$data = $request->validate(['version_no' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:3000']);
return response()->json(app(InvestmentZoneOperationalProfile::class)->review($id, $request->user(), (int) $data['version_no'], $action, $data['reason']));
}
public function revisions(string $id): JsonResponse public function revisions(string $id): JsonResponse
{ {
InvestmentZone::findOrFail($id); InvestmentZone::findOrFail($id);
@@ -294,6 +307,30 @@ class InvestmentZoneController extends Controller
return response()->json(DB::table('investment_zone_revisions')->where('zone_id', $id)->orderByDesc('version_no')->paginate(20, ['id', 'version_no', 'actor_id', 'action', 'sha256', 'created_at'])); return response()->json(DB::table('investment_zone_revisions')->where('zone_id', $id)->orderByDesc('version_no')->paginate(20, ['id', 'version_no', 'actor_id', 'action', 'sha256', 'created_at']));
} }
public function revision(Request $request, string $id, int $version): JsonResponse
{
abort_unless(app(InvestmentZoneOperationalProfile::class)->reviewAccess($request->user()), 403);
InvestmentZone::findOrFail($id);
$revision = DB::table('investment_zone_revisions')->where('zone_id', $id)->where('version_no', $version)->first();
abort_unless($revision !== null, 404);
try {
$json = Crypt::decryptString($revision->snapshot);
abort_unless(hash_equals($revision->sha256, hash('sha256', $json)), 409);
$snapshot = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
$fields = $snapshot['draft']['fields'] ?? $snapshot['public'] ?? $snapshot;
$details = $fields['operational_details'] ?? [];
if (isset($details['private_ciphertext'])) {
$details = json_decode(Crypt::decryptString($details['private_ciphertext']), true, 512, JSON_THROW_ON_ERROR);
}
} catch (\Throwable $e) {
abort(409, 'Não foi possível conferir esta versão. O histórico foi preservado.');
}
return response()->json(['version_no' => $revision->version_no, 'action' => $revision->action,
'fields' => Arr::only($fields, ['name', 'description']),
'observations' => array_map(fn ($row) => Arr::only($row, ['label', 'value', 'unit', 'scope', 'period_start', 'period_end', 'source_reference']), $details['integral']['observations'] ?? [])]);
}
public function validateLocation(Request $request, InvestmentZones $zones, string $id): JsonResponse public function validateLocation(Request $request, InvestmentZones $zones, string $id): JsonResponse
{ {
InvestmentZoneAccess::requireRole($request->user(), 'territory_reviewers'); InvestmentZoneAccess::requireRole($request->user(), 'territory_reviewers');
@@ -3,6 +3,8 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\InvestmentZone; use App\Models\InvestmentZone;
use App\Services\PortalEditorialSubjects;
use App\Services\PortalEditorialWorkflow;
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;
@@ -36,14 +38,28 @@ class InvestmentZoneRelationController extends Controller
DB::table('investment_zone_relations')->insert([...$data, 'id' => $relation, 'zone_id' => $id, DB::table('investment_zone_relations')->insert([...$data, 'id' => $relation, 'zone_id' => $id,
'editor_id' => $request->user()->id, 'created_at' => now(), 'updated_at' => now()]); 'editor_id' => $request->user()->id, 'created_at' => now(), 'updated_at' => now()]);
$this->audit($relation, $request->user()->id, 'created', 1); $this->audit($relation, $request->user()->id, 'created', 1);
if (app(PortalEditorialSubjects::class)->available()) {
app(PortalEditorialWorkflow::class)->saveSubject($request->user(), 'zone-relations', $relation, 0, [...$data, 'zone_id' => $id], true);
}
return response()->json(DB::table('investment_zone_relations')->where('id', $relation)->first(), 201); $record = DB::table('investment_zone_relations')->where('id', $relation)->first();
if (app(PortalEditorialSubjects::class)->available()) {
$record->editorial_url = '/management/editorial/subjects/zone-relations/'.$relation;
$record->pending_publication = true;
}
return response()->json($record, 201);
}); });
} }
public function review(Request $request, string $id, string $action): JsonResponse public function review(Request $request, string $id, string $action): JsonResponse
{ {
$data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]); $data = $request->validate(['version_no' => ['required', 'integer', 'min:1']]);
if (app(PortalEditorialSubjects::class)->writes('zone-relations', $id)) {
app(PortalEditorialSubjects::class)->authorize($request->user(), 'zone-relations', $id, true);
return response()->json(['pending_publication' => true, 'editorial_url' => '/management/editorial/subjects/zone-relations/'.$id]);
}
return DB::transaction(function () use ($request, $id, $action, $data) { return DB::transaction(function () use ($request, $id, $action, $data) {
$relation = DB::table('investment_zone_relations')->where('id', $id)->lockForUpdate()->first(); $relation = DB::table('investment_zone_relations')->where('id', $id)->lockForUpdate()->first();
@@ -3,6 +3,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Models\InvestmentSubmission; use App\Models\InvestmentSubmission;
use App\Models\Sector;
use App\Services\InvestmentComplements; use App\Services\InvestmentComplements;
use App\Services\InvestmentCorridorContext; use App\Services\InvestmentCorridorContext;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
@@ -19,6 +20,27 @@ use Inertia\Response;
final class InvestorContextController extends Controller final class InvestorContextController extends Controller
{ {
/** Explicit choices only; a title never assigns an activity or amount.
* @return array<string,mixed>
*/
private function ideaEntry(Request $request): array
{
$entry = $request->validate([
'project_title' => 'nullable|string|max:200',
'sector_id' => 'nullable|integer|exists:sectors,id',
'sector' => 'nullable|string|max:100|exists:sectors,slug',
'investment_budget_min' => 'nullable|numeric|min:0',
'investment_budget_max' => ['nullable', 'numeric', 'min:0', Rule::when($request->filled('investment_budget_min'), 'gte:investment_budget_min')],
'currency' => 'nullable|regex:/^[A-Z]{3}$/D',
]);
if (empty($entry['sector_id']) && ! empty($entry['sector'])) {
$entry['sector_id'] = (string) Sector::where('slug', $entry['sector'])->value('id');
}
unset($entry['sector']);
return $entry;
}
/** /**
* @return array<array-key, mixed> * @return array<array-key, mixed>
*/ */
@@ -82,17 +104,21 @@ final class InvestorContextController extends Controller
public function options(Request $r, InvestorContext $context): JsonResponse public function options(Request $r, InvestorContext $context): JsonResponse
{ {
$d = $r->validate(['q' => 'nullable|string|max:120']); $d = $r->validate(['q' => 'nullable|string|max:120', 'sector_id' => 'nullable|integer|exists:sectors,id', 'province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid']);
$filters = array_intersect_key($d, array_flip(['province_id', 'district_id', 'admin_post_id', 'locality_id']));
if (! empty($d['sector_id'])) {
$filters['sector'] = Sector::whereKey($d['sector_id'])->firstOrFail()->slug;
}
return response()->json($context->options($d['q'] ?? '')); return response()->json($context->options($d['q'] ?? '', $filters));
} }
public function corridorOptions(Request $r): JsonResponse public function corridorOptions(Request $r): JsonResponse
{ {
$data = $r->validate(['corridor' => ['nullable', Rule::in(array_keys(config('investment_corridors')))], 'territory' => 'nullable|uuid']); $data = $r->validate(['corridor' => ['nullable', Rule::in(array_keys(config('investment_corridors')))], 'territory' => 'nullable|uuid', 'include_corridors' => 'nullable|boolean']);
$service = app(InvestmentCorridorContext::class); $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(), return response()->json(['corridors' => ($data['include_corridors'] ?? true) ? 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)]); 'parks' => $service->parks($data['corridor'] ?? null, $data['territory'] ?? null)]);
} }
@@ -101,6 +127,16 @@ final class InvestorContextController extends Controller
return response()->json($context->saveDraft($r->user(), $id, $r->all())); return response()->json($context->saveDraft($r->user(), $id, $r->all()));
} }
public function supplyAggregate(Request $r, string $id, InvestorContext $context): JsonResponse
{
return response()->json($context->saveSupplyAggregate($r->user(), $id, $r->all()))->header('Cache-Control', 'private, no-store');
}
public function promoter(Request $r, string $id, InvestorContext $context): JsonResponse
{
return response()->json($r->isMethod('GET') ? $context->promoter($r->user(), $id) : $context->setPromoter($r->user(), $id, $r->all()))->header('Cache-Control', 'private, no-store');
}
public function edit(Request $r, string $id, InvestorContext $context): Response public function edit(Request $r, string $id, InvestorContext $context): Response
{ {
$data = $context->view($r->user(), $id); $data = $context->view($r->user(), $id);
@@ -133,8 +169,8 @@ final class InvestorContextController extends Controller
} }
} }
$complements = isset($draft['complements']) ? app(InvestmentComplements::class)->resolve($draft['complements'], $data['context']['complements'] ?? []) : ($data['context']['complements'] ?? []); $complements = isset($draft['complements']) ? app(InvestmentComplements::class)->resolve($draft['complements'], $data['context']['complements'] ?? []) : ($data['context']['complements'] ?? []);
$entryTerritory = null; $entryTerritory = ($source['kind'] ?? '') === 'territory' ? $source : null;
if (($source['kind'] ?? null) === 'portfolio') { if ($r->hasAny(['province_id', 'district_id', 'admin_post_id', 'locality_id'])) {
$path = app(InvestmentGeography::class)->selection($r->validate(['province_id' => 'nullable|uuid', 'district_id' => 'nullable|uuid', 'admin_post_id' => 'nullable|uuid', 'locality_id' => 'nullable|uuid'])); $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) { if ($path) {
$entryTerritory = $context->reference('territory:'.$path[array_key_last($path)]->id); $entryTerritory = $context->reference('territory:'.$path[array_key_last($path)]->id);
@@ -148,7 +184,7 @@ final class InvestorContextController extends Controller
} }
} }
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']) : [])]); return Inertia::render('investor-path/context', ['entryIdea' => $this->ideaEntry($r), '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): JsonResponse public function preview(Request $r, string $id, InvestorContext $context): JsonResponse
@@ -175,7 +211,7 @@ final class InvestorContextController extends Controller
$choices = $this->entryChoices($r, $context); $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]); return Inertia::render('investor-path/context-start', ['entrySubmission' => $entrySubmission, 'entryComplements' => $this->entryComplements($r), 'entryQuery' => [...$this->ideaEntry($r), ...$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): JsonResponse|Response public function installation(Request $r, InvestorContextInstallation $install): JsonResponse|Response
@@ -2,11 +2,16 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Services\CompanyComparison;
use App\Services\FintechInvestment; use App\Services\FintechInvestment;
use App\Services\InvestmentGuides;
use App\Services\InvestmentZonePathContext; use App\Services\InvestmentZonePathContext;
use App\Services\InvestorPath; use App\Services\InvestorPath;
use App\Services\LegacyContent; use App\Services\LegacyContent;
use App\Services\SectorContentAnalysis;
use App\Services\SectorResourceReferences;
use App\Services\SectorInvestment; use App\Services\SectorInvestment;
use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -16,10 +21,22 @@ use Inertia\Response;
class InvestorPathController extends Controller class InvestorPathController extends Controller
{ {
public function fiscalReport(Request $request, string $id, string $reportId, \App\Services\SimulationFormDrafts $drafts): JsonResponse
{
abort_unless(app(InvestorPath::class)->available(), 404);
$request->validate(['opportunity' => 'nullable|string|max:150']);
$data = $drafts->dossierReport($request->user(), $id, $reportId, $request->query('opportunity'));
return response()->json($data)->header('Content-Disposition', 'attachment; filename="relatorio-fiscal-'.$reportId.'.json"')
->header('X-Content-Type-Options', 'nosniff');
}
public function index(Request $request, InvestorPath $path): JsonResponse|Response public function index(Request $request, InvestorPath $path): JsonResponse|Response
{ {
abort_unless($path->available(), 404); abort_unless($path->available(), 404);
$data = ['contexts' => $path->contexts($request->user())]; $data = ['contexts' => $path->contexts($request->user()),
'companyComparisonAnswers' => $request->has('company_comparison') ? app(CompanyComparison::class)->answers(['answers' => $request->input('company_comparison')]) : null,
'guideSelection' => $request->has('investment_guide') ? app(InvestmentGuides::class)->selection($request->array('investment_guide')) : null];
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data); return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
} }
@@ -28,6 +45,9 @@ class InvestorPathController extends Controller
{ {
abort_unless($path->available(), 404); abort_unless($path->available(), 404);
$data = ['contexts' => $path->contexts($request->user()), 'sectorSource' => app(SectorInvestment::class)->context($sectorSlug)]; $data = ['contexts' => $path->contexts($request->user()), 'sectorSource' => app(SectorInvestment::class)->context($sectorSlug)];
if (isset(SectorResourceReferences::SOURCES[$sectorSlug]) && $request->filled('resource_area')) {
$data['resourceSource'] = app(SectorResourceReferences::class)->selection($sectorSlug, ['area_id' => $request->query('resource_area'), 'location_label' => $request->query('resource_location'), 'group_id' => $request->query('resource_group'), 'source_sha256' => $request->query('resource_source')]);
}
return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data); return $request->expectsJson() ? response()->json($data) : Inertia::render('investor-path/index', $data);
} }
@@ -57,6 +77,9 @@ class InvestorPathController extends Controller
public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse public function create(Request $request, InvestorPath $path): JsonResponse|RedirectResponse
{ {
$comparison = $request->has('company_comparison') ? app(CompanyComparison::class)->answers(['answers' => $request->input('company_comparison')]) : null;
$guide = $request->has('investment_guide') ? app(InvestmentGuides::class)->selection($request->array('investment_guide')) : null;
abort_if($comparison !== null && $guide !== null, 422, 'Escolha o contexto de preparação que pretende continuar.');
$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) { if ($zone) {
$request->validate(['confirm' => 'required|accepted']); $request->validate(['confirm' => 'required|accepted']);
@@ -66,22 +89,38 @@ class InvestorPathController extends Controller
if ($sector !== null) { if ($sector !== null) {
app(SectorInvestment::class)->context($sector); app(SectorInvestment::class)->context($sector);
} }
$reference = $request->input('sector_reference');
if ($reference !== null) {
abort_unless(isset(SectorResourceReferences::SOURCES[$sector]) && is_array($reference), 422);
app(SectorResourceReferences::class)->selection($sector, $reference);
}
$source = $request->input('content_resource_id'); $source = $request->input('content_resource_id');
if ($source !== null) { if ($source !== null) {
$resourceId = filter_var($source, FILTER_VALIDATE_INT); $resourceId = filter_var($source, FILTER_VALIDATE_INT);
abort_unless(is_int($resourceId) && $resourceId !== 0, 422); abort_unless(is_int($resourceId) && $resourceId !== 0, 422);
app(LegacyContent::class)->articleForResource($resourceId); app(LegacyContent::class)->articleForResource($resourceId);
} }
$id = DB::transaction(function () use ($path, $request, $source, $sector, $zone): string { $analysis = $source !== null ? app(SectorContentAnalysis::class)->selection(app(LegacyContent::class)->articleForResource((int) $source), $request->all()) : null;
abort_if($request->filled('evidence') && $source === null, 422);
$id = DB::transaction(function () use ($path, $request, $source, $sector, $zone, $reference): string {
if ($reference !== null) {
DB::table('users')->where('id', $request->user()->id)->lockForUpdate()->first();
}
$existingReferenceCase = $reference !== null ? DB::table('desk_cases')->where('user_id', $request->user()->id)->where('client_key', $request->input('client_key'))->first() : null;
$id = $path->create($request->user(), $request->all()); $id = $path->create($request->user(), $request->all());
if ($existingReferenceCase) {
$selection = app(SectorResourceReferences::class)->selection($sector, $reference);
$oldPayload = app(VirtualDesk::class)->decode($existingReferenceCase->payload);
abort_unless(array_any($oldPayload['investor_path']['sector_references'] ?? [], fn ($row) => $row['key'] === $selection['key']), 409, 'A chave de criação já foi usada com outra referência sectorial; recupere o dossier existente.');
}
if ($source !== null) { if ($source !== null) {
$case = $path->view($request->user(), $id)['case']; $case = $path->view($request->user(), $id)['case'];
app(LegacyContent::class)->attach($request->user(), $id, ['version' => $case['version'], 'resource_id' => (int) $source]); app(SectorContentAnalysis::class)->attach($request->user(), $id, ['version' => $case['version'], 'resource_id' => (int) $source, ...$request->only(['evidence', 'source_sha256', 'source_version', 'idea'])]);
} }
if ($sector !== null) { if ($sector !== null) {
$case = $path->view($request->user(), $id)['case']; $case = $path->view($request->user(), $id)['case'];
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, 'sector_reference' => $reference]);
} }
if ($zone) { if ($zone) {
@@ -92,7 +131,12 @@ class InvestorPathController extends Controller
return $id; return $id;
}); });
return $request->expectsJson() ? response()->json(['id' => $id], 201) : redirect('/investimentos/'.$id)->with('success', 'Investimento guardado no seu dossier.'); $href = $comparison === null ? ($analysis ? app(SectorContentAnalysis::class)->continuation($id, $analysis) : '/investimentos/'.$id) : '/investimentos/'.$id.'/forma-juridica?'.http_build_query(['answers' => $comparison]);
if ($guide !== null) {
$href = '/investimentos/'.$id.'/guias/'.$guide['slug'].'?'.http_build_query(['current' => 1, 'selection' => 1, 'sha256' => $guide['sha256'], 'instruments' => $guide['instruments']]);
}
return $request->expectsJson() ? response()->json(['id' => $id, ...($comparison !== null ? ['comparison_href' => $href] : []), ...($guide !== null ? ['guide_href' => $href] : [])], 201) : redirect($href)->with('success', 'Investimento guardado no seu dossier.');
} }
public function show(Request $request, string $id, InvestorPath $path): JsonResponse|Response public function show(Request $request, string $id, InvestorPath $path): JsonResponse|Response
@@ -4,6 +4,8 @@ namespace App\Http\Controllers;
use App\Services\InvestorPath; use App\Services\InvestorPath;
use App\Services\LegacyContent; use App\Services\LegacyContent;
use App\Services\PublicSearchMetrics;
use App\Services\SectorContentAnalysis;
use App\Services\VirtualDesk; use App\Services\VirtualDesk;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -24,6 +26,7 @@ class LegacyContentController extends Controller
$articles = array_values(array_filter($articles, fn ($item) => $q === '' $articles = array_values(array_filter($articles, fn ($item) => $q === ''
|| str_contains(mb_strtolower(strip_tags($item['html'].' '.$item['title'])), mb_strtolower($q)))); || str_contains(mb_strtolower(strip_tags($item['html'].' '.$item['title'])), mb_strtolower($q))));
$match = $articles !== []; $match = $articles !== [];
app(PublicSearchMetrics::class)->candidate($request, 'sector_content', count($articles), ['q' => $q]);
return Inertia::render('portal/legacy', ['article' => $article, 'articles' => $articles, 'view' => 'landing', 'query' => $q, 'match' => $match]); return Inertia::render('portal/legacy', ['article' => $article, 'articles' => $articles, 'view' => 'landing', 'query' => $q, 'match' => $match]);
} }
@@ -38,12 +41,19 @@ class LegacyContentController extends Controller
abort_unless($path->available(), 404); abort_unless($path->available(), 404);
$article = $legacy->article($legacySlug); $article = $legacy->article($legacySlug);
return Inertia::render('investor-path/index', ['contexts' => $path->contexts($request->user()), 'contentSource' => $article]); $analysis = app(SectorContentAnalysis::class)->selection($article, $request->all());
return Inertia::render('investor-path/index', ['contexts' => $path->contexts($request->user()), 'contentSource' => $article, 'sectorIdea' => $analysis, 'analysisAction' => $request->query('analysis_action') === 'compare' ? 'compare' : 'prepare']);
} }
public function attach(Request $request, string $id, LegacyContent $legacy): JsonResponse|RedirectResponse public function attach(Request $request, string $id, LegacyContent $legacy): JsonResponse|RedirectResponse
{ {
$legacy->attach($request->user(), $id, $request->all()); $analysis = app(SectorContentAnalysis::class)->attach($request->user(), $id, $request->all());
if ($analysis) {
$href = app(SectorContentAnalysis::class)->continuation($id, $analysis);
return $request->expectsJson() ? response()->json(['saved' => true, 'continue' => $href]) : redirect($href);
}
return $request->expectsJson() ? response()->json(['saved' => true]) : redirect('/investimentos/'.$id)->with('success', 'Referência guardada no dossier.'); return $request->expectsJson() ? response()->json(['saved' => true]) : redirect('/investimentos/'.$id)->with('success', 'Referência guardada no dossier.');
} }
@@ -0,0 +1,72 @@
<?php
namespace App\Http\Controllers;
use App\Services\InvestmentGeography;
use App\Services\OfferPublicCatalogue;
use App\Services\OpportunityManagement;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
final class OfferPublicCatalogueController extends Controller
{
public function index(Request $request, OfferPublicCatalogue $catalogue): Response
{
$filters = $catalogue->filters($request);
return $this->uncached(Inertia::render('offers/catalogue', [...$catalogue->page($request, $filters), 'filters' => $filters,
'mapData' => in_array($filters['view'] ?? '', ['map', 'combined'], true) ? $catalogue->map($filters) : null,
'territorySelection' => app(InvestmentGeography::class)->selection($filters),
'references' => ['categories' => OpportunityManagement::CATEGORIES, 'options' => [], 'clusters' => [], 'corridors' => [], 'projects' => [], 'locations' => [], 'sectors' => []]])->toResponse($request));
}
public function show(Request $request, int $id, OfferPublicCatalogue $catalogue): Response
{
return $this->uncached(Inertia::render('offers/public-detail', ['offer' => $catalogue->detail($id)])->toResponse($request));
}
public function search(Request $request, OfferPublicCatalogue $catalogue): JsonResponse
{
return response()->json($catalogue->page($request, $catalogue->filters($request)))->header('Cache-Control', 'private, no-store');
}
public function detail(int $id, OfferPublicCatalogue $catalogue): JsonResponse
{
return response()->json(['data' => $catalogue->detail($id)])->header('Cache-Control', 'private, no-store');
}
public function map(Request $request, OfferPublicCatalogue $catalogue): JsonResponse
{
return response()->json($catalogue->map($catalogue->filters($request)))->header('Cache-Control', 'private, no-store');
}
public function export(Request $request, OfferPublicCatalogue $catalogue): StreamedResponse
{
$result = $catalogue->records($catalogue->filters($request));
return response()->streamDownload(function () use ($result) {
$stream = fopen('php://output', 'w');
if ($stream === false) {
return;
}
fwrite($stream, "\xEF\xBB\xBF");
fputcsv($stream, ['Título', 'Categoria', 'Localização', 'Preço', 'Moeda', 'Publicação', 'URL'], ';', '"', '');
foreach ($result['records'] as $record) {
$fields = [$record['title'], $record['category'], implode(' / ', array_column($record['location'], 'name')),
$record['price']['mode'] === 'negotiable' ? 'A negociar' : $record['price']['amount'], $record['price']['currency'], $record['published_at'], url($record['url'])];
fputcsv($stream, array_map(fn ($value) => preg_match('/^[\s]*[=+@-]/u', (string) $value) ? "'".$value : $value, $fields), ';', '"', '');
}
fclose($stream);
}, 'ofertas.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store', 'X-Export-Limit' => '1000', 'X-Results-Truncated' => $result['truncated'] ? 'true' : 'false']);
}
private function uncached(Response $response): Response
{
$response->headers->set('Cache-Control', 'private, no-store');
return $response;
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers;
use App\Services\OpportunityCuration;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class OpportunityCurationController extends Controller
{
public function show(Request $request, int $id, OpportunityCuration $service): Response
{
$base = str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities';
$filters = $request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
return Inertia::render('management/opportunity-curation', [...$service->state($request->user(), $id, (int) ($filters['page'] ?? 1)), 'basePath' => $base]);
}
public function preview(Request $request, int $id, OpportunityCuration $service): JsonResponse
{
return response()->json($service->preview($request->user(), $id, $request->all()))->header('Cache-Control', 'private, no-store');
}
public function confirm(Request $request, int $id, OpportunityCuration $service): JsonResponse
{
return response()->json($service->confirm($request->user(), $id, $request->all()))->header('Cache-Control', 'private, no-store');
}
}
@@ -8,12 +8,14 @@ use App\Models\Sector;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\OpportunityCanonicalContract; use App\Services\OpportunityCanonicalContract;
use App\Services\OpportunityCanonicalResponse; use App\Services\OpportunityCanonicalResponse;
use App\Services\OpportunityCuration;
use App\Services\OpportunityManagement; 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\OpportunityPromotion;
use App\Services\OpportunityResources; use App\Services\OpportunityResources;
use App\Services\OpportunityTechnicalIncidents;
use App\Services\OpportunityWorkflowTasks; use App\Services\OpportunityWorkflowTasks;
use App\Services\PortalProfileAccess; use App\Services\PortalProfileAccess;
use App\Services\ProactiveInvestment; use App\Services\ProactiveInvestment;
@@ -129,6 +131,8 @@ class OpportunityManagementController extends Controller
$access->authorize($request->user(), 'view', $record); $access->authorize($request->user(), 'view', $record);
} }
Inertia::share(['basePath' => str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities', Inertia::share(['basePath' => str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades' : '/management/opportunities',
'curationHref' => $record && app(OpportunityCuration::class)->allowed($request->user(), $record)
? (str_starts_with($request->path(), 'minhas-oportunidades') ? '/minhas-oportunidades/' : '/management/opportunities/').$record->id.'/destaque' : null,
'canonicalOptions' => ($record?->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades')) ? app(OpportunityCanonicalContract::class)->options($request->user(), $record) : null, 'canonicalOptions' => ($record?->owner_user_id !== null || str_starts_with($request->path(), 'minhas-oportunidades')) ? app(OpportunityCanonicalContract::class)->options($request->user(), $record) : null,
'workflowState' => $record ? $access->state($record) : null, 'workflowState' => $record ? $access->state($record) : null,
'profileReauthenticationRequired' => $record && $record->owner_user_id !== null 'profileReauthenticationRequired' => $record && $record->owner_user_id !== null
@@ -139,6 +143,7 @@ class OpportunityManagementController extends Controller
'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' => []],
'workflowTasks' => $record && $record->owner_user_id !== null ? app(OpportunityWorkflowTasks::class)->listing($record) : [], 'workflowTasks' => $record && $record->owner_user_id !== null ? app(OpportunityWorkflowTasks::class)->listing($record) : [],
'workflowIncidents' => $record && $record->owner_user_id !== null ? app(OpportunityTechnicalIncidents::class)->recent($request->user(), $record) : [],
'profileMode' => $record ? $record->owner_user_id !== null : str_starts_with($request->path(), 'minhas-oportunidades'), 'profileMode' => $record ? $record->owner_user_id !== null : str_starts_with($request->path(), 'minhas-oportunidades'),
'profileActions' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->actions($request->user(), $record) : [], 'profileContext' => $record?->workflow_context, 'profileOrganization' => $record?->organization_id]); 'profileActions' => $record && $record->owner_user_id !== null ? app(OpportunityProfileWorkflow::class)->actions($request->user(), $record) : [], 'profileContext' => $record?->workflow_context, 'profileOrganization' => $record?->organization_id]);
$values = $record ? $service->values($record) : []; $values = $record ? $service->values($record) : [];
@@ -10,6 +10,8 @@ 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\OpportunityTechnicalExecution;
use App\Services\OpportunityTechnicalIncidents;
use App\Services\OpportunityTerritorialPresentation; use App\Services\OpportunityTerritorialPresentation;
use App\Services\OrganizationCountryInstallation; use App\Services\OrganizationCountryInstallation;
use App\Services\PortalProfileAccess; use App\Services\PortalProfileAccess;
@@ -75,7 +77,7 @@ class OpportunityResourceController extends Controller
return hash('sha256', json_encode([$request->user()->getAuthIdentifier(), $plan['target'], $plan['migration'], $plan['code_hash']], JSON_THROW_ON_ERROR)); return hash('sha256', json_encode([$request->user()->getAuthIdentifier(), $plan['target'], $plan['migration'], $plan['code_hash']], JSON_THROW_ON_ERROR));
} }
public function index(int $id, OpportunityResources $service): Response public function index(int $id, OpportunityResources $service): \Symfony\Component\HttpFoundation\Response
{ {
$opportunity = Opportunity::withTrashed()->findOrFail($id); $opportunity = Opportunity::withTrashed()->findOrFail($id);
app(PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity); app(PortalProfileAccess::class)->authorize(request()->user(), 'view', $opportunity);
@@ -100,7 +102,9 @@ class OpportunityResourceController extends Controller
} }
} }
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)]); Inertia::encryptHistory();
return tap(Inertia::render('management/opportunity-resources', ['opportunity' => $opportunity, 'etag' => app(OpportunityManagement::class)->etag($opportunity), 'resources' => $resources, 'technicalIncidents' => app(OpportunityTechnicalIncidents::class)->recent(request()->user(), $opportunity), '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)])->toResponse(request()), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
} }
public function reuseLibrary(Request $request, int $id): JsonResponse public function reuseLibrary(Request $request, int $id): JsonResponse
@@ -116,9 +120,18 @@ class OpportunityResourceController extends Controller
if (is_string($input['payload'] ?? null)) { if (is_string($input['payload'] ?? null)) {
$input['payload'] = json_decode($input['payload'], true); $input['payload'] = json_decode($input['payload'], true);
} }
$record = $service->save($request->user(), $id, $kind, $input, $request->file('file'), $resourceId); $operation = function () use ($request, $id, $kind, $input, $resourceId, $service) {
$record = $service->save($request->user(), $id, $kind, $input, $request->file('file'), $resourceId);
return response()->json(['id' => $record->id, 'message' => 'Recurso guardado no servidor. Não publicado; validação final e scan são independentes.', 'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id))], $resourceId ? 200 : 201); return response()->json(['id' => $record->id, 'message' => 'Recurso guardado no servidor. Não publicado; validação final e scan são independentes.', 'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id))], $resourceId ? 200 : 201);
};
if (! $request->hasFile('file') || ! in_array($kind, ['documents', 'images'], true)) {
return $operation();
}
$before = Opportunity::withTrashed()->findOrFail($id);
app(PortalProfileAccess::class)->authorize($request->user(), 'edit', $before);
return app(OpportunityTechnicalExecution::class)->run($request->user(), $before, $kind === 'images' ? 'upload_image' : 'upload_document', $input, $operation);
} }
public function lifecycle(Request $request, int $id, string $kind, string $resourceId, OpportunityResources $service): JsonResponse public function lifecycle(Request $request, int $id, string $kind, string $resourceId, OpportunityResources $service): JsonResponse
@@ -130,9 +143,14 @@ class OpportunityResourceController extends Controller
public function prepareImage(Request $request, int $id, string $resourceId, OpportunityImageProcessor $service): JsonResponse public function prepareImage(Request $request, int $id, string $resourceId, OpportunityImageProcessor $service): JsonResponse
{ {
$service->prepare($request->user(), $id, $resourceId, $request->all()); $before = Opportunity::withTrashed()->findOrFail($id);
app(PortalProfileAccess::class)->authorize($request->user(), 'edit', $before);
return response()->json(['message' => 'Derivadas WebP geradas sem EXIF original; scan independente e revisão de divulgação pendentes.']); return app(OpportunityTechnicalExecution::class)->run($request->user(), $before, 'prepare_image', $request->all(), function () use ($request, $id, $resourceId, $service) {
$service->prepare($request->user(), $id, $resourceId, $request->all());
return response()->json(['message' => 'Derivadas WebP geradas sem EXIF original; scan independente e revisão de divulgação pendentes.']);
});
} }
public function previewImage(int $id, string $resourceId, string $documentId): \Illuminate\Http\Response|BinaryFileResponse public function previewImage(int $id, string $resourceId, string $documentId): \Illuminate\Http\Response|BinaryFileResponse
@@ -2,26 +2,35 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Jobs\ScanDocumentForMalware;
use App\Models\ExistingBusiness; use App\Models\ExistingBusiness;
use App\Models\Sector; use App\Models\Sector;
use App\Models\User;
use App\Services\InvestmentCatalogue; use App\Services\InvestmentCatalogue;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\InvestmentRelations; use App\Services\InvestmentRelations;
use App\Services\PartnershipAgreementHistory;
use App\Services\PartnershipAgreementProjection;
use App\Services\PartnershipAgreements;
use App\Services\PartnershipCandidacies;
use App\Services\PartnershipCandidacyHistory;
use App\Services\PartnershipDraftSaves;
use App\Services\PartnershipExchange; use App\Services\PartnershipExchange;
use App\Services\PartnershipMatching; use App\Services\PartnershipMatching;
use App\Services\PartnershipMilestones;
use App\Services\PartnershipNotifications;
use App\Services\PartnershipPublication;
use App\Services\PartnershipPublicationHistory;
use App\Services\PartnershipRoomUploads;
use App\Services\PartnershipSources; use App\Services\PartnershipSources;
use App\Services\PublicSearchMetrics;
use App\Services\SectorOrganization; 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;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\BinaryFileResponse;
@@ -82,6 +91,7 @@ class PartnershipExchangeController extends Controller
} }
$results = $query->orderByDesc('p.id')->select(['p.id', 'p.title', 'p.sector', 'p.province', 'p.kind', 'p.partnership_type', 'p.sector_id', 'p.deadline', 'p.published_at']) $results = $query->orderByDesc('p.id')->select(['p.id', 'p.title', 'p.sector', 'p.province', 'p.kind', 'p.partnership_type', 'p.sector_id', 'p.deadline', 'p.published_at'])
->selectRaw("p.payload->>'summary' as summary")->paginate(12)->withQueryString(); ->selectRaw("p.payload->>'summary' as summary")->paginate(12)->withQueryString();
app(PublicSearchMetrics::class)->candidate($request, 'partnerships', $results->total(), $filters);
if ($request->expectsJson()) { if ($request->expectsJson()) {
return response()->json($results); return response()->json($results);
} }
@@ -119,16 +129,23 @@ class PartnershipExchangeController extends Controller
public function dashboard(Request $request): Response public function dashboard(Request $request): Response
{ {
$actor = $request->user(); $actor = $request->user();
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id'); $exchange = app(PartnershipExchange::class);
$organizations = $exchange->readableOrganizations($actor);
$mine = DB::table('portal_partnerships')->where(fn ($q) => $q->where(fn ($own) => $own->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))->latest()->limit(100)->get(); $mine = DB::table('portal_partnerships')->where(fn ($q) => $q->where(fn ($own) => $own->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))->latest()->limit(100)->get();
$interests = DB::table('partnership_interests as i')->join('portal_partnerships as p', 'p.id', '=', 'i.partnership_id') $interests = DB::table('partnership_interests as i')->join('portal_partnerships as p', 'p.id', '=', 'i.partnership_id')
->leftJoin('partnership_rooms as room', 'room.interest_id', '=', 'i.id') ->leftJoin('partnership_rooms as room', 'room.interest_id', '=', 'i.id')
->where(fn ($q) => $q->where(fn ($own) => $own->where('i.user_id', $actor->id)->whereNull('i.organization_id'))->orWhereIn('i.organization_id', $organizations)) ->where(fn ($q) => $q->where(fn ($own) => $own->where('i.user_id', $actor->id)->whereNull('i.organization_id'))->orWhereIn('i.organization_id', $organizations))
->select(['i.id', 'i.partnership_id', 'i.status', 'i.decision_reason', 'p.title', 'room.id as room_id'])->orderByDesc('i.id')->limit(100)->get(); ->select(['i.id', 'i.partnership_id', 'i.status', 'i.decision_reason', 'p.title', 'p.status as partnership_status', 'p.user_id', 'p.organization_id', 'room.id as room_id'])->orderByDesc('i.id')->limit(100)->get()
->map(function ($interest) use ($actor, $exchange) {
$canRead = $interest->partnership_status === 'published' || $exchange->owns($actor, $interest, false) || Gate::forUser($actor)->allows('manage-portal');
return ['id' => $interest->id, 'partnership_id' => $interest->partnership_id, 'status' => $interest->status, 'decision_reason' => $interest->decision_reason,
'title' => $canRead ? $interest->title : null, 'partnership_href' => $canRead ? '/parcerias/'.$interest->partnership_id : null, 'room_id' => $interest->room_id];
});
$moderation = Gate::forUser($actor)->allows('manage-portal') ? DB::table('portal_partnerships')->whereIn('status', ['submitted', 'pending'])->orderBy('updated_at')->get(['id', 'title', 'status', 'version']) : []; $moderation = Gate::forUser($actor)->allows('manage-portal') ? DB::table('portal_partnerships')->whereIn('status', ['submitted', 'pending'])->orderBy('updated_at')->get(['id', 'title', 'status', 'version']) : [];
return Inertia::render('partnerships/dashboard', ['mine' => $mine->map(fn ($p) => ['id' => $p->id, 'title' => $p->title, 'status' => $p->status, 'version' => $p->version]), 'interests' => $interests, 'moderation' => $moderation, return Inertia::render('partnerships/dashboard', ['mine' => $mine->map(fn ($p) => ['id' => $p->id, 'title' => $p->title, 'status' => $p->status, 'version' => $p->version]), 'interests' => $interests, 'moderation' => $moderation,
'notifications' => DB::table('partnership_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(50)->get()]); 'notifications' => app(PartnershipNotifications::class)->forUser($actor)]);
} }
public function edit(Request $request, ?int $id = null): Response public function edit(Request $request, ?int $id = null): Response
@@ -141,7 +158,10 @@ class PartnershipExchangeController extends Controller
$origins = [['type' => $source['type'], 'target_id' => $source['target_id']]]; $origins = [['type' => $source['type'], 'target_id' => $source['target_id']]];
} }
return Inertia::render('partnerships/editor', ['record' => $record ? [...(array) $record, 'payload' => json_decode($record->payload, true)] : null, 'origins' => $origins, $payload = $record ? json_decode($record->payload, true) : [];
unset($payload['_creation_hash']);
return Inertia::render('partnerships/editor', ['editorActorId' => $request->user()->id, 'saveCommands' => $record ? app(PartnershipDraftSaves::class)->commands($request->user(), $record) : [], 'record' => $record ? [...(array) $record, 'payload' => $payload] : null, 'origins' => $origins,
'locations' => $record ? DB::table('partnership_locations')->where('partnership_id', $id)->get() : [], ...$this->catalogues($request)]); 'locations' => $record ? DB::table('partnership_locations')->where('partnership_id', $id)->get() : [], ...$this->catalogues($request)]);
} }
@@ -149,7 +169,7 @@ class PartnershipExchangeController extends Controller
{ {
$record = app(PartnershipExchange::class)->save($request->user(), $request->all(), $id); $record = app(PartnershipExchange::class)->save($request->user(), $request->all(), $id);
return $request->expectsJson() ? response()->json(['id' => $record->id, 'version' => $record->version, 'status' => $record->status]) : redirect('/parcerias/'.$record->id.'/editar')->with('success', 'Rascunho guardado.'); return $request->expectsJson() ? response()->json(['id' => $record->id, 'version' => $record->version, 'status' => $record->status, 'replayed' => (bool) ($record->command_replayed ?? false), 'saved_version' => $record->command_saved_version ?? null]) : redirect('/parcerias/'.$record->id.'/editar')->with('success', 'Rascunho guardado.');
} }
public function show(Request $request, int $id): Response|JsonResponse public function show(Request $request, int $id): Response|JsonResponse
@@ -163,17 +183,23 @@ class PartnershipExchangeController extends Controller
$privateDetails = ($payload['confidentiality'] ?? 'public') === 'private' && ! $owner && ! $moderator; $privateDetails = ($payload['confidentiality'] ?? 'public') === 'private' && ! $owner && ! $moderator;
$mine = $request->user() ? DB::table('partnership_interests')->where('partnership_id', $id)->get()->filter(fn ($i) => app(PartnershipExchange::class)->owns($request->user(), $i, false))->values() : collect(); $mine = $request->user() ? DB::table('partnership_interests')->where('partnership_id', $id)->get()->filter(fn ($i) => app(PartnershipExchange::class)->owns($request->user(), $i, false))->values() : collect();
$interests = $owner ? DB::table('partnership_interests')->where('partnership_id', $id)->orderBy('id')->get() : $mine; $interests = $owner ? DB::table('partnership_interests')->where('partnership_id', $id)->orderBy('id')->get() : $mine;
$interestData = $interests->map(function ($interest) use ($record) { $commands = $request->user() ? app(PartnershipCandidacies::class)->commands($request->user(), $id) : [];
$interestData = $interests->map(function ($interest) use ($record, $request, $commands) {
return [...(array) $interest, 'payload' => json_decode($interest->payload, true), 'assessment' => json_decode($interest->assessment, true), return [...(array) $interest, 'payload' => json_decode($interest->payload, true), 'assessment' => json_decode($interest->assessment, true),
'can_edit' => $request->user() && app(PartnershipExchange::class)->owns($request->user(), $interest), 'commands' => $commands[(int) $interest->id] ?? [],
'match' => app(PartnershipMatching::class)->explain($record, $interest), 'room_id' => DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id')]; 'match' => app(PartnershipMatching::class)->explain($record, $interest), 'room_id' => DB::table('partnership_rooms')->where('interest_id', $interest->id)->value('id')];
}); });
$props = ['record' => ['id' => $record->id, 'title' => $record->title, 'status' => $record->status, 'version' => $record->version, 'kind' => $record->kind, $props = ['record' => ['id' => $record->id, 'title' => $record->title, 'status' => $record->status, 'version' => $record->version, 'kind' => $record->kind,
'partnership_type' => $record->partnership_type, 'sector' => $record->sector, 'province' => $record->province, 'sector_id' => $record->sector_id, 'deadline' => $record->deadline, 'partnership_type' => $record->partnership_type, 'sector' => $record->sector, 'province' => $record->province, 'sector_id' => $record->sector_id, 'deadline' => $record->deadline,
'offer' => $privateDetails ? null : $record->offer, 'seeking' => $privateDetails ? null : $record->seeking, 'payload' => $privateDetails ? ['summary' => $payload['summary'] ?? '', 'confidentiality' => 'private'] : $payload], 'offer' => $privateDetails ? null : $record->offer, 'seeking' => $privateDetails ? null : $record->seeking, 'payload' => $privateDetails ? ['summary' => $payload['summary'] ?? '', 'confidentiality' => 'private'] : $payload],
'owner' => (bool) $owner, 'canEdit' => $request->user() && app(PartnershipExchange::class)->owns($request->user(), $record), 'moderator' => (bool) $moderator, 'owner' => (bool) $owner, 'canEdit' => $request->user() && app(PartnershipExchange::class)->owns($request->user(), $record), 'moderator' => (bool) $moderator,
'acceptingInterests' => app(PartnershipCandidacies::class)->accepting($record),
'canStartInterest' => $request->user() && ! $owner && ! DB::table('partnership_interests')->where('partnership_id', $id)->where('user_id', $request->user()->id)->exists(),
'origins' => app(PartnershipSources::class)->forPartnership($id, $owner ? $request->user() : null), 'interests' => $interestData, 'origins' => app(PartnershipSources::class)->forPartnership($id, $owner ? $request->user() : null), 'interests' => $interestData,
'locations' => app(InvestmentRelations::class)->locations(array_values(DB::table('partnership_locations')->where('partnership_id', $id)->get()->map(fn ($l) => ['id' => $l->geo_location_id, 'role' => $l->role, 'source_reference' => $l->source_reference])->all())), 'locations' => app(InvestmentRelations::class)->locations(array_values(DB::table('partnership_locations')->where('partnership_id', $id)->get()->map(fn ($l) => ['id' => $l->geo_location_id, 'role' => $l->role, 'source_reference' => $l->source_reference])->all())),
'history' => ($owner || $moderator) ? DB::table('partnership_events')->where('partnership_id', $id)->where('event_type', 'like', 'partnership_opportunity.%')->orderBy('occurred_at')->get(['event_type', 'actor_id', 'occurred_at', 'payload']) : [], 'historySummary' => ($owner || $moderator) ? app(PartnershipPublicationHistory::class)->summary($request->user(), $id) : null,
'publicationActions' => app(PartnershipPublication::class)->actions($request->user(), $record),
'publicationCommands' => app(PartnershipPublication::class)->commands($request->user(), $record),
...$this->catalogues($request)]; ...$this->catalogues($request)];
if ($request->user()) { if ($request->user()) {
Inertia::encryptHistory(); Inertia::encryptHistory();
@@ -182,39 +208,74 @@ class PartnershipExchangeController extends Controller
return $request->expectsJson() ? response()->json($props)->header('Cache-Control', 'private, no-store') : Inertia::render('partnerships/detail', $props); return $request->expectsJson() ? response()->json($props)->header('Cache-Control', 'private, no-store') : Inertia::render('partnerships/detail', $props);
} }
public function publicationHistory(Request $request, int $id): Response|JsonResponse
{
$data = $request->validate(['before' => 'nullable|string|max:4000']);
$history = app(PartnershipPublicationHistory::class)->page($request->user(), $id, $data['before'] ?? null);
return $request->expectsJson() ? response()->json($history) : Inertia::render('partnerships/publication-history', $history);
}
public function transition(Request $request, int $id): RedirectResponse|JsonResponse public function transition(Request $request, int $id): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000']); $data = $request->validate(['client_key' => 'nullable|uuid', 'version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000']);
$record = app(PartnershipExchange::class)->transition($request->user(), $id, $data['version'], $data['action'], $data['reason']); $record = app(PartnershipExchange::class)->transition($request->user(), $id, $data['version'], $data['action'], $data['reason'], $data['client_key'] ?? null);
return $request->expectsJson() ? response()->json(['status' => $record->status, 'version' => $record->version]) : back()->with('success', 'Decisão registada.'); return $request->expectsJson() ? response()->json(['id' => $record->id, 'status' => $record->status, 'version' => $record->version, 'replayed' => (bool) ($record->command_replayed ?? false)]) : back()->with('success', 'Decisão registada.');
} }
public function interest(Request $request, int $id): RedirectResponse|JsonResponse public function interest(Request $request, int $id): RedirectResponse|JsonResponse
{ {
$interest = app(PartnershipExchange::class)->interest($request->user(), $id, $request->all()); $interest = app(PartnershipExchange::class)->interest($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json(['id' => $interest->id, 'version' => $interest->version]) : back()->with('success', 'Interesse guardado.'); return $request->expectsJson() ? response()->json(['id' => $interest->id, 'version' => $interest->version, 'replayed' => (bool) ($interest->command_replayed ?? false)]) : back()->with('success', 'Interesse guardado.');
} }
public function decide(Request $request, int $id): RedirectResponse|JsonResponse public function decide(Request $request, int $id): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000', 'assessment' => 'array|max:7']); $data = $request->validate(['client_key' => 'nullable|uuid', 'partnership_version' => 'nullable|integer|min:1', 'weights_hash' => 'nullable|string|regex:/^[a-f0-9]{64}$/', 'version' => 'required|integer|min:1', 'action' => 'required|string', 'reason' => 'required|string|max:2000', 'assessment' => 'array|max:7']);
$interest = app(PartnershipExchange::class)->decideInterest($request->user(), $id, $data['version'], $data['action'], $data['reason'], $data['assessment'] ?? []); $interest = app(PartnershipExchange::class)->decideInterest($request->user(), $id, $data['version'], $data['action'], $data['reason'], $data['assessment'] ?? [], $data['partnership_version'] ?? null, $data['weights_hash'] ?? null, $data['client_key'] ?? null);
return $request->expectsJson() ? response()->json(['status' => $interest->status, 'version' => $interest->version]) : back()->with('success', 'Candidatura atualizada.'); return $request->expectsJson() ? response()->json(['status' => $interest->status, 'version' => $interest->version, 'replayed' => (bool) ($interest->command_replayed ?? false)]) : back()->with('success', 'Candidatura atualizada.');
}
public function candidacyHistory(Request $request, int $id): Response|JsonResponse
{
$data = $request->validate(['before' => 'nullable|string|max:4000']);
$history = app(PartnershipCandidacyHistory::class)->page($request->user(), $id, $data['before'] ?? null);
return $request->expectsJson() ? response()->json($history) : Inertia::render('partnerships/interest-history', $history);
}
public function agreementHistory(Request $request, int $id): Response|JsonResponse
{
$data = $request->validate(['before' => 'nullable|string|max:4000']);
$history = app(PartnershipAgreementHistory::class)->page($request->user(), $id, $data['before'] ?? null);
return $request->expectsJson() ? response()->json($history) : Inertia::render('partnerships/agreement-history', $history);
} }
public function room(Request $request, int $id): Response|JsonResponse public function room(Request $request, int $id): Response|JsonResponse
{ {
$context = app(PartnershipExchange::class)->room($request->user(), $id); $context = app(PartnershipExchange::class)->room($request->user(), $id);
$props = [...$context, 'room' => [...(array) $context['room'], 'agreement' => $context['room']->agreement ? json_decode($context['room']->agreement, true) : null], $participants = app(PartnershipExchange::class)->participants($context['partnership'], $context['interest']);
'messages' => DB::table('partnership_messages as m')->join('users as u', 'u.id', '=', 'm.author_id')->where('room_id', $id)->orderBy('m.id')->get(['m.id', 'm.body', 'm.created_at', 'm.author_id', 'u.name']), $participantIds = array_column($participants, 'id');
$canWrite = app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) || app(PartnershipExchange::class)->owns($request->user(), $context['interest']);
$canAssign = $canWrite && in_array($context['room']->status, ['agreement_recorded', 'agreed', 'execution'], true);
$creationKeys = app(PartnershipMilestones::class)->creationKeys($request->user(), (int) $context['partnership']->id, $id);
$partnership = (array) $context['partnership'];
$payload = json_decode($partnership['payload'], true, 512, JSON_THROW_ON_ERROR);
unset($payload['_creation_hash']);
$partnership['payload'] = json_encode($payload, JSON_THROW_ON_ERROR);
$props = [...$context, 'partnership' => $partnership, 'room' => [...(array) $context['room'], 'agreement' => app(PartnershipAgreementProjection::class)->current($context['room']->agreement)],
'messages' => DB::table('partnership_messages as m')->join('users as u', 'u.id', '=', 'm.author_id')->where('room_id', $id)->orderBy('m.id')->get(['m.id', 'm.body', 'm.created_at', 'm.author_id', 'm.client_key', 'u.name'])
->map(fn ($message) => [...(array) $message, 'client_key' => (int) $message->author_id === $request->user()->id ? $message->client_key : null]),
'documents' => DB::table('partnership_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('room_id', $id) 'documents' => DB::table('partnership_documents as link')->join('documents as d', 'd.id', '=', 'link.document_id')->where('room_id', $id)
->where(fn ($q) => $q->where('link.shared', true)->orWhere('link.owner_id', $request->user()->id)) ->where(fn ($q) => $q->where('link.shared', true)->orWhere('link.owner_id', $request->user()->id))
->get(['link.id', 'link.shared', 'link.owner_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.id as document_id']), ->get(['link.id', 'link.shared', 'link.owner_id', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.id as document_id']),
'milestones' => DB::table('partnership_milestones')->where('room_id', $id)->orderBy('id')->get(), 'milestones' => DB::table('partnership_milestones as m')->leftJoin('users as responsible', 'responsible.id', '=', 'm.responsible_id')->where('m.room_id', $id)->orderBy('m.id')
'canWrite' => app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) || app(PartnershipExchange::class)->owns($request->user(), $context['interest'])]; ->get(['m.*', 'responsible.name as responsible_name'])->map(fn ($milestone) => [...(array) $milestone, 'responsible_is_participant' => in_array((int) $milestone->responsible_id, $participantIds, true), 'client_key' => $creationKeys[(int) $milestone->id] ?? null]),
'agreementActorId' => $request->user()->id, 'agreementParty' => app(PartnershipAgreements::class)->party($request->user(), $context), 'agreementCommands' => app(PartnershipAgreements::class)->commands($request->user(), $context), 'participants' => $canAssign ? $participants : [], 'canWrite' => $canWrite];
return $request->expectsJson() ? response()->json($props) : Inertia::render('partnerships/room', $props); return $request->expectsJson() ? response()->json($props) : Inertia::render('partnerships/room', $props);
} }
@@ -223,9 +284,10 @@ class PartnershipExchangeController extends Controller
{ {
$data = $request->validate(['client_key' => 'required|uuid', 'body' => 'required|string|max:15000']); $data = $request->validate(['client_key' => 'required|uuid', 'body' => 'required|string|max:15000']);
DB::transaction(function () use ($request, $id, $data) { DB::transaction(function () use ($request, $id, $data) {
$context = app(PartnershipExchange::class)->room($request->user(), $id, true); $context = app(PartnershipExchange::class)->room($request->user(), $id);
abort_unless(app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) || app(PartnershipExchange::class)->owns($request->user(), $context['interest']), 403);
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first(); $locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409, 'Sala encerrada.'); abort_unless($locked !== null, 404);
$key = ['room_id' => $id, 'author_id' => $request->user()->id, 'client_key' => $data['client_key']]; $key = ['room_id' => $id, 'author_id' => $request->user()->id, 'client_key' => $data['client_key']];
$existing = DB::table('partnership_messages')->where($key)->first(); $existing = DB::table('partnership_messages')->where($key)->first();
if ($existing) { if ($existing) {
@@ -233,6 +295,7 @@ class PartnershipExchangeController extends Controller
return; return;
} }
abort_if(in_array($locked->status, ['closed', 'cancelled'], true), 409, 'Sala encerrada.');
DB::table('partnership_messages')->insert([...$key, 'body' => $data['body']]); DB::table('partnership_messages')->insert([...$key, 'body' => $data['body']]);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.message_created.v1', ['room_id' => $id], 'Nova mensagem privada', [$context['partnership']->user_id, $context['interest']->user_id]); app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.message_created.v1', ['room_id' => $id], 'Nova mensagem privada', [$context['partnership']->user_id, $context['interest']->user_id]);
}); });
@@ -242,100 +305,31 @@ class PartnershipExchangeController extends Controller
public function agreement(Request $request, int $id): RedirectResponse|JsonResponse public function agreement(Request $request, int $id): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['version' => 'required|integer|min:1', 'action' => 'required|in:record,confirm,start,complete,cancel,renew', 'title' => 'required_if:action,record|nullable|string|max:200', $result = app(PartnershipAgreements::class)->act($request->user(), $id, $request->all());
'terms' => 'required_if:action,record|nullable|string|max:20000', 'reason' => 'required|string|max:2000']);
DB::transaction(function () use ($request, $id, $data) {
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
$room = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
abort_unless((int) $room->version === (int) $data['version'], 409, 'Acordo alterado.');
$agreement = $room->agreement ? json_decode($room->agreement, true) : null;
$status = $room->status;
if ($data['action'] === 'record') {
abort_unless(in_array($status, ['negotiation', 'agreement_recorded'], true), 409);
$previous = $agreement['previous_versions'] ?? [];
if ($agreement) {
$previous[] = ['title' => $agreement['title'], 'terms' => $agreement['terms'], 'confirmations' => $agreement['confirmations'], 'recorded_at' => $agreement['recorded_at']];
}
$agreement = ['title' => $data['title'], 'terms' => $data['terms'], 'recorded_by' => $request->user()->id, 'recorded_at' => now()->toIso8601String(), 'confirmations' => [],
'parties' => [$context['partnership']->user_id, $context['interest']->user_id], 'legal_signature_status' => 'not_verified', 'previous_versions' => $previous];
$status = 'agreement_recorded';
} elseif ($data['action'] === 'confirm') {
abort_unless($status === 'agreement_recorded' && $agreement, 409);
$party = app(PartnershipExchange::class)->owns($request->user(), $context['partnership']) ? 'proponent' : 'candidate';
$agreement['confirmations'][$party] = ['actor_id' => $request->user()->id, 'date' => now()->toIso8601String(), 'reason' => $data['reason']];
if (count($agreement['confirmations']) === 2) {
$status = 'agreed';
}
} else {
$allowed = ['start' => ['agreed'], 'complete' => ['execution'], 'cancel' => ['negotiation', 'agreement_recorded', 'agreed', 'execution'], 'renew' => ['agreed', 'execution']];
abort_unless(in_array($status, $allowed[$data['action']] ?? [], true), 409);
if ($data['action'] === 'complete') {
abort_if(DB::table('partnership_milestones')->where('room_id', $id)->where('status', '!=', 'completed')->exists(), 409, 'Existem marcos pendentes.');
}
$status = ['start' => 'execution', 'complete' => 'closed', 'cancel' => 'cancelled', 'renew' => 'negotiation'][$data['action']];
if ($data['action'] === 'renew') {
$agreement['previous_versions'][] = ['title' => $agreement['title'], 'terms' => $agreement['terms'], 'confirmations' => $agreement['confirmations']];
$agreement['confirmations'] = [];
}
}
DB::table('partnership_rooms')->where('id', $id)->update(['agreement' => $agreement ? json_encode($agreement) : null, 'status' => $status, 'version' => $room->version + 1, 'updated_at' => now()]);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership_agreement.changed.v1', ['room_id' => $id, 'status' => $status, 'version' => $room->version + 1, 'reason' => $data['reason']], 'Acordo: '.$status, [$context['partnership']->user_id, $context['interest']->user_id]);
});
return $request->expectsJson() ? response()->json(['recorded' => true]) : back()->with('success', 'Acordo atualizado; assinatura jurídica não verificada.'); return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Acordo atualizado; assinatura jurídica não verificada.');
} }
public function milestone(Request $request, int $id, ?int $milestone = null): RedirectResponse|JsonResponse public function milestone(Request $request, int $id, ?int $milestone = null): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['title' => 'required|string|max:200', 'responsible_id' => 'required|integer', 'due_date' => 'nullable|date_format:Y-m-d', 'status' => 'required|in:pending,progress,completed', $data = $request->validate(['client_key' => 'nullable|uuid', 'title' => 'required|string|max:200', 'responsible_id' => 'required|integer', 'due_date' => 'nullable|date_format:Y-m-d', 'status' => 'required|in:pending,progress,completed',
'evidence' => 'required_if:status,completed|nullable|string|max:10000', 'version' => ($milestone ? 'required' : 'nullable').'|integer|min:1']); 'evidence' => 'required_if:status,completed|nullable|string|max:10000', 'version' => ($milestone ? 'required' : 'nullable').'|integer|min:1']);
DB::transaction(function () use ($request, $id, $milestone, $data) { if (isset($data['client_key'])) {
$context = app(PartnershipExchange::class)->room($request->user(), $id, true); $data['client_key'] = strtolower($data['client_key']);
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first(); }
abort_unless($locked !== null && in_array($locked->status, ['agreement_recorded', 'agreed', 'execution'], true), 409); $result = app(PartnershipMilestones::class)->save($request->user(), $id, $data, $milestone);
$responsible = User::query()->whereKey($data['responsible_id'])->first();
abort_unless($responsible !== null && (app(PartnershipExchange::class)->owns($responsible, $context['partnership']) || app(PartnershipExchange::class)->owns($responsible, $context['interest'])), 422, 'Responsável deve ser participante identificado.');
if ($milestone) {
$existing = DB::table('partnership_milestones')->where('room_id', $id)->where('id', $milestone)->lockForUpdate()->first();
abort_unless($existing !== null, 404);
abort_unless((int) $existing->version === (int) $data['version'], 409);
DB::table('partnership_milestones')->where('id', $milestone)->update([...$data, 'version' => $existing->version + 1, 'updated_at' => now()]);
} else {
unset($data['version']);
$milestone = DB::table('partnership_milestones')->insertGetId([...$data, 'room_id' => $id, 'created_at' => now(), 'updated_at' => now()]);
}
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership_milestone.changed.v1', ['milestone_id' => $milestone, 'status' => $data['status']], 'Marco atualizado', [$context['partnership']->user_id, $context['interest']->user_id]);
});
return $request->expectsJson() ? response()->json(['saved' => true]) : back()->with('success', 'Marco guardado.'); return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Marco guardado.');
} }
public function upload(Request $request, int $id): RedirectResponse|JsonResponse public function upload(Request $request, int $id): RedirectResponse|JsonResponse
{ {
$data = $request->validate(['file' => 'required|file|mimes:pdf,jpg,jpeg,png|max:10240', 'shared' => 'required|boolean']); $data = $request->validate(['client_key' => 'nullable|uuid', 'file' => 'required|file|mimes:pdf,jpg,jpeg,png|max:10240', 'shared' => 'required|boolean']);
$context = app(PartnershipExchange::class)->room($request->user(), $id, true);
$file = $request->file('file'); $file = $request->file('file');
$documentId = (string) Str::uuid(); abort_unless($file instanceof UploadedFile, 422);
$stored = $file->storeAs('partnerships/'.$id, $documentId, 'local'); $result = app(PartnershipRoomUploads::class)->save($request->user(), $id, $file, (bool) $data['shared'], isset($data['client_key']) ? strtolower($data['client_key']) : null);
abort_unless(is_string($stored) && $stored !== '', 503);
try {
DB::transaction(function () use ($request, $id, $data, $file, $documentId, $stored, $context) {
app(PartnershipExchange::class)->room($request->user(), $id, true);
$locked = DB::table('partnership_rooms')->where('id', $id)->lockForUpdate()->first();
abort_unless($locked !== null && ! in_array($locked->status, ['closed', 'cancelled'], true), 409);
DB::table('documents')->insert(['id' => $documentId, 'source_system' => 'partnership-exchange', 'data_classification' => 'restricted',
'file_name' => basename($file->getClientOriginalName()), 'media_type' => $file->getMimeType(), 'storage_key' => $stored,
'sha256' => hash_file('sha256', Storage::disk('local')->path($stored)), 'status' => 'quarantined', 'size_bytes' => $file->getSize(), 'uploaded_by' => $request->user()->id]);
DB::table('partnership_documents')->insert(['room_id' => $id, 'document_id' => $documentId, 'owner_id' => $request->user()->id, 'shared' => $data['shared']]);
app(PartnershipExchange::class)->event($context['partnership'], $request->user(), 'partnership.document_added.v1', ['room_id' => $id, 'document_id' => $documentId, 'shared' => $data['shared']], 'Documento privado anexado');
});
} catch (\Throwable $e) {
Storage::disk('local')->delete($stored);
throw $e;
}
ScanDocumentForMalware::dispatch($documentId)->afterCommit();
return $request->expectsJson() ? response()->json(['uploaded' => true]) : back()->with('success', 'Documento privado guardado; análise antimalware pendente.'); return $request->expectsJson() ? response()->json($result) : back()->with('success', 'Envio reconciliado com o documento privado. Consulte o estado da análise na lista.')->with('uploaded_document_id', $result['document_id']);
} }
public function download(Request $request, int $id, int $attachment): \Illuminate\Http\Response|BinaryFileResponse public function download(Request $request, int $id, int $attachment): \Illuminate\Http\Response|BinaryFileResponse
@@ -367,7 +361,7 @@ class PartnershipExchangeController extends Controller
public function notification(Request $request, int $id): RedirectResponse public function notification(Request $request, int $id): RedirectResponse
{ {
abort_unless(DB::table('partnership_notifications')->where('id', $id)->where('user_id', $request->user()->id)->update(['read_at' => now()]) > 0, 404); app(PartnershipNotifications::class)->markRead($request->user(), $id);
return back(); return back();
} }
@@ -0,0 +1,265 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Services\ContentManagement;
use App\Services\DocumentManagementAccess;
use App\Services\PortalEditorialNativeNotices;
use App\Services\PortalEditorialSubjects;
use App\Services\PortalEditorialWorkflow;
use App\Services\PortalProfileAccess;
use App\Services\TerritorialRegistry;
use App\Services\VerifiedDocumentBinary;
use App\Support\CheckedFile;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class PortalEditorialWorkflowController extends Controller
{
public function subjects(Request $request, PortalEditorialWorkflow $workflow): Response
{
$adapter = app(PortalEditorialSubjects::class);
abort_unless($adapter->available() && $request->user()->can('manage-portal') && ! app(PortalProfileAccess::class)->has($request->user(), 'auditor'), 403);
$items = $workflow->subjectQueue()->orderByDesc('e.updated_at')->paginate(25, ['e.id', 'e.subject_kind', 'e.subject_key', 'e.revision_no', 'e.state', DB::raw("e.payload->'resource'->>'title' AS title")]);
return $this->screen($request, 'management/editorial-subjects', ['items' => $items]);
}
public function subject(Request $request, string $kind, string $id, PortalEditorialWorkflow $workflow): Response
{
$adapter = app(PortalEditorialSubjects::class);
$adapter->authorize($request->user(), $kind, $id);
$record = $adapter->query($kind, $id)->firstOrFail();
$selected = $request->validate(['edition' => 'nullable|uuid'])['edition'] ?? null;
$latest = $workflow->latestSubject($kind, $id);
$editions = DB::table('portal_editorial_editions')->where('subject_kind', $kind)->where('subject_key', $id);
$edition = $selected ? (clone $editions)->where('id', $selected)->first() : $latest;
abort_if($selected && ! $edition, 404);
$payload = $edition ? $workflow->payload($edition) : null;
$independent = $edition ? $workflow->requiresIndependent($edition) : $adapter->independent($kind);
$canApprove = ! $independent || ! in_array($request->user()->id, $payload['contributors'] ?? [], true);
return $this->screen($request, 'management/editorial-edition', ['subject' => 'structural', 'subjectKind' => $kind, 'editUrl' => $adapter->editUrl($kind, $record), 'subjectFields' => $adapter->form($kind), 'subjectInitial' => Arr::only(get_object_vars($record), $adapter->definition($kind)['fields']),
'resource' => ['id' => $id, 'title' => $record->name ?? $record->title ?? $kind, 'published' => ($record->deleted_at ?? null) === null && ($record->validation_status ?? null) !== 'revoked' && (clone $editions)->where('state', 'published')->exists(), 'public_edition_no' => (clone $editions)->where('state', 'published')->max('revision_no')],
'edition' => $edition ? [...get_object_vars($edition), 'payload' => $payload, 'fresh' => $edition->state === 'published' || $workflow->fresh($edition)] : null,
'current' => $edition && $edition->id === $latest?->id, 'independentRequired' => $independent, 'canApprove' => $canApprove, 'manager' => true, 'legalReviewer' => false,
'reviewers' => User::whereIn('email', config('portal.managers', []))->whereNotNull('email_verified_at')->get(['id', 'name']),
'history' => DB::table('audit_events')->where('source_system', 'document-access-v1')->where('action', 'like', 'editorial_%')->where('after_data->subject_kind', $kind)->where('after_data->subject_key', $id)->orderByDesc('id')->get(['id', 'action', 'actor_user_id', 'after_data', 'occurred_at']),
'editions' => $editions->orderByDesc('revision_no')->get(['id', 'revision_no', 'state', 'content_hash', 'author_id', 'created_at'])]);
}
public function subjectTransition(Request $request, string $kind, string $id, string $edition, PortalEditorialWorkflow $workflow): Response
{
$result = $workflow->transition($request->user(), $id, $edition, $request->all(), false, false, $kind);
return $request->expectsJson() ? response()->json(['edition' => $result])->header('Cache-Control', 'private, no-store') : back()->with('success', 'Operação editorial registada.');
}
public function subjectSave(Request $request, string $kind, string $id, PortalEditorialWorkflow $workflow): Response
{
$adapter = app(PortalEditorialSubjects::class);
$adapter->authorize($request->user(), $kind, $id, true);
$data = $request->validate(['expected_revision' => 'required|integer|min:1', 'fields' => 'required|array', 'withdraw' => 'sometimes|boolean']);
$edition = $workflow->saveSubject($request->user(), $kind, $id, (int) $data['expected_revision'], $adapter->validate($kind, $data['fields']), false, $data['withdraw'] ?? null);
return $request->expectsJson() ? response()->json(['edition' => $edition], 201)->header('Cache-Control', 'private, no-store') : redirect('/management/editorial/subjects/'.$kind.'/'.$id)->with('success', 'Proposta privada guardada.');
}
public function subjectChoices(Request $request, string $kind, string $id): Response
{
$adapter = app(PortalEditorialSubjects::class);
$adapter->authorize($request->user(), $kind, $id);
$data = $request->validate(['field' => 'required|string|max:80', 'q' => 'nullable|string|max:100']);
return response()->json(['data' => $adapter->choices($kind, $data['field'], $data['q'] ?? null), 'limit' => 100])->header('Cache-Control', 'private, no-store');
}
private const KIND = "CASE WHEN e.payload->'resource'->>'legislation' = 'true' OR e.payload->'resource'->>'document_type' = 'legislation' THEN 'legislation' WHEN e.payload->'resource'->>'editorial_content' IS NOT NULL THEN 'article' ELSE 'document' END";
/** @param array<string,mixed> $data */
private function screen(Request $request, string $component, array $data): Response
{
$response = $request->expectsJson() ? response()->json($data) : Inertia::render($component, $data)->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store');
return $response;
}
public function index(Request $request, PortalEditorialWorkflow $workflow): Response
{
abort_unless($workflow->enabled(), 503);
$actor = $request->user();
$access = app(DocumentManagementAccess::class);
$query = $workflow->queue($actor);
$filters = array_filter($request->validate(['state' => 'nullable|in:draft,submitted,in_review,approved,published,returned,rejected,archived', 'kind' => 'nullable|in:article,legislation,document']), fn ($value) => $value !== null && $value !== '');
if (isset($filters['state'])) {
$query->where('e.state', $filters['state']);
}
if (isset($filters['kind'])) {
$query->whereRaw(self::KIND.' = ?', [$filters['kind']]);
}
$items = $query->orderByDesc('e.updated_at')->paginate(25, ['r.id', DB::raw("e.payload->'resource'->>'title' AS title"), 'r.document_type', 'r.published', 'e.id as edition_id', 'e.revision_no', 'e.state', 'e.legal_required', 'u.name as responsible'])->withQueryString();
$destinations = app(ContentManagement::class)->access($actor);
$data = ['items' => $items, 'filters' => $filters, 'notices' => $workflow->notices($actor), 'resourceAccess' => $access->full($actor) || $access->editorial($actor), 'opportunitiesUrl' => $destinations['opportunities']['index'] ?? null,
'offersUrl' => isset($destinations['opportunities']['index']) && app(PortalProfileAccess::class)->available() ? '/minhas-oportunidades/ofertas' : null,
'offerOperationsUrl' => ! app(PortalProfileAccess::class)->has($actor, 'auditor') && (app(PortalProfileAccess::class)->has($actor, 'validator') || app(PortalProfileAccess::class)->has($actor, 'publisher')) ? '/minhas-oportunidades/ofertas?operational=1' : null,
'opportunityPending' => $workflow->opportunityPending($actor), 'clustersUrl' => $destinations['clusters']['index'] ?? null,
'portfolioUrl' => $destinations['portfolio']['index'] ?? null, 'portfolioPending' => $workflow->portfolioPending($actor), 'demographyUrl' => $destinations['demography']['index'] ?? null, 'demographyPending' => $workflow->demographyPending($actor),
'territorialUrl' => app(TerritorialRegistry::class)->editorialAvailable() && $actor->can('manage-portal') ? '/management/territorial/editorial' : null,
'nativePending' => app(PortalEditorialNativeNotices::class)->pending($actor), 'zonesUrl' => app(PortalEditorialNativeNotices::class)->access($actor, 'investment-zones') ? '/management/investment/zones' : null,
'subjectsUrl' => app(PortalEditorialSubjects::class)->available() && $actor->can('manage-portal') ? '/management/editorial/subjects' : null, 'subjectsPending' => $workflow->subjectPending($actor)];
return $this->screen($request, 'management/editorial-workflow', $data);
}
public function show(Request $request, int $id, PortalEditorialWorkflow $workflow): Response
{
$workflow->authorize($request->user(), $id);
$resource = DB::table('portal_resources')->where('id', $id)->first();
abort_unless($resource !== null, 404);
$selected = $request->validate(['edition' => 'nullable|uuid'])['edition'] ?? null;
$latest = $workflow->latest($id);
$e = $selected ? DB::table('portal_editorial_editions')->where('resource_id', $id)->where('id', $selected)->first() : $latest;
abort_if($selected && ! $e, 404);
$payload = $e ? $workflow->payload($e) : null;
$independent = ! $e || ! $workflow->requiresIndependent($e) || ! in_array($request->user()->id, $payload['contributors'], true);
$data = ['resource' => ['id' => $id, 'title' => $resource->title, 'published' => (bool) $resource->published, 'public_edition_no' => $resource->published ? DB::table('portal_editorial_editions')->where('resource_id', $id)->where('state', 'published')->max('revision_no') : null], 'edition' => $e ? [...(array) $e, 'payload' => $payload, 'fresh' => $e->state === 'published' || $workflow->fresh($e)] : null,
'current' => $e && $e->id === $latest?->id,
'independentRequired' => $e ? $workflow->requiresIndependent($e) : false,
'canApprove' => $independent && app(DocumentManagementAccess::class)->full($request->user()),
'manager' => app(DocumentManagementAccess::class)->full($request->user()),
'reviewers' => User::whereIn('email', config('portal.managers', []))->whereNotNull('email_verified_at')->get(['id', 'name']),
'legalReviewer' => $workflow->legalReviewer($request->user()),
'history' => DB::table('audit_events')->where('source_system', 'document-access-v1')->where('action', 'like', 'editorial_%')->where('after_data->resource_id', $id)->orderByDesc('id')->get(['id', 'action', 'actor_user_id', 'after_data', 'occurred_at']),
'editions' => DB::table('portal_editorial_editions')->where('resource_id', $id)->orderByDesc('revision_no')->get(['id', 'revision_no', 'state', 'content_hash', 'author_id', 'created_at'])];
return $this->screen($request, 'management/editorial-edition', $data);
}
public function transition(Request $request, int $id, string $edition, PortalEditorialWorkflow $workflow): Response
{
$result = $workflow->transition($request->user(), $id, $edition, $request->all());
return $request->expectsJson() ? response()->json(['edition' => $result])->header('Cache-Control', 'private, no-store') : back()->with('success', 'Operação editorial registada.');
}
public function portfolio(Request $request, string $id, PortalEditorialWorkflow $workflow): Response
{
$workflow->authorizePortfolio($request->user(), $id);
$record = DB::table('investment_dossiers')->where('id', $id)->first();
abort_unless($record !== null, 404);
$selected = $request->validate(['edition' => 'nullable|uuid'])['edition'] ?? null;
$latest = $workflow->latestPortfolio($id);
$edition = $selected ? DB::table('portal_editorial_editions')->where('dossier_id', $id)->where('id', $selected)->first() : $latest;
abort_if($selected && ! $edition, 404);
$payload = $edition ? $workflow->payload($edition) : null;
$independent = ! $edition || ! in_array($request->user()->id, $payload['contributors'], true);
return $this->screen($request, 'management/editorial-edition', ['subject' => 'portfolio',
'resource' => ['id' => $id, 'title' => $record->title, 'published' => $record->publication_status === 'published', 'public_edition_no' => $record->publication_status === 'published' ? DB::table('portal_editorial_editions')->where('dossier_id', $id)->where('state', 'published')->max('revision_no') : null],
'edition' => $edition ? [...get_object_vars($edition), 'payload' => $payload, 'fresh' => $edition->state === 'published' || $workflow->fresh($edition)] : null,
'current' => $edition && $edition->id === $latest?->id, 'independentRequired' => true, 'canApprove' => $independent, 'manager' => true, 'legalReviewer' => false,
'reviewers' => User::whereIn('email', config('portal.managers', []))->whereNotNull('email_verified_at')->get(['id', 'name']),
'history' => DB::table('audit_events')->where('source_system', 'document-access-v1')->where('action', 'like', 'editorial_%')->where('after_data->dossier_id', $id)->orderByDesc('id')->get(['id', 'action', 'actor_user_id', 'after_data', 'occurred_at']),
'editions' => DB::table('portal_editorial_editions')->where('dossier_id', $id)->orderByDesc('revision_no')->get(['id', 'revision_no', 'state', 'content_hash', 'author_id', 'created_at'])]);
}
public function portfolioTransition(Request $request, string $id, string $edition, PortalEditorialWorkflow $workflow): Response
{
$result = $workflow->transition($request->user(), $id, $edition, $request->all(), true);
return $request->expectsJson() ? response()->json(['edition' => $result])->header('Cache-Control', 'private, no-store') : back()->with('success', 'Operação editorial da carteira registada.');
}
public function demography(Request $request, string $id, PortalEditorialWorkflow $workflow): Response
{
$workflow->authorizeDemography($request->user(), $id);
$batch = DB::table('demographic_imports')->where('id', $id)->first();
abort_unless($batch !== null, 404);
$selected = $request->validate(['edition' => 'nullable|uuid'])['edition'] ?? null;
$latest = $workflow->latestDemography($id);
$edition = $selected ? DB::table('portal_editorial_editions')->where('demographic_import_id', $id)->where('id', $selected)->first() : $latest;
abort_if($selected && ! $edition, 404);
$payload = $edition ? $workflow->payload($edition) : null;
$independent = ! $edition || ! $workflow->requiresIndependent($edition) || ! in_array($request->user()->id, $payload['contributors'], true);
return $this->screen($request, 'management/editorial-edition', ['subject' => 'demography',
'resource' => ['id' => $id, 'title' => $batch->file_name, 'published' => $batch->status === 'approved', 'public_edition_no' => $batch->status === 'approved' ? DB::table('portal_editorial_editions')->where('demographic_import_id', $id)->where('state', 'published')->max('revision_no') : null],
'edition' => $edition ? [...get_object_vars($edition), 'payload' => $payload, 'fresh' => $edition->state === 'published' || $workflow->fresh($edition)] : null,
'current' => $edition && $edition->id === $latest?->id, 'independentRequired' => $edition ? $workflow->requiresIndependent($edition) : false, 'canApprove' => $independent, 'manager' => true, 'legalReviewer' => false,
'reviewers' => User::whereIn('email', config('portal.managers', []))->whereNotNull('email_verified_at')->get(['id', 'name']),
'history' => DB::table('audit_events')->where('source_system', 'document-access-v1')->where('action', 'like', 'editorial_%')->where('after_data->demographic_import_id', $id)->orderByDesc('id')->get(['id', 'action', 'actor_user_id', 'after_data', 'occurred_at']),
'editions' => DB::table('portal_editorial_editions')->where('demographic_import_id', $id)->orderByDesc('revision_no')->get(['id', 'revision_no', 'state', 'content_hash', 'author_id', 'created_at'])]);
}
public function demographyDraft(Request $request, string $id, PortalEditorialWorkflow $workflow): Response
{
$data = $request->validate(['expected_revision' => 'required|integer|min:0']);
$edition = $workflow->saveDemography($request->user(), $id, (int) $data['expected_revision']);
return $request->expectsJson() ? response()->json(['edition' => $edition], 201)->header('Cache-Control', 'private, no-store') : redirect('/management/editorial/demography/'.$id);
}
public function demographyTransition(Request $request, string $id, string $edition, PortalEditorialWorkflow $workflow): Response
{
$result = $workflow->transition($request->user(), $id, $edition, $request->all(), false, true);
return $request->expectsJson() ? response()->json(['edition' => $result])->header('Cache-Control', 'private, no-store') : back()->with('success', 'Operação editorial do lote registada.');
}
public function demographyOriginal(Request $request, string $id, PortalEditorialWorkflow $workflow): Response
{
$workflow->authorizeDemography($request->user(), $id);
$batch = DB::table('demographic_imports')->where('id', $id)->first();
abort_unless($batch !== null, 404);
$path = Storage::disk('local')->path('demography/'.$id.'/original.xlsx');
abort_unless(CheckedFile::matches($path, trim($batch->sha256)), 409, 'Original indisponível ou alterado.');
return response()->download($path, basename($batch->file_name), ['Cache-Control' => 'private, no-store', 'X-Robots-Tag' => 'noindex, nofollow']);
}
public function file(Request $request, int $id, string $edition, string $document, PortalEditorialWorkflow $workflow): Response
{
$workflow->authorize($request->user(), $id);
$e = DB::table('portal_editorial_editions')->where('id', $edition)->where('resource_id', $id)->first();
abort_unless($e !== null, 404);
$file = null;
foreach ($workflow->payload($e)['files'] as $entry) {
if ($entry['id'] === $document) {
$file = $entry;
break;
}
}
abort_unless($file !== null, 404);
abort_unless($workflow->canReadFile($request->user(), $document), 403);
$record = DB::table('documents')->where('id', $document)->first();
abort_unless($record && hash_equals(trim($file['sha256']), trim($record->sha256)) && (int) $file['version_no'] === (int) $record->version_no, 409, 'O anexo mudou; esta edição conserva a referência anterior.');
return $this->binary($record);
}
private function binary(\stdClass $record): Response
{
$response = app(VerifiedDocumentBinary::class)->respond($record);
$response->headers->set('Cache-Control', 'private, no-store');
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
public function markRead(Request $request, int $notice, PortalEditorialWorkflow $workflow): Response
{
abort_unless($workflow->enabled(), 503);
$n = DB::table('portal_editorial_notifications')->where('id', $notice)->where('user_id', $request->user()->id)->first();
abort_unless($n !== null, 404);
abort_unless($workflow->visibleNotice($request->user(), $n), 404);
DB::table('portal_editorial_notifications')->where('id', $notice)->where('user_id', $request->user()->id)->whereNull('read_at')->update(['read_at' => now()]);
return $request->expectsJson() ? response()->json(['read' => true]) : back();
}
}
@@ -2,12 +2,14 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Exceptions\OpportunityWorkflowUnavailable;
use App\Models\Opportunity; use App\Models\Opportunity;
use App\Models\User; 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;
use App\Services\OpportunityProfileWorkflow; use App\Services\OpportunityTechnicalSupport;
use App\Services\OpportunityWorkflowExecution;
use App\Services\PortalInternalDesignation; use App\Services\PortalInternalDesignation;
use App\Services\PortalProfileAccess; use App\Services\PortalProfileAccess;
use App\Services\PortalProfileAdministration; use App\Services\PortalProfileAdministration;
@@ -49,13 +51,15 @@ class PortalProfileController extends Controller
{ {
$service->administrative($request->user()); $service->administrative($request->user());
return Inertia::render('profiles/administration', ['requests' => DB::table('portal_profile_requests')->latest()->get(), return Inertia::render('profiles/administration', ['technicalSupportAvailable' => app(OpportunityTechnicalSupport::class)->installed(), '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) => [ 'staffAccounts' => User::query()->select(['id', 'name', 'email', 'email_verified_at'])
'id' => $user->id, 'name' => $user->name, 'email' => $user->email, ->selectRaw('CASE WHEN two_factor_secret IS NOT NULL AND two_factor_confirmed_at IS NOT NULL THEN 1 ELSE 0 END AS mfa_enrolled')
'verified' => $user->email_verified_at !== null, 'mfa' => $user->two_factor_confirmed_at !== null, ->withCasts(['mfa_enrolled' => 'boolean'])->orderBy('name')->get()->map(fn (User $user) => [
]), 'id' => $user->id, 'name' => $user->name, 'email' => $user->email,
'verified' => $user->email_verified_at !== null, 'mfa' => $user->getAttribute('mfa_enrolled'),
]),
'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']),
@@ -148,9 +152,14 @@ class PortalProfileController extends Controller
return app(OpportunityManagementController::class)->edit($request, app(OpportunityManagement::class), $id); return app(OpportunityManagementController::class)->edit($request, app(OpportunityManagement::class), $id);
} }
public function workflow(Request $request, int $id, OpportunityProfileWorkflow $service): JsonResponse public function workflow(Request $request, int $id, OpportunityWorkflowExecution $service): JsonResponse
{ {
$record = $service->transition($request->user(), $id, $request->all()); try {
$record = $service->transition($request->user(), $id, $request->all());
} catch (OpportunityWorkflowUnavailable $failure) {
return response()->json(['message' => 'Não foi possível confirmar o resultado. Consulte o estado da oportunidade antes de repetir. '.($failure->recorded ? 'Incidente técnico registado. ' : 'Não foi possível guardar o incidente; conserve esta referência. ').'Referência: '.$failure->reference,
'reference' => $failure->reference, 'incident_recorded' => $failure->recorded], 503)->header('Cache-Control', 'private, no-store');
}
return response()->json(['id' => $id, 'status' => app(PortalProfileAccess::class)->state($record), 'publication_status' => $record->status, 'etag' => app(OpportunityManagement::class)->etag($record), 'message' => 'Ação interna registada; não representa decisão externa.']); return response()->json(['id' => $id, 'status' => app(PortalProfileAccess::class)->state($record), 'publication_status' => $record->status, 'etag' => app(OpportunityManagement::class)->etag($record), 'message' => 'Ação interna registada; não representa decisão externa.']);
} }
@@ -7,6 +7,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
class PortalProfileInstallationController extends Controller class PortalProfileInstallationController extends Controller
{ {
@@ -22,6 +23,19 @@ class PortalProfileInstallationController extends Controller
return response()->json($installation->apply($request->user(), $request->all())); return response()->json($installation->apply($request->user(), $request->all()));
} }
public function supportPreview(Request $request, PortalProfileInstallation $installation): HttpResponse
{
$plan = $installation->supportPreview($request->user());
Inertia::encryptHistory();
return tap($request->expectsJson() ? response()->json($plan) : Inertia::render('profiles/support-installation', $plan)->toResponse($request), static fn (HttpResponse $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function applySupport(Request $request, PortalProfileInstallation $installation): JsonResponse
{
return response()->json($installation->applySupport($request->user(), $request->all()))->header('Cache-Control', 'private, no-store');
}
public function bootstrap(Request $request, PortalProfileInstallation $installation): JsonResponse public function bootstrap(Request $request, PortalProfileInstallation $installation): JsonResponse
{ {
return response()->json($installation->bootstrap($request->user(), $request->all())); return response()->json($installation->bootstrap($request->user(), $request->all()));
@@ -15,8 +15,10 @@ use App\Services\InterestSubmission;
use App\Services\InvestmentGeography; 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\PortalEditorialWorkflow;
use App\Services\PortalProfileAccess; use App\Services\PortalProfileAccess;
use App\Services\PublicDocumentPresentation; use App\Services\PublicDocumentPresentation;
use App\Services\PublicSearchMetrics;
use App\Services\SectorOrganization; use App\Services\SectorOrganization;
use App\Services\VerifiedDocumentBinary; use App\Services\VerifiedDocumentBinary;
use App\Services\VirtualDesk; use App\Services\VirtualDesk;
@@ -118,15 +120,16 @@ class PortalServicesController extends Controller
->orWhere('r.source_reference', 'ilike', $term)->orWhere('r.category', 'ilike', $term)->orWhere('r.topic', 'ilike', $term)); ->orWhere('r.source_reference', 'ilike', $term)->orWhere('r.category', 'ilike', $term)->orWhere('r.topic', 'ilike', $term));
} }
$pageResult = $query->orderByRaw("CASE WHEN r.document_type IN ('official_form','digital_adaptation','guidance_template') THEN 1 ELSE 0 END") $pageResult = $query->orderByRaw("CASE WHEN r.document_type IN ('official_form','digital_adaptation','guidance_template') THEN 1 ELSE 0 END")
->orderByDesc('r.essential')->orderBy('r.title')->select([ ->orderByDesc('r.essential')->orderBy('r.title')->orderBy('r.id')->select([
'r.id', 'r.document_id', 'r.title', 'r.description', 'r.category', 'r.topic', 'r.document_type', 'r.document_number', 'r.document_date', 'r.id', 'r.document_id', 'r.title', 'r.description', 'r.category', 'r.topic', 'r.document_type', 'r.document_number', 'r.document_date',
'r.applicable_from', 'r.applicable_until', 'r.applicable_from', 'r.applicable_until',
'r.source_url', 'r.language', 'r.version_label', 'r.document_group_id', 'r.territorial_scope', 'r.territory_id', 'r.source_url', 'r.language', 'r.version_label', 'r.document_group_id', 'r.territorial_scope', 'r.territory_id',
'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(3)->withQueryString();
$pageResult->getCollection()->transform(fn ($resource) => app(PublicDocumentPresentation::class)->resource($resource)); $pageResult->getCollection()->transform(fn ($resource) => app(PublicDocumentPresentation::class)->resource($resource));
$props['resources'] = $pageResult; $props['resources'] = $pageResult;
app(PublicSearchMetrics::class)->candidate($request, 'documents', $pageResult->total(), $filters);
$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');
$props['issuers'] = (clone $this->resources())->whereNotNull('d.issuer')->distinct()->orderBy('d.issuer')->pluck('d.issuer'); $props['issuers'] = (clone $this->resources())->whereNotNull('d.issuer')->distinct()->orderBy('d.issuer')->pluck('d.issuer');
@@ -153,6 +156,7 @@ class PortalServicesController extends Controller
$query->where('title', 'ilike', '%'.$filters['q'].'%'); $query->where('title', 'ilike', '%'.$filters['q'].'%');
} }
$props['partnerships'] = $query->orderByDesc('id')->select(['id', 'title', 'sector', 'province', 'offer', 'seeking'])->paginate(20)->withQueryString(); $props['partnerships'] = $query->orderByDesc('id')->select(['id', 'title', 'sector', 'province', 'offer', 'seeking'])->paginate(20)->withQueryString();
app(PublicSearchMetrics::class)->candidate($request, 'partnerships', $props['partnerships']->total(), $filters);
} }
if ($page === 'desk') { if ($page === 'desk') {
if (app(VirtualDesk::class)->installed()) { if (app(VirtualDesk::class)->installed()) {
@@ -317,6 +321,9 @@ class PortalServicesController extends Controller
$editorial = $access->editorial($request->user()); $editorial = $access->editorial($request->user());
$resources = $editorial ? $this->filterManagedResources($access->editorialResources($request->user()), $managementFilters)->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();
if (app(PortalEditorialWorkflow::class)->enabled()) {
$resources = $resources->map(fn ($r) => app(PortalEditorialWorkflow::class)->workingResource($r));
}
$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');
$resources->each(function ($resource) use ($links, $revisions) { $resources->each(function ($resource) use ($links, $revisions) {
@@ -325,7 +332,7 @@ class PortalServicesController extends Controller
}); });
return Inertia::render('portal/manage', [ return Inertia::render('portal/manage', [
'managementFilters' => $managementFilters, 'associationOptions' => $this->contentAssociations($request), 'editorialWorkflowEnabled' => app(PortalEditorialWorkflow::class)->enabled(), '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(),
@@ -350,12 +357,15 @@ class PortalServicesController extends Controller
$resources->each(fn ($resource) => $resource->links = $links->get($resource->id, collect())->values()); $resources->each(fn ($resource) => $resource->links = $links->get($resource->id, collect())->values());
$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');
$resources->each(fn ($resource) => $resource->revisions = $revisions->get($resource->id, collect())->values()); $resources->each(fn ($resource) => $resource->revisions = $revisions->get($resource->id, collect())->values());
if (app(PortalEditorialWorkflow::class)->enabled()) {
$resources = $resources->map(fn ($r) => app(PortalEditorialWorkflow::class)->workingResource($r));
}
$malwareHealth = $scanner->health(); $malwareHealth = $scanner->health();
$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), 'editorialWorkflowEnabled' => app(PortalEditorialWorkflow::class)->enabled(), '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(),
@@ -471,9 +481,15 @@ class PortalServicesController extends Controller
$duplicate = $identity ? DB::table('portal_resources')->where('document_identity_key', $identity)->value('id') : null; $duplicate = $identity ? DB::table('portal_resources')->where('document_identity_key', $identity)->value('id') : null;
$fields = $this->resourceFields($data, $request->user()->id, $identity, $duplicate, true); $fields = $this->resourceFields($data, $request->user()->id, $identity, $duplicate, true);
$this->assertPublicClassificationEligible($data, $document); $this->assertPublicClassificationEligible($data, $document);
$workflow = app(PortalEditorialWorkflow::class);
$id = DB::table('portal_resources')->insertGetId([...$fields, 'approved_by' => null, 'published' => false, 'created_at' => now(), 'updated_at' => now()]); $id = DB::table('portal_resources')->insertGetId([...$fields, 'approved_by' => null, 'published' => false, 'created_at' => now(), 'updated_at' => now()]);
$this->syncResourceLinks($id, $data['associations'] ?? []); $this->syncResourceLinks($id, $data['associations'] ?? []);
$this->recordResourceRevision($id, 'created', $request->user()->id, 1); $this->recordResourceRevision($id, 'created', $request->user()->id, 1);
if ($workflow->enabled()) {
$workflow->save($request->user(), $id, 1, ['_document' => ['issuer' => ($data['issuer'] ?? null) ?: $document->issuer, 'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'], 'data_classification' => $data['data_classification'] ?? $document->data_classification]]);
return $id;
}
DB::table('documents')->where('id', $document->id)->update(['issuer' => ($data['issuer'] ?? null) ?: $document->issuer, DB::table('documents')->where('id', $document->id)->update(['issuer' => ($data['issuer'] ?? null) ?: $document->issuer,
'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'], 'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'],
'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]); 'data_classification' => $data['data_classification'] ?? $document->data_classification, 'updated_at' => now()]);
@@ -493,7 +509,9 @@ class PortalServicesController extends Controller
$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(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.'); $workflow = app(PortalEditorialWorkflow::class);
$current = $workflow->enabled() ? $workflow->workingResource($resource) : $resource;
abort_if((int) $current->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(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);
@@ -504,6 +522,12 @@ class PortalServicesController extends Controller
$duplicate = $identity ? DB::table('portal_resources')->where('document_identity_key', $identity)->where('id', '!=', $id)->value('id') : null; $duplicate = $identity ? DB::table('portal_resources')->where('document_identity_key', $identity)->where('id', '!=', $id)->value('id') : null;
$fields = $this->resourceFields($data, $request->user()->id, $identity, $duplicate, false); $fields = $this->resourceFields($data, $request->user()->id, $identity, $duplicate, false);
$this->assertPublicClassificationEligible($data, $document); $this->assertPublicClassificationEligible($data, $document);
$workflow = app(PortalEditorialWorkflow::class);
if ($workflow->enabled()) {
$workflow->save($request->user(), $id, $expectedVersion, [...$fields, '_document' => ['issuer' => ($data['issuer'] ?? null) ?: $document->issuer, 'issued_on' => ($data['document_date'] ?? null) ?: $document->issued_on, 'rights_status' => $data['rights_status'], 'data_classification' => $data['data_classification'] ?? $document->data_classification]], $data['associations'] ?? []);
return;
}
$retainPublication = (bool) $resource->published && $data['rights_status'] === 'authorized' $retainPublication = (bool) $resource->published && $data['rights_status'] === 'authorized'
&& $data['source_confirmation'] !== 'unconfirmed' && ! empty($data['source_url']) && $data['source_confirmation'] !== 'unconfirmed' && ! empty($data['source_url'])
&& (! ($data['legislation'] || $data['document_type'] === 'legislation') || $data['source_confirmation'] === 'official_confirmed') && (! ($data['legislation'] || $data['document_type'] === 'legislation') || $data['source_confirmation'] === 'official_confirmed')
@@ -520,7 +544,7 @@ class PortalServicesController extends Controller
$this->audit($request, 'resource_metadata_updated', 'portal_resources', $id); $this->audit($request, 'resource_metadata_updated', 'portal_resources', $id);
}); });
return to_route('services.manage')->with('success', 'Metadados e relações actualizados; o estado de publicação foi preservado.'); return to_route('services.manage')->with('success', 'Edição guardada; confira o circuito editorial quando estiver activo. A versão pública é preservada nesse circuito.');
} }
public function moderate(Request $request, string $type, int $id): RedirectResponse public function moderate(Request $request, string $type, int $id): RedirectResponse
@@ -534,6 +558,12 @@ class PortalServicesController extends Controller
return redirect('/parcerias/'.$id)->with('success', 'Reveja a proposta e registe uma decisão fundamentada na ficha da Bolsa.'); return redirect('/parcerias/'.$id)->with('success', 'Reveja a proposta e registe uma decisão fundamentada na ficha da Bolsa.');
} }
$data = $this->validateManagement($request, ['published' => ['required', 'boolean']]); $data = $this->validateManagement($request, ['published' => ['required', 'boolean']]);
if ($type === 'resources' && app(PortalEditorialWorkflow::class)->enabled()) {
app(PortalEditorialWorkflow::class)->authorize($request->user(), $id, true);
}
if ($type === 'resources' && $data['published'] && app(PortalEditorialWorkflow::class)->enabled()) {
abort(409, 'Use a aprovação e publicação explícitas da edição no circuito editorial.');
}
$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);
@@ -579,6 +609,7 @@ class PortalServicesController extends Controller
public function applyDocumentDisclosureAuthorization(Request $request): RedirectResponse public function applyDocumentDisclosureAuthorization(Request $request): RedirectResponse
{ {
abort_if(app(PortalEditorialWorkflow::class)->enabled(), 409, 'A divulgação de novas edições requer aprovação e publicação no circuito editorial.');
$event = DB::table('audit_events')->where('source_system', 'user-instruction') $event = DB::table('audit_events')->where('source_system', 'user-instruction')
->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(); ->where('action', 'public_disclosure_authorized')->first();
@@ -0,0 +1,51 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\PrivateOfferOperations;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class PrivateOfferOperationsController extends Controller
{
public function show(Request $request, int $id, PrivateOfferOperations $operations): Response
{
return response()->json($operations->presentation($request->user(), $id));
}
public function owner(Request $request, int $id, PrivateOfferOperations $operations): Response
{
$operations->ownerAction($request->user(), $id, $request->all());
return response()->json($operations->presentation($request->user(), $id));
}
public function reportPage(Request $request, int $id, PrivateOfferOperations $operations): Response
{
$record = Opportunity::findOrFail($id);
abort_unless($record->isPrivateOfferPreparation() && $operations->canReport($request->user(), $record), 404);
return Inertia::render('offers/report', ['offerId' => $id])->toResponse($request);
}
public function report(Request $request, int $id, PrivateOfferOperations $operations): Response
{
return response()->json($operations->report($request->user(), $id, $request->all()), 201);
}
public function handleReport(Request $request, int $id, string $reportId, PrivateOfferOperations $operations): Response
{
$operations->handleReport($request->user(), $id, $reportId, $request->all());
return response()->json($operations->presentation($request->user(), $id));
}
public function highlight(Request $request, int $id, PrivateOfferOperations $operations): Response
{
$operations->highlight($request->user(), $id, $request->all());
return response()->json($operations->presentation($request->user(), $id));
}
}
@@ -0,0 +1,153 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Services\OfferAvailability;
use App\Services\OpportunityCanonicalContract;
use App\Services\OpportunityManagement;
use App\Services\OpportunityProfileWorkflow;
use App\Services\OpportunityResources;
use App\Services\PortalProfileAccess;
use App\Services\PrivateOfferConfidentiality;
use App\Services\PrivateOfferOperations;
use App\Services\PrivateOfferPreparation;
use App\Services\VerifiedDocumentBinary;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
final class PrivateOfferPreparationController extends Controller
{
public function resources(Request $request, PrivateOfferPreparation $service, int $id): JsonResponse
{
$record = $service->record($request->user(), $id);
$resources = [];
foreach (['images', 'documents'] as $kind) {
$resources[$kind] = array_map(fn ($row) => ['id' => $row->id, 'version' => $row->version, 'deleted' => $row->deleted_at !== null,
'caption' => $row->payload['caption'] ?? null, 'digitally_edited' => $row->payload['digitally_edited'] ?? null,
'edit_description' => $row->payload['edit_description'] ?? null,
'scan' => $row->file->malware_scan_status ?? 'pending'], app(OpportunityResources::class)->listing($id, $kind));
}
return response()->json(['resources' => $resources, 'etag' => app(OpportunityManagement::class)->etag($record),
'internalProofAccess' => app(PrivateOfferConfidentiality::class)->internal($request->user(), $record)]);
}
public function attachment(Request $request, PrivateOfferPreparation $service, int $id, string $kind, string $resourceId): \Symfony\Component\HttpFoundation\Response
{
$record = $service->record($request->user(), $id);
abort_unless(in_array($kind, ['documents', 'images'], true), 404);
$link = DB::table('opportunity_'.$kind)->where('opportunity_id', $id)->where('id', $resourceId)->whereNull('deleted_at')->first();
abort_unless($link !== null, 404);
$document = DB::table('documents')->where('id', $link->document_id)->whereNull('deleted_at')->first();
abort_unless($document !== null, 404);
return app(VerifiedDocumentBinary::class)->respond($document);
}
public function confidentiality(Request $request, PrivateOfferConfidentiality $privacy, int $id): JsonResponse|Response
{
$overview = $privacy->overview($request->user(), $id);
return $request->expectsJson() ? response()->json($overview) : Inertia::render('offers/confidentiality', ['offerId' => $id]);
}
public function confidentialityAction(Request $request, PrivateOfferConfidentiality $privacy, int $id): JsonResponse
{
return response()->json($privacy->act($request->user(), $id, $request->all()));
}
public function confidentialRead(Request $request, PrivateOfferConfidentiality $privacy, int $id): JsonResponse
{
try {
$result = $privacy->read($request->user(), $id);
} catch (HttpExceptionInterface $error) {
app(PortalProfileAccess::class)->audit($request->user(), 'offer_confidential_denied', ['record_id' => $id, 'http_status' => $error->getStatusCode()]);
throw $error;
}
abort_if(isset($result['denied']), 403, 'É necessária aceitação do NDA e autorização expressa do vendedor para esta versão.');
return response()->json($result);
}
public function nda(Request $request, PrivateOfferConfidentiality $privacy, int $id): \Symfony\Component\HttpFoundation\Response
{
$overview = $privacy->overview($request->user(), $id);
abort_unless($overview['nda'], 409, 'O NDA aprovado ainda não foi disponibilizado.');
app(PortalProfileAccess::class)->audit($request->user(), 'offer_nda_access', ['record_id' => $id, 'version_hash' => $overview['version_hash'], 'nda' => $overview['nda']]);
$document = DB::table('documents')->where('id', $overview['nda']['document_id'])->firstOrFail();
abort_unless((int) $document->version_no === $overview['nda']['version'] && hash_equals(trim($document->sha256), $overview['nda']['sha256']), 409, 'O exemplar do NDA mudou; actualize antes de continuar.');
return app(VerifiedDocumentBinary::class)->respond($document);
}
public function index(Request $request, PortalProfileAccess $access): Response
{
$filters = $request->validate(['state' => 'nullable|in:draft,submitted,in_review,needs_information,rejected,approved', 'operational' => 'nullable|boolean', 'pending_reports' => 'nullable|boolean']);
$query = ($filters['operational'] ?? false) ? app(PrivateOfferOperations::class)->staffQuery($request->user()) : $access->scope(Opportunity::query(), $request->user());
if ($filters['pending_reports'] ?? false) {
$query = app(PrivateOfferOperations::class)->staffQuery($request->user());
$query->whereRaw("jsonb_path_exists(COALESCE(workflow_context->'offer_reports','{}'::jsonb), '$.* ? (@.status == \"open\" || @.status == \"in_review\")')");
}
$records = $query->whereNotNull('workflow_context->private_offer_preparation')
->when($filters['state'] ?? null, fn ($q, $state) => $q->where('workflow_context->private_offer_preparation->state', $state))
->orderByDesc('id')->paginate(20)->withQueryString();
return Inertia::render('offers/preparation-index', ['records' => $records->through(fn ($r) => [
'id' => $r->id, 'title' => app(OpportunityManagement::class)->values($r)['title'] ?? null, 'reference' => $r->reference,
'state' => $access->state($r),
'availability' => app(OfferAvailability::class)->record($r)['state'],
]), 'filters' => $filters, 'canCreate' => count($access->navigation($request->user())['contexts']) > 0]);
}
public function edit(Request $request, PrivateOfferPreparation $service, ?int $id = null): Response|JsonResponse
{
$record = $id ? $service->record($request->user(), $id) : null;
$contexts = app(PortalProfileAccess::class)->navigation($request->user())['contexts'];
abort_unless($record || count($contexts) > 0, 403, 'É necessária uma atribuição de promotor no âmbito da oferta.');
$presentation = $record ? $service->presentation($request->user(), $record) : null;
if ($request->expectsJson() && ! $request->header('X-Inertia')) {
return response()->json(['record' => $presentation]);
}
$options = app(OpportunityCanonicalContract::class)->options($request->user(), $record);
return Inertia::render('offers/preparation', ['record' => $presentation, 'contexts' => $contexts,
'contacts' => $options['contacts'], 'contactInvestors' => $options['contactInvestors'],
'sectors' => DB::table('sectors')->where('is_active', true)->orderBy('name')->get(['id', 'name']),
'propertyTypes' => array_values(array_filter($options['definitions']['realEstatePatch']['properties']['property_type']['enum'], fn ($type) => is_string($type)))]);
}
public function save(Request $request, PrivateOfferPreparation $service, ?int $id = null): JsonResponse
{
if ($id) {
$service->record($request->user(), $id, true);
}
$record = $service->save($request->user(), $request->all(), $id);
return response()->json(['record' => $service->presentation($request->user(), $record)], $id ? 200 : 201);
}
public function submit(Request $request, PrivateOfferPreparation $service, int $id): JsonResponse
{
$record = $service->submit($request->user(), $id, $request->all());
return response()->json(['record' => $service->presentation($request->user(), $record),
'message' => 'Submissão privada registada. A oferta não foi publicada.']);
}
public function transition(Request $request, PrivateOfferPreparation $service, OpportunityProfileWorkflow $workflow, int $id): JsonResponse
{
$service->record($request->user(), $id);
$data = $request->validate(['etag' => 'required|string|size:64', 'action' => 'required|in:start_review,assign_review,request_correction,reject,approve,request_revision',
'assignee_user_id' => 'required_if:action,assign_review|integer|min:1',
'reason' => 'required|string|min:20|max:1000', 'correction_items' => 'sometimes|array', 'correction_items.*' => 'string']);
$record = $workflow->transition($request->user(), $id, $data);
return response()->json(['record' => $service->presentation($request->user(), $record), 'message' => 'Decisão privada registada. A oferta não foi publicada.']);
}
}
@@ -6,11 +6,26 @@ use App\Models\Opportunity;
use App\Services\ProactiveSupply; use App\Services\ProactiveSupply;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class ProactiveSupplyController extends Controller final class ProactiveSupplyController extends Controller
{ {
public function review(Request $request, ProactiveSupply $service): JsonResponse|Response
{
$service->authorize($request->user());
$v = $request->validate(['record_id' => 'nullable|integer|min:1']);
$record = isset($v['record_id']) ? Opportunity::whereKey($v['record_id'])->firstOrFail() : null;
$data = $service->review($request->user(), $request->all(), $record);
$data['recordId'] = isset($v['record_id']) ? (int) $v['record_id'] : null;
return $request->expectsJson() ? response()->json($data)->header('Cache-Control', 'private, no-store')
: Inertia::render('management/proactive-supply-review', $data);
}
public function index(Request $request, ProactiveSupply $service): JsonResponse public function index(Request $request, ProactiveSupply $service): JsonResponse
{ {
$service->authorize($request->user());
$v = $request->validate(['record_id' => 'nullable|integer|min:1']); $v = $request->validate(['record_id' => 'nullable|integer|min:1']);
$record = isset($v['record_id']) ? Opportunity::whereKey($v['record_id'])->firstOrFail() : null; $record = isset($v['record_id']) ? Opportunity::whereKey($v['record_id'])->firstOrFail() : null;
+2 -23
View File
@@ -13,37 +13,16 @@ use Symfony\Component\HttpFoundation\Response;
class ProcurementController extends Controller 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 private function query(Procurement $service): Builder
{ {
abort_unless($service->available(), 404); return $service->publicQuery();
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 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 = $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 !== ''); $filters = array_filter($filters, fn ($value) => $value !== null && $value !== '');
$query = $this->query($service); $query = $service->publicQuery($filters);
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 = $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)]); $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)); $facets = $this->query($service)->get(['v.payload'])->map(fn ($r) => json_decode($r->payload, true));
@@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers;
use App\Services\ProductExperiments;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class ProductExperimentController extends Controller
{
public function index(Request $request, ProductExperiments $experiments): Response|JsonResponse
{
$data = $experiments->listing($request->user(), $request->all());
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/experiments/index', $data);
}
public function create(Request $request, ProductExperiments $experiments): Response|JsonResponse
{
return $this->show($request, $experiments);
}
public function show(Request $request, ProductExperiments $experiments, ?string $id = null): Response|JsonResponse
{
$data = $experiments->view($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/experiments/edit', $data);
}
public function store(Request $request, ProductExperiments $experiments): JsonResponse
{
return response()->json($experiments->save($request->user(), null, $request->all()), 201);
}
public function revise(Request $request, ProductExperiments $experiments, string $id): JsonResponse
{
return response()->json($experiments->save($request->user(), $id, $request->all()));
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Controllers;
use App\Services\ProductUsageMetrics;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
final class ProductUsageMetricsController extends Controller
{
public function index(Request $request, ProductUsageMetrics $metrics): Response|JsonResponse
{
$data = ['report' => $metrics->report($request->user(), $request->all())];
return $request->expectsJson() ? response()->json($data) : Inertia::render('management/product-usage', $data);
}
}
@@ -5,11 +5,14 @@ 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\Models\Sector;
use App\Services\BusinessProximitySearch;
use App\Services\CountryCatalogue; use App\Services\CountryCatalogue;
use App\Services\ExistingBusinessClassification; use App\Services\ExistingBusinessClassification;
use App\Services\ExistingBusinessDrafts; use App\Services\ExistingBusinessDrafts;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\OpportunityClassification; use App\Services\OpportunityClassification;
use App\Services\PublicBusinessLocations;
use App\Services\PublicSearchMetrics;
use App\Services\SectorOrganization; use App\Services\SectorOrganization;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
@@ -30,13 +33,7 @@ class PublicBusinessOpportunityController extends Controller
$path = app(InvestmentGeography::class)->selection($filters); $path = app(InvestmentGeography::class)->selection($filters);
if ($path !== []) { if ($path !== []) {
$territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id); $territoryIds = app(InvestmentGeography::class)->descendants($path[array_key_last($path)]->id);
$query->whereExists(fn ($locations) => $locations->selectRaw('1')->from('existing_business_locations as matching_location') $query->whereExists(app(PublicBusinessLocations::class)->matchingArea($territoryIds)->selectRaw('1')->whereColumn('l.existing_business_id', 'existing_businesses.id'));
->whereColumn('matching_location.existing_business_id', 'existing_businesses.id')->where('matching_location.is_public', true)
->where(function ($match) use ($territoryIds): void {
foreach (['province_id', 'district_id', 'admin_post_id', 'locality_id'] as $field) {
$match->orWhereIn('matching_location.'.$field, $territoryIds);
}
}));
} }
if (! empty($filters['q'])) { if (! empty($filters['q'])) {
$term = trim($filters['q']); $term = trim($filters['q']);
@@ -52,12 +49,21 @@ class PublicBusinessOpportunityController extends Controller
$query->where('existing_businesses.modality', $filters['modality']); $query->where('existing_businesses.modality', $filters['modality']);
} }
$results = PublicBusinessOpportunityResource::collection($query->paginate($filters['per_page'] ?? 12)->appends($filters)); $coverage = null;
if (! empty($filters['near_business'])) {
$proximity = app(BusinessProximitySearch::class);
$coverage = $proximity->constrain($query, $proximity->origin($filters['near_business']), (float) $filters['radius_km']);
} else {
$query->orderByDesc('existing_businesses.published_at')->orderBy('existing_businesses.id');
}
$page = $query->paginate($filters['per_page'] ?? 12)->appends($filters);
app(PublicSearchMetrics::class)->candidate($request, 'businesses', $page->total(), $filters);
$results = PublicBusinessOpportunityResource::collection($page)->additional(['geographicCoverage' => $coverage]);
if ($request->expectsJson()) { if ($request->expectsJson()) {
return $results->response(); return $results->response();
} }
return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path, return Inertia::render('investment/business-marketplace', ['results' => $results, 'filters' => $filters, 'territorySelection' => $path, 'geographicCoverage' => $coverage,
'classificationOptions' => app(OpportunityClassification::class)->options(), 'classificationOptions' => app(OpportunityClassification::class)->options(),
'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'])]);
} }
@@ -72,6 +78,7 @@ class PublicBusinessOpportunityController extends Controller
'modality' => ['nullable', Rule::in(ExistingBusinessDrafts::MODALITIES)], 'modality' => ['nullable', Rule::in(ExistingBusinessDrafts::MODALITIES)],
'sector' => ['nullable', 'integer', 'min:1'], 'sector' => ['nullable', 'integer', 'min:1'],
'per_page' => ['nullable', 'integer', 'min:1', 'max:50'], 'per_page' => ['nullable', 'integer', 'min:1', 'max:50'],
'near_business' => ['nullable', 'required_with:radius_km', 'uuid'], 'radius_km' => ['nullable', 'required_with:near_business', 'numeric', 'min:0.1', 'max:2000'],
'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'], 'province_id' => ['nullable', 'uuid'], 'district_id' => ['nullable', 'uuid'],
'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'], 'admin_post_id' => ['nullable', 'uuid'], 'locality_id' => ['nullable', 'uuid'],
...app(ExistingBusinessClassification::class)->filterRules(), ...app(ExistingBusinessClassification::class)->filterRules(),
@@ -87,8 +94,18 @@ class PublicBusinessOpportunityController extends Controller
} }
$returnFilters = $this->filters($request); $returnFilters = $this->filters($request);
$similarProvince = $record->getAttribute('similar_province_id');
if ($similarProvince !== null && ! app(InvestmentGeography::class)->publicReferences()->where('geo_locations.id', $similarProvince)->exists()) {
$similarProvince = null;
}
return Inertia::render('investment/business-opportunity', ['record' => $resource->resolve($request), return Inertia::render('investment/business-opportunity', ['record' => $resource->resolve($request),
'similarRadiusAvailable' => app(BusinessProximitySearch::class)->available($record->id),
'similarCatalogueUrl' => '/negocios?'.http_build_query(array_filter([
'modality' => $record->modality,
'sector' => $record->sector_id,
'province_id' => $similarProvince,
], fn ($value) => $value !== null && $value !== '')),
'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters), 'returnUrl' => $returnFilters === [] ? '/negocios' : '/negocios?'.http_build_query($returnFilters),
'interestUrl' => '/negocios/'.rawurlencode($slug).'/manifestar-interesse'.($returnFilters === [] ? '' : '?'.http_build_query($returnFilters))]); 'interestUrl' => '/negocios/'.rawurlencode($slug).'/manifestar-interesse'.($returnFilters === [] ? '' : '?'.http_build_query($returnFilters))]);
} }
@@ -110,14 +127,14 @@ class PublicBusinessOpportunityController extends Controller
/** @return Builder<ExistingBusiness> */ /** @return Builder<ExistingBusiness> */
private function publishedQuery(): Builder private function publishedQuery(): Builder
{ {
$publicLocations = DB::table('existing_business_locations as locations') $publicLocations = app(PublicBusinessLocations::class)->primary()
->leftJoin('geo_locations as province', 'province.id', '=', 'locations.province_id') ->leftJoin('geo_locations as province', 'province.id', '=', 'l.province_id')
->leftJoin('geo_locations as district', 'district.id', '=', 'locations.district_id') ->leftJoin('geo_locations as district', 'district.id', '=', 'l.district_id')
->leftJoin('geo_locations as locality', 'locality.id', '=', 'locations.locality_id') ->leftJoin('geo_locations as locality', 'locality.id', '=', 'l.locality_id')
->where('locations.is_public', true)->where('locations.is_primary', true)
->whereNull('province.deleted_at')->whereNull('district.deleted_at')->whereNull('locality.deleted_at') ->whereNull('province.deleted_at')->whereNull('district.deleted_at')->whereNull('locality.deleted_at')
->select('locations.existing_business_id', 'province.name as province') ->select('l.existing_business_id', 'l.updated_at as location_recorded_at', 'province.name as province', 'province.id as similar_province_id')
->selectRaw("CASE WHEN locations.precision_level IN ('district','admin_post','locality','exact') THEN district.name ELSE NULL END AS district") ->selectRaw(app(PublicBusinessLocations::class)->sourceProjection())
->selectRaw("CASE WHEN l.precision_level IN ('district','admin_post','locality','exact') THEN district.name ELSE NULL END AS district")
->selectRaw('NULL::text AS locality'); ->selectRaw('NULL::text AS locality');
return ExistingBusiness::query()->published()->with('sector:id,name,slug') return ExistingBusiness::query()->published()->with('sector:id,name,slug')
@@ -127,6 +144,7 @@ class PublicBusinessOpportunityController extends Controller
'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max', 'existing_businesses.currency', 'existing_businesses.amount_min', 'existing_businesses.amount_max',
'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id', 'existing_businesses.available_percentage', 'existing_businesses.published_at', 'existing_businesses.sector_id',
'existing_businesses.owner_user_id', 'existing_businesses.organization_id', 'existing_businesses.version_no', 'existing_businesses.expires_at', 'existing_businesses.status', 'existing_businesses.modality', 'existing_businesses.owner_user_id', 'existing_businesses.organization_id', 'existing_businesses.version_no', 'existing_businesses.expires_at', 'existing_businesses.status', 'existing_businesses.modality',
'public_location.province', 'public_location.district', 'public_location.locality']); 'public_location.province', 'public_location.district', 'public_location.locality', 'public_location.similar_province_id',
'public_location.location_recorded_at', 'public_location.location_source_reference', 'public_location.location_source_date']);
} }
} }
@@ -0,0 +1,67 @@
<?php
namespace App\Http\Controllers;
use App\Models\Opportunity;
use App\Support\PublicSitemapXml;
use Generator;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PublicSitemapController extends Controller
{
private const PAGE_SIZE = 1000;
public function index(PublicSitemapXml $xml): StreamedResponse
{
$base = $this->base();
$pages = (int) ceil(Opportunity::published()->count() / self::PAGE_SIZE);
$locations = (static function () use ($base, $pages): Generator {
yield $base.'/sitemap/pages.xml';
for ($page = 1; $page <= $pages; $page++) {
yield $base.'/sitemap/opportunities/'.$page.'.xml';
}
})();
return $this->response($xml, $locations, true);
}
public function pages(PublicSitemapXml $xml): StreamedResponse
{
$base = $this->base();
$paths = ['/', '/oportunidades', '/sectores', '/como-investir', '/documentos', '/apoio', '/simulador-fiscal', '/politica-de-privacidade', '/termos-de-uso'];
return $this->response($xml, array_map(fn ($path) => $base.$path, $paths));
}
public function opportunities(string $page, PublicSitemapXml $xml): StreamedResponse
{
$number = filter_var($page, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 1000000]]);
abort_if($number === false, 404);
$base = $this->base();
$records = Opportunity::published()->orderBy('id')->offset(($number - 1) * self::PAGE_SIZE)->limit(self::PAGE_SIZE)->get(['slug']);
abort_if($records->isEmpty(), 404);
return $this->response($xml, $records->map(fn ($record) => $base.'/oportunidades/'.rawurlencode($record->slug)));
}
private function base(): string
{
$url = rtrim((string) config('app.url'), '/');
$parts = parse_url($url);
abort_unless(filter_var($url, FILTER_VALIDATE_URL) && is_array($parts)
&& in_array($parts['scheme'] ?? null, ['http', 'https'], true)
&& ! isset($parts['query']) && ! isset($parts['fragment']) && ! isset($parts['user']) && ! isset($parts['pass']), 503);
return $url;
}
/** @param iterable<string> $locations */
private function response(PublicSitemapXml $xml, iterable $locations, bool $index = false): StreamedResponse
{
return response()->stream(static function () use ($xml, $locations, $index): void {
foreach ($xml->chunks($locations, $index) as $chunk) {
echo $chunk;
}
}, 200, ['Content-Type' => 'application/xml; charset=UTF-8', 'Cache-Control' => 'no-store', 'X-Content-Type-Options' => 'nosniff']);
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Http\Controllers;
use App\Services\OpportunityTechnicalSupport;
use App\Services\TechnicalIncidentHandling;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class TechnicalSupportController extends Controller
{
public function index(Request $request, OpportunityTechnicalSupport $support): Response
{
$filters = $request->validate(['page' => ['nullable', 'integer', 'min:1'], 'status' => ['nullable', 'in:all,open,in_progress,resolved'], 'unread' => ['nullable', 'boolean']]);
$status = $filters['status'] ?? 'all';
$unread = $request->boolean('unread');
$incidents = $support->queue($request->user(), $status, $unread);
Inertia::encryptHistory();
return tap(Inertia::render('profiles/technical-support', ['actorId' => $request->user()->id, 'incidents' => $incidents, 'filters' => ['status' => $status, 'unread' => $unread]])->toResponse($request), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function show(Request $request, string $reference, TechnicalIncidentHandling $handling, OpportunityTechnicalSupport $support): Response
{
$filters = $request->validate(['history_page' => ['nullable', 'integer', 'min:1'], 'page' => ['nullable', 'integer', 'min:1'], 'status' => ['nullable', 'in:all,open,in_progress,resolved'], 'unread' => ['nullable', 'boolean']]);
$data = $handling->detail($request->user(), $reference);
Inertia::encryptHistory();
$query = array_filter(['page' => $request->integer('page') > 1 ? $request->integer('page') : null, 'status' => ($filters['status'] ?? 'all') !== 'all' ? $filters['status'] : null, 'unread' => $request->boolean('unread') ? 1 : null], fn ($v) => $v !== null);
return tap(Inertia::render('profiles/technical-incident', [...$data, 'notice' => $support->notice($request->user(), $reference), 'backUrl' => '/suporte-tecnico/incidentes'.($query !== [] ? '?'.http_build_query($query) : '')])->toResponse($request), static fn (Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
}
public function decide(Request $request, string $reference, TechnicalIncidentHandling $handling): JsonResponse
{
return response()->json($handling->decide($request->user(), $reference, $request->all()))->header('Cache-Control', 'private, no-store');
}
public function consulted(Request $request, string $reference, OpportunityTechnicalSupport $support): JsonResponse
{
return response()->json($support->markConsulted($request->user(), $reference))->header('Cache-Control', 'private, no-store');
}
}
@@ -5,11 +5,32 @@ namespace App\Http\Controllers;
use App\Services\TerritorialRegistry; use App\Services\TerritorialRegistry;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Pagination\CursorPaginator;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
class TerritorialRegistryController extends Controller class TerritorialRegistryController extends Controller
{ {
public function editor(Request $request, TerritorialRegistry $registry): Response
{
abort_unless($registry->editorialAvailable(), 404);
$actor = $request->user();
$roles = array_values(array_filter(['editors', 'reviewers', 'publishers'], fn ($role) => in_array(strtolower($actor->email), config('territorial.'.$role, []), true)));
$context = $request->validate(['territory' => 'nullable|uuid', 'notice_version' => 'nullable|integer|min:1']);
return Inertia::render('management/territorial-editorial', ['roles' => $roles, 'actorId' => $actor->id, 'initialTerritory' => $context['territory'] ?? null, 'noticeVersion' => $context['notice_version'] ?? null])->toResponse($request);
}
public function preview(Request $request, TerritorialRegistry $registry, string $id): JsonResponse
{
abort_unless($registry->editorialAvailable(), 404);
return response()->json($registry->preview($id));
}
public function sources(Request $request): JsonResponse public function sources(Request $request): JsonResponse
{ {
$data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]); $data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]);
@@ -17,13 +38,25 @@ class TerritorialRegistryController extends Controller
return response()->json(DB::table('geo_sources')->orderBy('id')->cursorPaginate($data['limit'] ?? 20)->withQueryString()); return response()->json(DB::table('geo_sources')->orderBy('id')->cursorPaginate($data['limit'] ?? 20)->withQueryString());
} }
public function drafts(Request $request): JsonResponse public function drafts(Request $request, TerritorialRegistry $registry): JsonResponse
{ {
$data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]); $data = $request->validate(['limit' => ['nullable', 'integer', 'between:1,100'], 'cursor' => ['nullable', 'string', 'max:512']]);
return response()->json(DB::table('geo_locations as g')->join('geo_territory_profiles as p', 'p.geo_location_id', '=', 'g.id')->whereNull('g.deleted_at') $page = DB::table('geo_locations as g')->join('geo_territory_profiles as p', 'p.geo_location_id', '=', 'g.id')->whereNull('g.deleted_at')
->select(['g.id', 'g.name', 'g.code', 'g.location_type', 'g.parent_id', 'g.version_no', 'p.source_id', 'p.status', 'p.valid_from', 'p.valid_to', 'p.editor_id', 'p.reviewer_id', 'p.publisher_id']) ->select(['g.id', 'g.name', 'g.code', 'g.location_type', 'g.parent_id', 'g.version_no', 'p.source_id', 'p.status', 'p.valid_from', 'p.valid_to', 'p.editor_id', 'p.reviewer_id', 'p.publisher_id'])
->orderBy('g.id')->cursorPaginate($data['limit'] ?? 20)->withQueryString()); ->orderBy('g.id')->cursorPaginate($data['limit'] ?? 20)->withQueryString();
if ($registry->editorialAvailable()) {
abort_unless($page instanceof CursorPaginator, 503, 'Paginação territorial indisponível.');
$page->through(function ($row) use ($registry) {
$state = $registry->working($row->id);
return [...$state['location'], ...$state['profile'], 'id' => $row->id,
'public_version_no' => $state['public_version_no'], 'fresh' => $state['fresh'],
'private_revision' => $state['_editorial']['private'] ?? false];
});
}
return response()->json($page);
} }
public function index(Request $request, TerritorialRegistry $registry, ?string $collection = null): JsonResponse public function index(Request $request, TerritorialRegistry $registry, ?string $collection = null): JsonResponse
@@ -74,7 +107,8 @@ class TerritorialRegistryController extends Controller
{ {
$id = $registry->save($request->user(), $request->all(), $id); $id = $registry->save($request->user(), $request->all(), $id);
return response()->json(['id' => $id, 'status' => 'draft', 'version_no' => DB::table('geo_locations')->where('id', $id)->value('version_no')]); return response()->json(['id' => $id, 'status' => 'draft', 'version_no' => $registry->editorialAvailable()
? $registry->working($id)['location']['version_no'] : DB::table('geo_locations')->where('id', $id)->value('version_no')]);
} }
public function source(Request $request): JsonResponse public function source(Request $request): JsonResponse
@@ -95,9 +129,15 @@ class TerritorialRegistryController extends Controller
public function transition(Request $request, TerritorialRegistry $registry, string $id): JsonResponse public function transition(Request $request, TerritorialRegistry $registry, string $id): JsonResponse
{ {
$data = $request->validate(['action' => ['required', 'in:pending_review,approved,published,rejected,archived'], $data = $request->validate(['action' => ['required', 'in:pending_review,in_review,approved,published,rejected,archived,withdrawn'],
'version_no' => ['required', 'integer', 'min:1'], 'reason' => ['required', 'string', 'min:10', 'max:1000']]); 'version_no' => ['required', 'integer', 'min:1'], 'reason' => ['required', 'string', 'min:10', 'max:1000']]);
$registry->ensureWriteMode($id);
if ($registry->editorialAvailable() && $registry->hasEditorialHistory($id)) {
return response()->json($registry->transitionEditorial($request->user(), $id, $data));
}
abort_if(in_array($data['action'], ['in_review', 'withdrawn'], true), 422);
return DB::transaction(function () use ($request, $registry, $id, $data) { return DB::transaction(function () use ($request, $registry, $id, $data) {
DB::select('SELECT pg_advisory_xact_lock(280926, 150000)'); DB::select('SELECT pg_advisory_xact_lock(280926, 150000)');
$location = DB::table('geo_locations')->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first(); $location = DB::table('geo_locations')->where('id', $id)->whereNull('deleted_at')->lockForUpdate()->first();
+165 -42
View File
@@ -7,6 +7,9 @@ use App\Models\InvestmentSubmission;
use App\Models\User; use App\Models\User;
use App\Services\Ai\InvestorGuidance; use App\Services\Ai\InvestorGuidance;
use App\Services\CountryCatalogue; use App\Services\CountryCatalogue;
use App\Services\DeskAttachments;
use App\Services\DeskPaymentEvidence;
use App\Services\DeskServiceAvailability;
use App\Services\InstitutionalLinkMonitor; use App\Services\InstitutionalLinkMonitor;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\InvestorContextConsumers; use App\Services\InvestorContextConsumers;
@@ -27,6 +30,7 @@ use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class VirtualDeskController extends Controller class VirtualDeskController extends Controller
{ {
@@ -34,7 +38,7 @@ class VirtualDeskController extends Controller
{ {
$filters = $request->validate(['q' => 'nullable|string|max:120', 'theme' => 'nullable|string|max:80', 'profile' => 'nullable|string|max:100']); $filters = $request->validate(['q' => 'nullable|string|max:120', 'theme' => 'nullable|string|max:80', 'profile' => 'nullable|string|max:100']);
$installed = $desk->installed(); $installed = $desk->installed();
$services = $installed ? DB::table('desk_service_versions')->where('status', 'published')->orderBy('code')->orderByDesc('version')->get()->unique('code')->map(fn ($s) => ['id' => $s->id, 'version' => $s->version, 'definition' => json_decode($s->definition, true), 'source' => json_decode($s->source, true)])->values() : collect(); $services = $installed ? app(DeskServiceAvailability::class)->current()->get()->map(fn ($s) => ['id' => $s->id, 'version' => $s->version, 'effective_from' => $s->effective_from ?? null, 'definition' => json_decode($s->definition, true), 'source' => json_decode($s->source, true)])->values() : collect();
$services = $services->filter(fn ($s) => (! ($filters['q'] ?? '') || str_contains(mb_strtolower(json_encode($s['definition'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), mb_strtolower($filters['q']))) $services = $services->filter(fn ($s) => (! ($filters['q'] ?? '') || str_contains(mb_strtolower(json_encode($s['definition'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)), mb_strtolower($filters['q'])))
&& (! ($filters['theme'] ?? '') || $s['definition']['theme'] === $filters['theme']) && (! ($filters['profile'] ?? '') || $s['definition']['profile'] === $filters['profile']))->values(); && (! ($filters['theme'] ?? '') || $s['definition']['theme'] === $filters['theme']) && (! ($filters['profile'] ?? '') || $s['definition']['profile'] === $filters['profile']))->values();
$page = max(1, (int) $request->query('page', 1)); $page = max(1, (int) $request->query('page', 1));
@@ -49,7 +53,7 @@ class VirtualDeskController extends Controller
$actor = $request->user(); $actor = $request->user();
$organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id'); $organizations = DB::table('memberships')->where('user_id', $actor->id)->whereNull('deleted_at')->pluck('organization_id');
$cases = DB::table('desk_cases')->where(fn ($q) => $q->where(fn ($p) => $p->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))->orderByDesc('updated_at')->get(['id', 'title', 'version', 'updated_at']); $cases = DB::table('desk_cases')->where(fn ($q) => $q->where(fn ($p) => $p->where('user_id', $actor->id)->whereNull('organization_id'))->orWhereIn('organization_id', $organizations))->orderByDesc('updated_at')->get(['id', 'title', 'version', 'updated_at']);
$queue = DB::table('desk_requests as r')->join('desk_cases as c', 'c.id', '=', 'r.case_id')->whereNotIn('r.status', ['draft', 'cancelled'])->when(! $actor->can('manage-portal'), fn ($q) => $q->where('r.analyst_id', $actor->id)) $queue = DB::table('desk_requests as r')->join('desk_cases as c', 'c.id', '=', 'r.case_id')->whereNull('c.closed_at')->whereNotIn('r.status', ['draft', 'cancelled', 'closed'])->when(! $actor->can('manage-portal'), fn ($q) => $q->where('r.analyst_id', $actor->id))
->orderByRaw('r.due_at ASC NULLS LAST')->get(['r.id', 'r.protocol', 'r.status', 'r.version', 'r.analyst_id', 'r.due_at', 'c.title']); ->orderByRaw('r.due_at ASC NULLS LAST')->get(['r.id', 'r.protocol', 'r.status', 'r.version', 'r.analyst_id', 'r.due_at', 'c.title']);
$data = ['cases' => $cases, 'queue' => $queue, 'notifications' => DB::table('desk_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(100)->get(), $data = ['cases' => $cases, 'queue' => $queue, 'notifications' => DB::table('desk_notifications')->where('user_id', $actor->id)->orderByDesc('id')->limit(100)->get(),
'legacyRequests' => DB::table('interest_requests')->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->orderByDesc('created_at')->get(['id', 'reference', 'status', 'created_at']), 'legacyRequests' => DB::table('interest_requests')->where('metadata->portal_user_id', $actor->id)->whereNull('deleted_at')->orderByDesc('created_at')->get(['id', 'reference', 'status', 'created_at']),
@@ -74,6 +78,23 @@ class VirtualDeskController extends Controller
} }
public function showCase(Request $request, string $id, VirtualDesk $desk): JsonResponse|Response public function showCase(Request $request, string $id, VirtualDesk $desk): JsonResponse|Response
{
$data = $this->caseViewData($request, $id, $desk);
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/case', $data);
}
public function preDossier(Request $request, string $id, VirtualDesk $desk): \Illuminate\Http\Response
{
return response()->view('desk.pre-dossier', $this->caseViewData($request, $id, $desk), 200, [
'Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff',
]);
}
/** Same authorised projection for the workspace and its preparation document.
* @return array<string,mixed>
*/
private function caseViewData(Request $request, string $id, VirtualDesk $desk): array
{ {
$case = $desk->case($request->user(), $id); $case = $desk->case($request->user(), $id);
$owner = $desk->owns($request->user(), $case, false); $owner = $desk->owns($request->user(), $case, false);
@@ -86,14 +107,15 @@ class VirtualDeskController extends Controller
'legacyRequest' => ($case->interest_request_id ?? null) ? DB::table('interest_requests as r')->leftJoin('users as u', 'u.id', '=', 'r.assigned_to')->where('r.id', $case->interest_request_id)->whereNull('r.deleted_at') 'legacyRequest' => ($case->interest_request_id ?? null) ? DB::table('interest_requests as r')->leftJoin('users as u', 'u.id', '=', 'r.assigned_to')->where('r.id', $case->interest_request_id)->whereNull('r.deleted_at')
->when(! $request->user()->can('manage-portal'), fn ($q) => $q->where('r.metadata->portal_user_id', $request->user()->id)) ->when(! $request->user()->can('manage-portal'), fn ($q) => $q->where('r.metadata->portal_user_id', $request->user()->id))
->first(['r.id', 'r.reference', 'r.status', 'r.next_action', 'r.next_action_due_at', 'u.name as responsible_name']) : null, ->first(['r.id', 'r.reference', 'r.status', 'r.next_action', 'r.next_action_due_at', 'u.name as responsible_name']) : null,
'owner' => $owner, 'canWrite' => $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'), 'owner' => $owner, 'canWrite' => ! $case->closed_at && $desk->owns($request->user(), $case), 'manager' => $request->user()->can('manage-portal'),
'canChangeState' => (int) $case->user_id === $request->user()->id && $desk->owns($request->user(), $case), 'activity' => $owner ? $desk->caseActivity($case) : null,
'requests' => DB::table('desk_requests')->where('case_id', $id)->when(! $owner && ! $request->user()->can('manage-portal'), fn ($q) => $q->where('analyst_id', $request->user()->id))->orderByDesc('updated_at')->get(['id', 'status', 'protocol', 'service_version_id', 'version']), 'requests' => DB::table('desk_requests')->where('case_id', $id)->when(! $owner && ! $request->user()->can('manage-portal'), fn ($q) => $q->where('analyst_id', $request->user()->id))->orderByDesc('updated_at')->get(['id', 'status', 'protocol', 'service_version_id', 'version']),
'services' => DB::table('desk_service_versions')->where('status', 'published')->orderByDesc('version')->get(['id', 'code', 'version', 'definition'])->unique('code')->values()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title'], 'version' => $s->version]), 'services' => app(DeskServiceAvailability::class)->current()->get()->map(fn ($s) => ['id' => $s->id, 'title' => json_decode($s->definition, true)['title'], 'version' => $s->version, 'effective_from' => $s->effective_from ?? null]),
'documents' => $this->documents($id, $request->user()), 'events' => $this->events($id, $desk, $request->user()), 'stepStates' => config('virtual-desk.step_states'), 'states' => config('virtual-desk.request_states'), 'documents' => $this->documents($id, $request->user()), 'events' => $this->events($id, $desk, $request->user()), 'stepStates' => config('virtual-desk.step_states'), 'states' => config('virtual-desk.request_states'),
'links' => DB::table('desk_institutional_links')->get()->map(fn ($link) => [...(array) $link, 'monitor' => app(InstitutionalLinkMonitor::class)->status($link)]), 'source' => config('virtual-desk.source'), 'support' => config('portal.support'), 'links' => DB::table('desk_institutional_links')->get()->map(fn ($link) => [...(array) $link, 'monitor' => app(InstitutionalLinkMonitor::class)->status($link)]), 'source' => config('virtual-desk.source'), 'support' => config('portal.support'),
'guidance' => app(InvestorGuidance::class)->installed() ? app(InvestorGuidance::class)->view($request->user(), $id) : null]; 'guidance' => app(InvestorGuidance::class)->installed() ? app(InvestorGuidance::class)->view($request->user(), $id) : null];
return $request->expectsJson() ? response()->json($data) : Inertia::render('desk/case', $data); return $data;
} }
/** @return Collection<int,\stdClass> */ /** @return Collection<int,\stdClass> */
@@ -101,7 +123,46 @@ class VirtualDeskController extends Controller
{ {
return DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $case)->whereNull('d.deleted_at') return DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $case)->whereNull('d.deleted_at')
->when(! app(VirtualDesk::class)->owns($actor, app(VirtualDesk::class)->case($actor, $case), false) && ! $actor->can('manage-portal'), fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id')))) ->when(! app(VirtualDesk::class)->owns($actor, app(VirtualDesk::class)->case($actor, $case), false) && ! $actor->can('manage-portal'), fn ($q) => $q->where(fn ($p) => $p->whereNull('l.request_id')->orWhereIn('l.request_id', DB::table('desk_requests')->where('analyst_id', $actor->id)->select('id'))))
->get(['l.id', 'l.document_id', 'l.request_id', 'l.category', 'l.stage', 'l.source_reference', 'l.valid_until', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.sha256']); ->get(['l.id', 'l.document_id', 'l.request_id', 'l.category', 'l.stage', 'l.source_reference', 'l.valid_until', 'd.file_name', 'd.status', 'd.malware_scan_status', 'd.sha256', 'd.media_type', 'd.size_bytes', 'd.version_no']);
}
public function availableDocuments(Request $request, string $id, VirtualDesk $desk): JsonResponse
{
$case = $desk->case($request->user(), $id, true);
abort_if($case->closed_at, 409, 'Dossier encerrado.');
$data = $request->validate(['q' => 'nullable|string|max:120', 'offset' => 'nullable|integer|min:0']);
$offset = (int) ($data['offset'] ?? 0);
$actor = $request->user();
// Match the existing reuse authority: this dossier, own personal dossiers, or own uploads.
// A document's uploader does not inherit another dossier's reference or private context.
$sources = DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')
->where(fn ($q) => $q->where('c.id', $id)->orWhere(fn ($p) => $p->where('c.user_id', $actor->id)->whereNull('c.organization_id')))
->select(['l.id', 'l.document_id', 'l.category', 'l.stage', 'l.source_reference', 'l.valid_until', 'c.title as origin_label']);
$query = DB::table('documents as d')->leftJoinSub($sources, 's', fn ($q) => $q->on('s.document_id', '=', 'd.id'))
->whereNull('d.deleted_at')->where(fn ($q) => $q->where('d.uploaded_by', $actor->id)->orWhereNotNull('s.id'));
$search = trim($data['q'] ?? '');
if ($search !== '') {
$like = '%'.addcslashes($search, '\\%_').'%';
$query->where(fn ($q) => $q->where('d.file_name', 'ilike', $like)->orWhere('s.source_reference', 'ilike', $like)->orWhere('s.origin_label', 'ilike', $like));
}
$rows = $query->orderBy('d.file_name')->orderBy('d.id')->orderBy('s.id')->offset($offset)->limit(26)
->get(['d.id as document_id', 'd.file_name', 'd.version_no', 'd.status', 'd.malware_scan_status', 'd.media_type', 'd.size_bytes', 'd.source_system', 's.id', 's.category', 's.stage', 's.source_reference', 's.valid_until', 's.origin_label']);
$items = $rows->take(25)->filter(function ($document) {
try {
app(VerifiedDocumentBinary::class)->authorizeOpportunityAttachment((object) [...(array) $document, 'id' => $document->document_id]);
return true;
} catch (HttpExceptionInterface $exception) {
if ($exception->getStatusCode() !== 403) {
throw $exception;
}
return false;
}
})->map(fn ($document) => Arr::except((array) $document, ['source_system']))->values();
$this->auditRead($request, 'desk_cases', $id);
return response()->json(['documents' => $items, 'next_offset' => $rows->count() > 25 ? $offset + 25 : null], 200, ['Cache-Control' => 'private, no-store']);
} }
/** @return Collection<int,array{id:mixed,request_id:mixed,action:mixed,version:mixed,created_at:mixed,name:mixed,payload:array<string,mixed>}> */ /** @return Collection<int,array{id:mixed,request_id:mixed,action:mixed,version:mixed,created_at:mixed,name:mixed,payload:array<string,mixed>}> */
@@ -112,6 +173,13 @@ class VirtualDeskController extends Controller
->orderBy('e.event_order')->get(['e.id', 'e.request_id', 'e.action', 'e.payload', 'e.version', 'e.created_at', 'u.name'])->map(fn ($e) => ['id' => $e->id, 'request_id' => $e->request_id, 'action' => $e->action, 'version' => $e->version, 'created_at' => $e->created_at, 'name' => $e->name, 'payload' => $desk->decode($e->payload)]); ->orderBy('e.event_order')->get(['e.id', 'e.request_id', 'e.action', 'e.payload', 'e.version', 'e.created_at', 'u.name'])->map(fn ($e) => ['id' => $e->id, 'request_id' => $e->request_id, 'action' => $e->action, 'version' => $e->version, 'created_at' => $e->created_at, 'name' => $e->name, 'payload' => $desk->decode($e->payload)]);
} }
public function caseState(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$result = $desk->changeCaseState($request->user(), $id, $request->all());
return $request->expectsJson() ? response()->json($result) : back()->with('success', $result['replayed'] ? 'Operação já registada; o estado actual do dossier é apresentado.' : ($result['closed_at'] ? 'Dossier encerrado pelo dono. Os registos continuam disponíveis para consulta.' : 'Dossier reaberto pelo dono. Mantêm-se os estados próprios dos pedidos e das tarefas.'));
}
public function stage(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse public function stage(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{ {
$case = $desk->stage($request->user(), $id, $request->all()); $case = $desk->stage($request->user(), $id, $request->all());
@@ -147,17 +215,21 @@ class VirtualDeskController extends Controller
} }
} }
$this->auditRead($request, 'desk_requests', $id); $this->auditRead($request, 'desk_requests', $id);
$caseDocuments = $this->documents($case->id, $request->user());
$paymentEvidence = app(DeskPaymentEvidence::class)->forRequest($id);
$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),
'serviceEffectiveFrom' => DB::table('desk_service_versions')->where('id', $row->service_version_id)->selectRaw(app(DeskServiceAvailability::class)->dateProjection())->first()->effective_from,
'owner' => $desk->owns($request->user(), $case), 'manager' => app(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, []), 'operationsEditable' => ! $case->closed_at && ! in_array($row->status, ['closed', 'cancelled'], true), 'fieldsEditable' => ! $case->closed_at && in_array($row->status, ['draft', 'returned'], true), 'states' => config('virtual-desk.request_states'), 'transitions' => $case->closed_at ? [] : config('virtual-desk.transitions.'.$row->status, []), 'returnReasons' => config('product-metrics.return_reasons'),
'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, $definition), 'ai' => config('virtual-desk.ai'), 'documents' => $caseDocuments->filter(fn ($d) => ! $d->request_id || $d->request_id === $id)->values(),
'reusableDocuments' => $desk->owns($request->user(), $case) && ! $case->closed_at ? $caseDocuments->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),
'kind' => $messageKinds[$m->id] ?? 'historical_unclassified']), 'kind' => $messageKinds[$m->id] ?? 'historical_unclassified']),
'events' => $this->events($case->id, $desk, $request->user())->filter(fn ($e) => $e['request_id'] === $id)->values(), 'events' => $this->events($case->id, $desk, $request->user())->filter(fn ($e) => $e['request_id'] === $id)->values(),
'revisions' => DB::table('desk_revisions')->where('request_id', $id)->orderByDesc('version')->get(['version', 'snapshot', 'created_at'])->map(fn ($r) => [...(array) $r, 'snapshot' => $desk->decode($r->snapshot)]), 'revisions' => DB::table('desk_revisions')->where('request_id', $id)->orderByDesc('version')->get(['version', 'snapshot', 'created_at'])->map(fn ($r) => [...(array) $r, 'snapshot' => $desk->decode($r->snapshot)]),
'payments' => DB::table('desk_payments')->where('request_id', $id)->get(), 'payments' => DB::table('desk_payments')->where('request_id', $id)->get()->map(fn ($payment) => [...(array) $payment, 'document_evidence' => $paymentEvidence[$payment->id] ?? null]),
'analysts' => $request->user()->can('manage-portal') ? User::orderBy('name')->get(['id', 'name']) : [], 'analysts' => $request->user()->can('manage-portal') ? User::orderBy('name')->get(['id', 'name']) : [],
'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type'])]; 'territories' => app(InvestmentGeography::class)->publicReferences()->orderBy('name')->get(['id', 'name', 'location_type'])];
@@ -182,7 +254,9 @@ class VirtualDeskController extends Controller
{ {
abort_unless(app(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'])
->whereExists(fn ($q) => $q->selectRaw('1')->from('desk_cases')->whereColumn('desk_cases.id', 'desk_requests.case_id')->whereNull('desk_cases.closed_at'))
->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);
@@ -195,8 +269,9 @@ class VirtualDeskController extends Controller
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 !== null, 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)->lockForUpdate()->first();
abort_unless($case !== null, 404); abort_unless($case !== null, 404);
$desk->assertOpen($case);
if ((int) $row->version !== (int) $data['version']) { if ((int) $row->version !== (int) $data['version']) {
throw ValidationException::withMessages(['version' => 'Este pedido foi actualizado. Recupere a lista e tente novamente.']); throw ValidationException::withMessages(['version' => 'Este pedido foi actualizado. Recupere a lista e tente novamente.']);
} }
@@ -218,7 +293,8 @@ class VirtualDeskController extends Controller
$data = $request->validate(['body' => 'required|string|min:1|max:10000', 'client_key' => 'required|uuid']); $data = $request->validate(['body' => 'required|string|min:1|max:10000', 'client_key' => 'required|uuid']);
DB::transaction(function () use ($request, $id, $desk, $data) { DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true); $row = $desk->request($request->user(), $id, false, true);
$case = $desk->case($request->user(), $row->case_id); $case = $desk->case($request->user(), $row->case_id, false, true);
$desk->assertOpen($case);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409, 'Pedido encerrado.'); abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409, 'Pedido encerrado.');
abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403); abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403);
$existing = DB::table('desk_messages')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('client_key', $data['client_key'])->first(); $existing = DB::table('desk_messages')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('client_key', $data['client_key'])->first();
@@ -245,7 +321,10 @@ class VirtualDeskController extends Controller
$this->auditRead($request, 'desk_requests', $id, 'receipt_downloaded'); $this->auditRead($request, 'desk_requests', $id, 'receipt_downloaded');
if ($format === 'html') { if ($format === 'html') {
return response()->view('desk.receipt', ['record' => $row, 'snapshot' => $snapshot, 'definition' => $desk->definition($row)], 200, ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']); $definition = $desk->definition($row);
return response()->view('desk.receipt', ['record' => $row, 'snapshot' => $snapshot, 'definition' => $definition,
'applicableFields' => $desk->applicableFields($snapshot['payload'] ?? [], $definition)], 200, ['Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
} }
return response()->streamDownload(function () use ($row, $snapshot) { return response()->streamDownload(function () use ($row, $snapshot) {
@@ -257,49 +336,90 @@ class VirtualDeskController extends Controller
public function attach(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse public function attach(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{ {
$data = $request->validate(['version' => 'required|integer', 'file' => 'nullable|required_without:document_id|file|mimetypes:application/pdf,image/png,image/jpeg,text/plain|max:10240', $data = $request->validate(['version' => 'required|integer', 'file' => 'nullable|required_without:document_id|file|mimetypes:application/pdf,image/png,image/jpeg,text/plain|max:10240',
'document_id' => 'nullable|required_without:file|uuid', 'category' => 'required|string|max:80', 'stage' => 'nullable|string|max:3', 'request_id' => 'nullable|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'source_reference' => 'required|string|max:3000', 'consent' => 'accepted']); 'document_id' => 'nullable|required_without:file|required_with:reuse_link_id|prohibits:file|uuid', 'reuse_link_id' => 'nullable|uuid|prohibits:file', 'category' => 'nullable|required_without:field_key|string|max:80', 'field_key' => 'nullable|string|max:64',
'stage' => 'nullable|string|max:3', 'request_id' => 'nullable|required_with:field_key|uuid', 'valid_until' => 'nullable|date_format:Y-m-d', 'source_reference' => 'nullable|required_without:document_id|string|max:3000', 'consent' => 'accepted']);
$key = null; $key = null;
$newId = null; $newId = null;
$linkId = null;
$reusedLink = false;
try { try {
DB::transaction(function () use ($request, $id, $desk, $data, &$key, &$newId) { DB::transaction(function () use ($request, $id, $desk, $data, &$key, &$newId, &$linkId, &$reusedLink) {
$row = ($data['request_id'] ?? null) ? $desk->request($request->user(), $data['request_id'], true, true) : null;
$case = $desk->case($request->user(), $id, true, true); $case = $desk->case($request->user(), $id, true, true);
abort_if($case->closed_at, 409, 'Dossier encerrado.'); abort_if($case->closed_at, 409, 'Dossier encerrado.');
abort_unless((int) $case->version === (int) $data['version'], 409); abort_unless((int) $case->version === (int) $data['version'], 409);
if ($data['stage'] ?? null) { if ($data['stage'] ?? null) {
abort_unless(array_key_exists($data['stage'], config('virtual-desk.steps')), 422); abort_unless(array_key_exists($data['stage'], config('virtual-desk.steps')), 422);
} }
if ($data['request_id'] ?? null) { if ($row) {
$row = $desk->request($request->user(), $data['request_id'], true, true);
abort_unless($row->case_id === $id && in_array($row->status, ['draft', 'returned'], true), 409, 'Anexos de pedidos submetidos são imutáveis; use a devolução para corrigir.'); abort_unless($row->case_id === $id && in_array($row->status, ['draft', 'returned'], true), 409, 'Anexos de pedidos submetidos são imutáveis; use a devolução para corrigir.');
} }
abort_if(DB::table('desk_documents')->where('case_id', $id)->count() >= 100, 422, 'Limite de anexos do dossier atingido.'); $definition = $row ? $desk->definition($row) : [];
if ($request->hasFile('file')) { $field = ($data['field_key'] ?? null) ? app(DeskAttachments::class)->field($definition, $data['field_key']) : null;
$file = $request->file('file'); if ($field) {
$hash = hash_file('sha256', $file->getRealPath()); if (isset($data['stage']) && $data['stage'] !== $definition['stage']) {
$duplicate = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->where('d.sha256', $hash)->first(); throw ValidationException::withMessages(['stage' => 'A utilização nesta pergunta pertence à etapa do pedido; a origem do documento é conservada separadamente.']);
if ($duplicate) {
return;
} }
$newId = (string) Str::uuid(); abort_unless(app(DeskAttachments::class)->scopedLinksInstalled(), 409, 'Instale a actualização dos vínculos documentais para este formulário.');
$key = $file->storeAs('virtual-desk/'.$id, $newId, 'local'); if ($row->status === 'returned' && ! in_array($data['field_key'], json_decode($row->editable_fields ?? '[]', true), true)) {
abort_unless(is_string($key) && $key !== '', 500); throw ValidationException::withMessages(['field_key' => 'Esta pergunta não está autorizada para correcção.']);
DB::table('documents')->insert(['id' => $newId, 'source_system' => 'virtual-desk', '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']);
$documentId = $newId;
} else {
$documentId = $data['document_id'];
$document = DB::table('documents')->where('id', $documentId)->whereNull('deleted_at')->first();
abort_unless($document !== null, 404);
$owned = (int) $document->uploaded_by === $request->user()->id || DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')->where('l.document_id', $documentId)->where('c.user_id', $request->user()->id)->whereNull('c.organization_id')->exists();
abort_unless($owned, 403, 'Não há autorização para reutilizar este documento.');
if (DB::table('desk_documents')->where('case_id', $id)->where('document_id', $documentId)->exists()) {
return;
} }
} }
DB::table('desk_documents')->insert(['id' => (string) Str::uuid(), 'case_id' => $id, 'document_id' => $documentId, 'request_id' => $data['request_id'] ?? null, $document = null;
'category' => $data['category'], 'stage' => $data['stage'] ?? null, 'valid_until' => $data['valid_until'] ?? null, 'source_reference' => $data['source_reference'], 'linked_by' => $request->user()->id]); if ($request->hasFile('file')) {
$file = $request->file('file');
if ($field) {
app(DeskAttachments::class)->checkMetadata((object) ['media_type' => $file->getMimeType(), 'size_bytes' => $file->getSize()], $field, 'file');
}
$hash = hash_file('sha256', $file->getRealPath());
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')->where('l.case_id', $id)->whereNull('d.deleted_at')->where('d.sha256', $hash)->first(['d.*']);
if (! $document) {
abort_if(DB::table('desk_documents')->where('case_id', $id)->distinct()->count('document_id') >= 100, 422, 'Limite de ficheiros distintos do dossier atingido.');
$newId = (string) Str::uuid();
$key = $file->storeAs('virtual-desk/'.$id, $newId, 'local');
abort_unless(is_string($key) && $key !== '', 500);
DB::table('documents')->insert(['id' => $newId, 'source_system' => 'virtual-desk', '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']);
$document = DB::table('documents')->where('id', $newId)->firstOrFail();
}
} else {
$document = DB::table('documents')->where('id', $data['document_id'])->whereNull('deleted_at')->first();
abort_unless($document !== null, 404);
$owned = (int) $document->uploaded_by === $request->user()->id || DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)->exists()
|| DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')->where('l.document_id', $document->id)->where('c.user_id', $request->user()->id)->whereNull('c.organization_id')->exists();
abort_unless($owned, 403, 'Não há autorização para reutilizar este documento.');
}
if ($field) {
app(DeskAttachments::class)->checkMetadata($document, $field, 'document_id', true);
}
app(VerifiedDocumentBinary::class)->authorizeOpportunityAttachment($document);
$existing = DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)
->where(fn ($q) => ($data['request_id'] ?? null) ? $q->whereNull('request_id')->orWhere('request_id', $data['request_id']) : $q->whereNull('request_id'))->orderByRaw('request_id IS NULL DESC')->first();
if ($existing) {
$linkId = $existing->id;
$reusedLink = true;
return;
}
if (! app(DeskAttachments::class)->scopedLinksInstalled() && DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)->exists()) {
throw ValidationException::withMessages(['document_id' => 'Instale a actualização dos vínculos para reutilizar o ficheiro noutro pedido, preservando o âmbito anterior.']);
}
$inCase = DB::table('desk_documents')->where('case_id', $id)->where('document_id', $document->id)->exists();
abort_if(! $inCase && DB::table('desk_documents')->where('case_id', $id)->distinct()->count('document_id') >= 100, 422, 'Limite de ficheiros distintos do dossier atingido.');
$sourceLink = DB::table('desk_documents as l')->join('desk_cases as c', 'c.id', '=', 'l.case_id')->where('l.document_id', $document->id)
->where(fn ($q) => $q->where('l.case_id', $id)->orWhere(fn ($p) => $p->where('c.user_id', $request->user()->id)->whereNull('c.organization_id')))
->when($data['reuse_link_id'] ?? null, fn ($q, $sourceId) => $q->where('l.id', $sourceId))->orderBy('l.created_at')->orderBy('l.id')->first(['l.*']);
abort_if(($data['reuse_link_id'] ?? null) && ! $sourceLink, 403, 'Não há autorização para reutilizar esta referência documental.');
$source = $data['source_reference'] ?? $sourceLink?->source_reference;
if (! is_string($source) || trim($source) === '') {
throw ValidationException::withMessages(['source_reference' => 'Indique a proveniência deste documento; não existe uma referência autorizada para reutilizar.']);
}
$linkId = (string) Str::uuid();
DB::table('desk_documents')->insert(['id' => $linkId, 'case_id' => $id, 'document_id' => $document->id, 'request_id' => $data['request_id'] ?? null,
'category' => $field ? Str::limit($field['label'], 80, '') : $data['category'], 'stage' => $data['stage'] ?? ($field ? $definition['stage'] : $sourceLink?->stage), 'valid_until' => array_key_exists('valid_until', $data) ? $data['valid_until'] : $sourceLink?->valid_until, 'source_reference' => $source, 'linked_by' => $request->user()->id]);
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]); DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
$desk->event(DB::table('desk_cases')->where('id', $id)->first(), $request->user(), 'document_linked', ['document_id' => $documentId, 'source' => $data['source_reference'], 'consent' => true]); $desk->event(DB::table('desk_cases')->where('id', $id)->first(), $request->user(), 'document_linked', ['document_id' => $document->id, 'link_id' => $linkId, 'source' => $source, 'consent' => true, 'field_key' => $data['field_key'] ?? null, 'source_link_id' => $sourceLink?->id,
'reused_source' => $sourceLink ? ['source_reference' => $sourceLink->source_reference, 'category' => $sourceLink->category, 'stage' => $sourceLink->stage, 'valid_until' => $sourceLink->valid_until, 'document_id' => $document->id, 'version_no' => $document->version_no, 'sha256' => trim($document->sha256)] : null], $row);
}); });
} catch (\Throwable $e) { } catch (\Throwable $e) {
if ($key) { if ($key) {
@@ -310,7 +430,10 @@ class VirtualDeskController extends Controller
ScanDocumentForMalware::dispatch($newId)->afterCommit(); ScanDocumentForMalware::dispatch($newId)->afterCommit();
} }
return $request->expectsJson() ? response()->json(['ok' => true]) : back()->with('success', 'Documento privado associado; consulte o estado da análise.'); $available = $this->documents($id, $request->user());
return $request->expectsJson() ? response()->json(['ok' => true, 'link_id' => $linkId, 'reused_link' => $reusedLink, 'case_version' => (int) DB::table('desk_cases')->where('id', $id)->value('version'),
'documents' => $available->filter(fn ($d) => ! ($data['request_id'] ?? null) || ! $d->request_id || $d->request_id === $data['request_id'])->values(), 'reusable_documents' => $desk->owns($request->user(), $desk->case($request->user(), $id)) ? $available->values() : []]) : back()->with('success', $reusedLink ? 'Este documento já estava associado; conservou-se a referência registada.' : 'Documento privado associado; consulte o estado da análise.');
} }
public function download(Request $request, string $id, string $document, VirtualDesk $desk): BinaryFileResponse|\Illuminate\Http\Response public function download(Request $request, string $id, string $document, VirtualDesk $desk): BinaryFileResponse|\Illuminate\Http\Response
@@ -2,6 +2,8 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Services\DeskServiceAvailability;
use App\Services\DeskServiceEditor;
use App\Services\VirtualDeskInstallation; use App\Services\VirtualDeskInstallation;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -79,19 +81,22 @@ class VirtualDeskInstallationController extends Controller
DB::select('select pg_advisory_xact_lock(261008, 2)'); DB::select('select pg_advisory_xact_lock(261008, 2)');
$definition = config('virtual-desk.services.'.$data['code']); $definition = config('virtual-desk.services.'.$data['code']);
$existing = DB::table('desk_service_versions')->where('code', $data['code'])->orderByDesc('version')->first(); $existing = DB::table('desk_service_versions')->where('code', $data['code'])->orderByDesc('version')->first();
if ($existing && $existing->status === 'published' && json_decode($existing->definition, true) === $definition) { if ($existing && $existing->status === 'published' && app(DeskServiceEditor::class)->sameDefinition(json_decode($existing->definition, true, 512, JSON_THROW_ON_ERROR), $definition)) {
return $existing; return $existing;
} }
$id = (string) Str::uuid(); $id = (string) Str::uuid();
$effective = app(DeskServiceAvailability::class)->scheduled() ? now()->toDateString() : null;
DB::table('desk_service_versions')->insert(['id' => $id, 'code' => $data['code'], 'version' => ($existing->version ?? 0) + 1, 'status' => 'published', DB::table('desk_service_versions')->insert(['id' => $id, 'code' => $data['code'], 'version' => ($existing->version ?? 0) + 1, 'status' => 'published',
...($effective ? ['effective_from' => $effective] : []),
'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')), 'author_id' => $request->user()->id, 'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')), 'author_id' => $request->user()->id,
'published_by' => $request->user()->id, 'published_at' => now(), 'created_at' => now(), 'updated_at' => now()]); 'published_by' => $request->user()->id, 'published_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_service_versions', 'entity_id' => $id, 'actor_user_id' => $request->user()->id, DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_service_versions', 'entity_id' => $id, 'actor_user_id' => $request->user()->id,
'action' => 'internal_service_published', 'after_data' => json_encode(['code' => $data['code'], 'nature' => 'digital_preparation_not_official_form'])]); 'action' => 'internal_service_published', 'after_data' => json_encode(['code' => $data['code'], 'nature' => 'digital_preparation_not_official_form', 'effective_from' => $effective])]);
return DB::table('desk_service_versions')->where('id', $id)->first(); return DB::table('desk_service_versions')->where('id', $id)->first();
}); });
return $request->expectsJson() ? response()->json(['id' => $row->id], 201) : back()->with('success', 'Serviço de preparação interna publicado.'); return $request->expectsJson() ? response()->json(['id' => $row->id, 'effective_from' => $row->effective_from ?? null], 201)
: back()->with('success', 'Serviço de preparação interna publicado'.(($row->effective_from ?? null) ? ' com entrada em vigor em '.$row->effective_from : '').'.');
} }
} }
@@ -3,14 +3,16 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Services\Ai\InvestorGuidanceEvidence; use App\Services\Ai\InvestorGuidanceEvidence;
use App\Services\DeskPaymentEvidence;
use App\Services\VerifiedDocumentBinary;
use App\Services\VirtualDesk; use App\Services\VirtualDesk;
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\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Validation\Rule; use Illuminate\Validation\Rule;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/** Manual operations use the same requests, documents and encrypted audit history. */ /** Manual operations use the same requests, documents and encrypted audit history. */
class VirtualDeskOperationsController extends Controller class VirtualDeskOperationsController extends Controller
@@ -25,16 +27,19 @@ class VirtualDeskOperationsController extends Controller
abort_unless(! $desk->owns($request->user(), $case, false) && ($request->user()->can('manage-portal') || ($row && (int) $row->analyst_id === $request->user()->id)), 403); abort_unless(! $desk->owns($request->user(), $case, false) && ($request->user()->can('manage-portal') || ($row && (int) $row->analyst_id === $request->user()->id)), 403);
} }
private function cleanDocument(string $caseId, string $documentId, ?string $requestId): \stdClass private function cleanDocument(string $caseId, string $documentId, ?string $requestId, ?string $linkId = null): \stdClass
{ {
$doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id') $doc = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.case_id', $caseId)->where('d.id', $documentId)->whereNull('d.deleted_at') ->where('l.case_id', $caseId)->where('d.id', $documentId)->whereNull('d.deleted_at')
->when($linkId, fn ($q) => $q->where('l.id', $linkId))
->where(fn ($q) => $q->whereNull('l.request_id')->when($requestId, fn ($p) => $p->orWhere('l.request_id', $requestId))) ->where(fn ($q) => $q->whereNull('l.request_id')->when($requestId, fn ($p) => $p->orWhere('l.request_id', $requestId)))
->first(['d.*', 'l.id as link_id']); ->first(['d.*', 'l.id as link_id']);
abort_unless($doc !== null && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 422, 'Documento indisponível para conferência: verifique autorização, integridade e análise antimalware.'); abort_unless($doc !== null && $doc->status === 'active' && $doc->malware_scan_status === 'clean' && trim($doc->sha256) === $doc->malware_scanned_sha256, 422, 'Documento indisponível para conferência: verifique autorização, integridade e análise antimalware.');
$path = realpath(Storage::disk('local')->path($doc->storage_key)); try {
$root = realpath(Storage::disk('local')->path('')); app(VerifiedDocumentBinary::class)->respond($doc);
abort_unless($path && $root && str_starts_with($path, $root.DIRECTORY_SEPARATOR) && is_file($path) && is_string($hash = hash_file('sha256', $path)) && hash_equals(trim($doc->sha256), $hash), 422, 'O ficheiro original ou a sua integridade não pôde ser confirmado.'); } catch (HttpExceptionInterface) {
abort(422, 'O original, a sua autorização ou integridade não pôde ser confirmado.');
}
return $doc; return $doc;
} }
@@ -43,15 +48,16 @@ class VirtualDeskOperationsController extends Controller
{ {
$data = $request->validate(['version' => 'required|integer|min:1', 'request_id' => 'nullable|uuid', 'outcome' => 'required|in:internal_verified,internal_issue,contradiction_identified', 'what_checked' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000', 'supports' => 'nullable|array|max:4', 'supports.*' => ['string', Rule::in(InvestorGuidanceEvidence::FIELDS)]]); $data = $request->validate(['version' => 'required|integer|min:1', 'request_id' => 'nullable|uuid', 'outcome' => 'required|in:internal_verified,internal_issue,contradiction_identified', 'what_checked' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000', 'supports' => 'nullable|array|max:4', 'supports.*' => ['string', Rule::in(InvestorGuidanceEvidence::FIELDS)]]);
DB::transaction(function () use ($request, $id, $document, $desk, $data) { DB::transaction(function () use ($request, $id, $document, $desk, $data) {
$case = $desk->case($request->user(), $id, false, true); $desk->case($request->user(), $id);
abort_unless(! $case->closed_at && (int) $case->version === (int) $data['version'], 409);
$link = DB::table('desk_documents')->where('case_id', $id)->where('id', $document)->first(); $link = DB::table('desk_documents')->where('case_id', $id)->where('id', $document)->first();
abort_unless($link !== null, 404); abort_unless($link !== null, 404);
$requestId = $link->request_id ?: ($data['request_id'] ?? null); $requestId = $link->request_id ?: ($data['request_id'] ?? null);
$row = $requestId ? $desk->request($request->user(), $requestId, false, true) : null; $row = $requestId ? $desk->request($request->user(), $requestId, false, true) : null;
$case = $desk->case($request->user(), $id, false, true);
abort_unless(! $case->closed_at && (int) $case->version === (int) $data['version'], 409);
abort_if($row && $row->case_id !== $id, 422); abort_if($row && $row->case_id !== $id, 422);
$this->reviewer($request, $desk, $case, $row); $this->reviewer($request, $desk, $case, $row);
$doc = $this->cleanDocument($id, $link->document_id, $requestId); $doc = $this->cleanDocument($id, $link->document_id, $requestId, $link->id);
DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]); DB::table('desk_cases')->where('id', $id)->update(['version' => $case->version + 1, 'updated_at' => now()]);
$desk->event(DB::table('desk_cases')->where('id', $id)->firstOrFail(), $request->user(), 'document_reviewed', [ $desk->event(DB::table('desk_cases')->where('id', $id)->firstOrFail(), $request->user(), 'document_reviewed', [
...$data, 'document_id' => $doc->id, 'link_id' => $link->id, 'sha256' => trim($doc->sha256), 'document_version' => (int) $doc->version_no, 'reviewer_id' => $request->user()->id, ...$data, 'document_id' => $doc->id, 'link_id' => $link->id, 'sha256' => trim($doc->sha256), 'document_version' => (int) $doc->version_no, 'reviewer_id' => $request->user()->id,
@@ -64,26 +70,58 @@ class VirtualDeskOperationsController extends Controller
public function payment(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse public function payment(Request $request, string $id, VirtualDesk $desk): JsonResponse|RedirectResponse
{ {
$data = $request->validate(['reference' => 'required|string|max:255', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/', 'numeric', 'gt:0'], 'currency' => 'required|in:MZN,USD,EUR', 'source_reference' => 'required|string|min:3|max:3000', 'document_id' => 'nullable|uuid', 'consent' => 'accepted']); $data = $request->validate(['reference' => 'required|string|max:255', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/', 'numeric', 'gt:0'], 'currency' => 'required|in:MZN,USD,EUR', 'source_reference' => 'required|string|min:3|max:3000', 'document_id' => 'nullable|uuid', 'document_link_id' => 'nullable|uuid', 'consent' => 'accepted']);
DB::transaction(function () use ($request, $id, $desk, $data) { DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, true, true); $row = $desk->request($request->user(), $id, true, true);
$case = $desk->case($request->user(), $row->case_id); $case = $desk->case($request->user(), $row->case_id, true, true);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409); abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
if ($data['document_id'] ?? null) { $evidence = app(DeskPaymentEvidence::class)->snapshot($case->id, $id, $data);
abort_unless(DB::table('desk_documents')->where('case_id', $case->id)->where('document_id', $data['document_id'])->where(fn ($q) => $q->whereNull('request_id')->orWhere('request_id', $id))->exists(), 422);
}
// References are supplied by the investor; no bank reference or fee is generated. // References are supplied by the investor; no bank reference or fee is generated.
DB::select('SELECT pg_advisory_xact_lock(hashtext(?))', ['virtual-desk-payment:'.$data['reference']]);
$existing = DB::table('desk_payments')->where('reference', $data['reference'])->first(); $existing = DB::table('desk_payments')->where('reference', $data['reference'])->first();
if ($existing) { if ($existing) {
$parts = explode('.', (string) $data['amount']); $parts = explode('.', (string) $data['amount']);
$amount = (ltrim($parts[0], '0') ?: '0').'.'.str_pad($parts[1] ?? '', 2, '0'); $amount = (ltrim($parts[0], '0') ?: '0').'.'.str_pad($parts[1] ?? '', 2, '0');
abort_unless($existing->request_id === $id && (string) $existing->amount === $amount && $existing->currency === $data['currency'] && $existing->source_reference === $data['source_reference'] && $existing->document_id === ($data['document_id'] ?? null), 409); $saved = app(DeskPaymentEvidence::class)->forRequest($id)[$existing->id] ?? null;
abort_unless($existing->request_id === $id && (string) $existing->amount === $amount && $existing->currency === $data['currency'] && $existing->source_reference === $data['source_reference'] && $existing->document_id === ($evidence['document_id'] ?? null)
&& (! ($data['document_link_id'] ?? null) || ($saved['link_id'] ?? null) === $data['document_link_id']), 409);
return; return;
} }
$payment = (string) Str::uuid(); $payment = (string) Str::uuid();
DB::table('desk_payments')->insert(['id' => $payment, 'request_id' => $id, 'reference' => $data['reference'], 'amount' => $data['amount'], 'currency' => $data['currency'], 'source_reference' => $data['source_reference'], 'document_id' => $data['document_id'] ?? null, 'status' => 'pending', 'created_at' => now(), 'updated_at' => now()]); DB::table('desk_payments')->insert(['id' => $payment, 'request_id' => $id, 'reference' => $data['reference'], 'amount' => $data['amount'], 'currency' => $data['currency'], 'source_reference' => $data['source_reference'], 'document_id' => $evidence['document_id'] ?? null, 'status' => 'pending', 'created_at' => now(), 'updated_at' => now()]);
$desk->event($case, $request->user(), 'payment_declared', ['payment_id' => $payment, 'consent' => true, 'scope' => 'manual_declaration_no_bank_confirmation'], $row); $desk->event($case, $request->user(), 'payment_declared', ['payment_id' => $payment, 'payment_version' => 1, 'document_evidence' => $evidence, 'consent' => true, 'scope' => 'manual_declaration_no_bank_confirmation'], $row);
});
return $this->result($request);
}
public function paymentDocument(Request $request, string $id, string $payment, VirtualDesk $desk): JsonResponse|RedirectResponse
{
$data = $request->validate(['version' => 'required|integer|min:1', 'document_link_id' => 'required|uuid', 'reason' => 'required|string|min:3|max:3000', 'consent' => 'accepted', 'client_key' => 'required|uuid']);
$data['version'] = (int) $data['version'];
$data['consent'] = true;
DB::transaction(function () use ($request, $id, $payment, $desk, $data) {
$row = $desk->request($request->user(), $id, true, true);
$case = $desk->case($request->user(), $row->case_id, true, true);
abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
$record = DB::table('desk_payments')->where('id', $payment)->where('request_id', $id)->lockForUpdate()->first();
abort_unless($record !== null, 404);
foreach (DB::table('desk_events')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('action', 'payment_document_linked')->get(['payload']) as $event) {
$saved = $desk->decode($event->payload);
if (($saved['client_key'] ?? null) === $data['client_key']) {
abort_unless(($saved['payment_id'] ?? null) === $payment && ($saved['operation'] ?? null) === $data, 409, 'A operação já foi utilizada com outros dados. Inicie uma nova associação.');
return;
}
}
abort_unless((int) $record->version === (int) $data['version'] && in_array($record->status, ['pending', 'internal_issue'], true), 409, 'O registo mudou ou já está conferido. Actualize antes de associar outro comprovativo.');
$evidence = app(DeskPaymentEvidence::class)->snapshot($case->id, $id, $data);
abort_unless($evidence !== null, 422);
$previous = app(DeskPaymentEvidence::class)->forRequest($id)[$payment] ?? null;
DB::table('desk_payments')->where('id', $payment)->update(['document_id' => $evidence['document_id'], 'status' => 'pending', 'reason' => null, 'verified_by' => null, 'version' => $record->version + 1, 'updated_at' => now()]);
$desk->event($case, $request->user(), 'payment_document_linked', ['payment_id' => $payment, 'payment_version' => $record->version + 1, 'previous_document_id' => $record->document_id, 'previous_document_evidence' => $previous,
'document_evidence' => $evidence, 'client_key' => $data['client_key'], 'operation' => $data, 'reason' => $data['reason'], 'consent' => true, 'scope' => 'documentary_correction_no_amount_change_or_payment_confirmation'], $row);
}); });
return $this->result($request); return $this->result($request);
@@ -94,19 +132,21 @@ class VirtualDeskOperationsController extends Controller
$data = $request->validate(['version' => 'required|integer|min:1', 'status' => 'required|in:internal_verified,internal_issue', 'reason' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000']); $data = $request->validate(['version' => 'required|integer|min:1', 'status' => 'required|in:internal_verified,internal_issue', 'reason' => 'required|string|min:3|max:3000', 'evidence' => 'required|string|min:3|max:5000']);
DB::transaction(function () use ($request, $id, $payment, $desk, $data) { DB::transaction(function () use ($request, $id, $payment, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true); $row = $desk->request($request->user(), $id, false, true);
$case = $desk->case($request->user(), $row->case_id); $case = $desk->case($request->user(), $row->case_id, false, true);
$this->reviewer($request, $desk, $case, $row); $this->reviewer($request, $desk, $case, $row);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409); abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
$record = DB::table('desk_payments')->where('request_id', $id)->where('id', $payment)->lockForUpdate()->first(); $record = DB::table('desk_payments')->where('request_id', $id)->where('id', $payment)->lockForUpdate()->first();
abort_unless($record !== null, 404); abort_unless($record !== null, 404);
abort_unless((int) $record->version === (int) $data['version'], 409); abort_unless((int) $record->version === (int) $data['version'], 409);
$evidence = app(DeskPaymentEvidence::class)->forRequest($id)[$payment] ?? null;
$doc = null; $doc = null;
if ($data['status'] === 'internal_verified') { if ($data['status'] === 'internal_verified') {
abort_unless($record->document_id, 422, 'A conferência exige um comprovativo autorizado.'); abort_unless($record->document_id, 422, 'A conferência exige um comprovativo autorizado.');
$doc = $this->cleanDocument($case->id, $record->document_id, $id); $doc = $this->cleanDocument($case->id, $record->document_id, $id, $evidence['link_id'] ?? null);
abort_if($evidence && ($evidence['document_id'] !== $doc->id || $evidence['document_version'] !== (int) $doc->version_no || ! hash_equals($evidence['sha256'], trim($doc->sha256))), 422, 'O original já não corresponde ao comprovativo associado. Registe a correcção antes de conferir.');
} }
DB::table('desk_payments')->where('id', $payment)->update(['status' => $data['status'], 'reason' => $data['reason'], 'verified_by' => $request->user()->id, 'version' => $record->version + 1, 'updated_at' => now()]); DB::table('desk_payments')->where('id', $payment)->update(['status' => $data['status'], 'reason' => $data['reason'], 'verified_by' => $request->user()->id, 'version' => $record->version + 1, 'updated_at' => now()]);
$desk->event($case, $request->user(), 'payment_reviewed', [...$data, 'payment_id' => $payment, 'document_id' => $doc?->id, 'sha256' => $doc ? trim($doc->sha256) : null, 'reviewer_id' => $request->user()->id, 'scope' => 'internal_proof_check_no_bank_confirmation'], $row); $desk->event($case, $request->user(), 'payment_reviewed', [...$data, 'payment_id' => $payment, 'payment_version' => $record->version + 1, 'document_id' => $record->document_id, 'document_evidence' => $evidence, 'sha256' => $doc ? trim($doc->sha256) : null, 'reviewer_id' => $request->user()->id, 'scope' => 'internal_proof_check_no_bank_confirmation'], $row);
}); });
return $this->result($request); return $this->result($request);
@@ -117,9 +157,9 @@ class VirtualDeskOperationsController extends Controller
$data = $request->validate(['channel' => 'required|in:phone,email,sms,whatsapp,in_person', 'direction' => 'required|in:received,sent', 'occurred_at' => 'required|date|before_or_equal:now', 'summary' => 'required|string|min:3|max:5000', 'evidence' => 'required|string|min:3|max:3000', 'client_key' => 'required|uuid']); $data = $request->validate(['channel' => 'required|in:phone,email,sms,whatsapp,in_person', 'direction' => 'required|in:received,sent', 'occurred_at' => 'required|date|before_or_equal:now', 'summary' => 'required|string|min:3|max:5000', 'evidence' => 'required|string|min:3|max:3000', 'client_key' => 'required|uuid']);
DB::transaction(function () use ($request, $id, $desk, $data) { DB::transaction(function () use ($request, $id, $desk, $data) {
$row = $desk->request($request->user(), $id, false, true); $row = $desk->request($request->user(), $id, false, true);
$case = $desk->case($request->user(), $row->case_id); $case = $desk->case($request->user(), $row->case_id, false, true);
abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403); abort_unless($desk->owns($request->user(), $case) || $request->user()->can('manage-portal') || (int) $row->analyst_id === $request->user()->id, 403);
abort_if(in_array($row->status, ['closed', 'cancelled'], true), 409); abort_if($case->closed_at || in_array($row->status, ['closed', 'cancelled'], true), 409);
foreach (DB::table('desk_events')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('action', 'manual_communication_recorded')->get(['payload']) as $event) { foreach (DB::table('desk_events')->where('request_id', $id)->where('actor_id', $request->user()->id)->where('action', 'manual_communication_recorded')->get(['payload']) as $event) {
$saved = $desk->decode($event->payload); $saved = $desk->decode($event->payload);
if (($saved['client_key'] ?? null) === $data['client_key']) { if (($saved['client_key'] ?? null) === $data['client_key']) {
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Middleware;
use App\Services\PublicSearchMetrics;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class CollectPublicSearchMetrics
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$candidate = $request->attributes->get(PublicSearchMetrics::ATTRIBUTE);
$request->attributes->remove(PublicSearchMetrics::ATTRIBUTE);
$prefetch = str_contains(strtolower($request->header('Purpose', '').' '.$request->header('Sec-Purpose', '')), 'prefetch') || $request->header('X-Inertia-Prefetch') === 'true';
$privacySignal = $request->header('DNT') === '1' || $request->header('Sec-GPC') === '1';
if ($request->isMethod('GET') && $response->getStatusCode() === 200 && ! $prefetch && ! $privacySignal && is_array($candidate) && isset($candidate['channel'], $candidate['empty']) && is_string($candidate['channel']) && is_bool($candidate['empty'])) {
app(PublicSearchMetrics::class)->record($candidate['channel'], $candidate['empty']);
}
return $response;
}
}
@@ -24,7 +24,7 @@ final class EnsureScopedPortalAdministration
'management/economic-references/lot-01', 'management/economic-references/lot-01/*', 'management/economic-references/lot-01', 'management/economic-references/lot-01/*',
'management/education', 'management/education/*', 'management/investment/references', 'management/investment/references/*', 'api/v1/investment/admin/references', 'api/v1/investment/admin/references/*', 'management/education', 'management/education/*', 'management/investment/references', 'management/investment/references/*', 'api/v1/investment/admin/references', 'api/v1/investment/admin/references/*',
'management/investment/zones', 'management/investment/zones/*', 'api/v2/investment/admin/zones', 'api/v2/investment/admin/zones/*', 'management/investment/zones', 'management/investment/zones/*', 'api/v2/investment/admin/zones', 'api/v2/investment/admin/zones/*',
'management/balcao/atribuicoes', 'management/balcao/atribuicoes/*', 'management/balcao/servicos', 'management/balcao/atribuicoes', 'management/balcao/atribuicoes/*', 'management/balcao/servicos', 'management/balcao/servicos/*',
'management/balcao/fontes') || ($request->isMethod('GET') && $path === 'management/balcao-install'); 'management/balcao/fontes') || ($request->isMethod('GET') && $path === 'management/balcao-install');
$fiscal = $request->is('api/v2/investment/admin/tax-rules', 'api/v2/investment/admin/tax-rules/*', $fiscal = $request->is('api/v2/investment/admin/tax-rules', 'api/v2/investment/admin/tax-rules/*',
'api/v2/investment/admin/tax-rule-sources', 'management/investment/tax-rules/*'); 'api/v2/investment/admin/tax-rule-sources', 'management/investment/tax-rules/*');
@@ -4,6 +4,7 @@ namespace App\Http\Middleware;
use App\Models\ExistingBusiness; use App\Models\ExistingBusiness;
use App\Services\ContentManagement; use App\Services\ContentManagement;
use App\Services\FundingProgrammes;
use App\Services\InvestorPath; use App\Services\InvestorPath;
use App\Services\LegacyContent; use App\Services\LegacyContent;
use App\Services\OpportunityManagement; use App\Services\OpportunityManagement;
@@ -56,7 +57,10 @@ class HandleInertiaRequests extends Middleware
return [ return [
...parent::share($request), ...parent::share($request),
'name' => config('app.name'), 'name' => config('app.name'),
'administrationNavigation' => app(ContentManagement::class)->administrationNavigation($request->user(), $contentManagementAccess),
'dashboardNavigation' => app(ContentManagement::class)->dashboardNavigation($request->user(), $contentManagementAccess),
'procurementEnabled' => app(Procurement::class)->available(), 'procurementEnabled' => app(Procurement::class)->available(),
'fundingEnabled' => app(FundingProgrammes::class)->installed(),
'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, 'contentManagementHref' => $contentManagementAccess !== [] ? '/gestao-conteudos' : null,
@@ -23,6 +23,14 @@ class ProtectProfileOpportunity
} }
if ($request->user() && $id !== null && Schema::hasColumn('opportunities', 'owner_user_id')) { if ($request->user() && $id !== null && Schema::hasColumn('opportunities', 'owner_user_id')) {
$record = Opportunity::withTrashed()->find($id); $record = Opportunity::withTrashed()->find($id);
if ($record?->isPrivateOfferPreparation()) {
app(PortalProfileAccess::class)->authorize($request->user(), $request->isMethod('GET') ? 'view' : 'edit', $record);
if ($request->isMethod('GET') && $request->is('minhas-oportunidades/*/edit', 'minhas-oportunidades/*/view', 'management/opportunities/*/edit', 'management/opportunities/*/view')) {
return redirect('/minhas-oportunidades/ofertas/'.$record->id)->header('Cache-Control', 'private, no-store');
}
// Contact registration reuses the CRM master and its fresh-MFA gate.
abort_unless($request->isMethod('POST') && $request->is('minhas-oportunidades/*/contacts'), 403, 'Use a preparação privada da oferta.');
}
if ($record && $record->owner_user_id === null && ! $request->isMethod('GET')) { if ($record && $record->owner_user_id === null && ! $request->isMethod('GET')) {
abort_unless(app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()), 403, 'O papel v1 não contorna os controlos através de um registo legado.'); abort_unless(app(PortalProfileAccess::class)->legacyWriteAllowed($request->user()), 403, 'O papel v1 não contorna os controlos através de um registo legado.');
} }
+10 -1
View File
@@ -2,6 +2,8 @@
namespace App\Http\Middleware; namespace App\Http\Middleware;
use App\Services\PortalProfileAccess;
use App\Services\TerritorialRegistry;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Crypt;
@@ -24,9 +26,16 @@ class TerritorialRequest
} else { } else {
abort_unless($request->user()->can('manage-portal') && $request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403); abort_unless($request->user()->can('manage-portal') && $request->user()->two_factor_confirmed_at && $request->user()->two_factor_secret, 403);
$role = $request->is('*/transitions') ? match ($request->input('action')) { $role = $request->is('*/transitions') ? match ($request->input('action')) {
'approved', 'rejected' => 'reviewers', 'published', 'archived', 'revoked' => 'publishers', default => 'editors', 'in_review', 'approved', 'rejected' => 'reviewers', 'published', 'archived', 'withdrawn', 'revoked' => 'publishers', default => 'editors',
} : 'editors'; } : 'editors';
abort_unless(in_array(strtolower($request->user()->email), config('territorial.'.$role, []), true), 403, 'Função editorial não atribuída.'); abort_unless(in_array(strtolower($request->user()->email), config('territorial.'.$role, []), true), 403, 'Função editorial não atribuída.');
if ($request->is('api/v1/geo/territories*')) {
app(TerritorialRegistry::class)->ensureWriteMode($request->route('id'));
if (config('editorial_workflow.territorial_versions')) {
abort_unless(app(PortalProfileAccess::class)->mfa($request->user())
&& ! app(PortalProfileAccess::class)->has($request->user(), 'auditor'), 403, 'MFA válido necessário.');
}
}
$key = $request->header('Idempotency-Key', ''); $key = $request->header('Idempotency-Key', '');
abort_unless(Str::isUuid($key), 422, 'Idempotency-Key UUID obrigatório.'); abort_unless(Str::isUuid($key), 422, 'Idempotency-Key UUID obrigatório.');
$scope = $request->method().':'.$request->path(); $scope = $request->method().':'.$request->path();
@@ -37,13 +37,14 @@ class StoreSimulationFormDraftRequest extends FormRequest
'contact_province', 'contact_district', 'preferred_channel', 'contact_province', 'contact_district', 'preferred_channel',
]; ];
$economic = [ $economic = [
'preparation_step', 'planning_assumptions_snapshot', 'initial_budget_snapshot', 'fiscal_tools_selection', 'planned_funding', 'requested_funding', 'approved_funding', 'planning_loan',
'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', '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',
'project_duration_years', 'existing_project_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'project_duration_years', 'existing_project_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id',
'site_known', 'latitude', 'longitude', 'area_required', 'area_unit', 'special_zone_id', 'land_status', 'site_known', 'latitude', 'longitude', 'area_required', 'area_unit', 'special_zone_id', 'land_status',
'infrastructure_needs', 'currency', 'total_investment', 'own_capital', 'domestic_debt', 'foreign_debt', 'infrastructure_needs', 'investment_budget_min', 'investment_budget_max', 'currency', 'total_investment', 'own_capital', 'domestic_debt', 'foreign_debt',
'grants', 'secured_amount', 'sought_amount', 'annual_revenue', 'annual_operating_costs', 'expected_profit', 'grants', 'secured_amount', 'sought_amount', 'annual_revenue', 'annual_operating_costs', 'expected_profit',
'financing_term_months', 'funds_origin_countries', 'direct_jobs', 'indirect_jobs', 'national_jobs', 'financing_term_months', 'funds_origin_countries', 'direct_jobs', 'indirect_jobs', 'national_jobs',
'foreign_jobs', 'skills_needed', 'local_content_percentage', 'exports_value', 'import_substitution_value', 'foreign_jobs', 'skills_needed', 'local_content_percentage', 'exports_value', 'import_substitution_value',
@@ -69,6 +70,15 @@ class StoreSimulationFormDraftRequest extends FormRequest
'economic_snapshot.purpose' => ['required', 'in:simulate_only,own_investment,seek_investor,seek_partner,present_opportunity,request_facilitation'], 'economic_snapshot.purpose' => ['required', 'in:simulate_only,own_investment,seek_investor,seek_partner,present_opportunity,request_facilitation'],
'economic_snapshot.journey_type' => ['nullable', 'in:personal,small_business,company,investor'], 'economic_snapshot.journey_type' => ['nullable', 'in:personal,small_business,company,investor'],
'economic_snapshot.detail_level' => ['nullable', 'in:simple,advanced'], 'economic_snapshot.detail_level' => ['nullable', 'in:simple,advanced'],
'economic_snapshot.preparation_step' => ['nullable', 'in:purpose,market,investment,financial,operating,cashflow,tax,review,promoter,identity,project,location,impact,opportunity,documents,team,scenarios,procedures'],
'economic_snapshot.initial_budget_snapshot' => ['nullable', 'string', 'max:12000'],
'economic_snapshot.planning_assumptions_snapshot' => ['nullable', 'string', 'max:12000'],
'economic_snapshot.fiscal_tools_selection' => ['nullable', 'array', 'max:80'],
'economic_snapshot.fiscal_tools_selection.*' => ['string', 'max:100', 'regex:/^(tax|iva|irpc):[a-z_]+$/'],
'economic_snapshot.planned_funding' => ['nullable', 'numeric', 'min:0'],
'economic_snapshot.requested_funding' => ['nullable', 'numeric', 'min:0'],
'economic_snapshot.approved_funding' => ['nullable', 'numeric', 'min:0'],
'economic_snapshot.planning_loan' => ['nullable', 'in:yes,no,unknown'],
'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.cashflow_snapshot' => ['nullable', 'string', 'max:20000'],
@@ -126,6 +136,8 @@ class StoreSimulationFormDraftRequest extends FormRequest
'economic_snapshot.publication_authorisation' => ['nullable', 'in:yes,no'], 'economic_snapshot.publication_authorisation' => ['nullable', 'in:yes,no'],
'economic_snapshot.public_fields_confirmation' => ['nullable', 'in:yes,no'], 'economic_snapshot.public_fields_confirmation' => ['nullable', 'in:yes,no'],
'economic_snapshot.validation_acknowledged' => ['nullable', 'in:yes,no'], 'economic_snapshot.validation_acknowledged' => ['nullable', 'in:yes,no'],
'economic_snapshot.investment_budget_min' => ['nullable', 'numeric', 'min:0'],
'economic_snapshot.investment_budget_max' => ['nullable', 'numeric', 'min:0', \Illuminate\Validation\Rule::when($this->filled('economic_snapshot.investment_budget_min'), 'gte:economic_snapshot.investment_budget_min')],
'economic_snapshot.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'], 'economic_snapshot.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
'economic_snapshot.opportunity_currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'], 'economic_snapshot.opportunity_currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/'],
'economic_snapshot.rate' => ['nullable', 'numeric', 'between:0,100'], 'economic_snapshot.rate' => ['nullable', 'numeric', 'between:0,100'],
@@ -288,6 +300,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
$allowedLabels = [ $allowedLabels = [
'economic_snapshot.selection_labels' => ['journey_type', 'detail_level', 'purpose', 'manifestation_type', 'preferred_language', 'project_type', 'maturity_stage', 'sector_id', 'activity_id', 'economic_snapshot.selection_labels' => ['journey_type', 'detail_level', 'purpose', 'manifestation_type', 'preferred_language', 'project_type', 'maturity_stage', 'sector_id', 'activity_id',
'customer_validation_status', 'location_assessment_status', 'cost_estimate_status', 'receivables_timing_status', 'funding_status', 'planning_loan',
'province_id', 'district_id', 'admin_post_id', 'locality_id', 'site_known', 'land_status', 'infrastructure_needs', 'province_id', 'district_id', 'admin_post_id', 'locality_id', 'site_known', 'land_status', 'infrastructure_needs',
'area_unit', 'required_documents', 'opportunity_currency', 'area_unit', 'required_documents', 'opportunity_currency',
'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',
@@ -303,7 +316,7 @@ class StoreSimulationFormDraftRequest extends FormRequest
$labels = is_array($label) ? $label : [$label]; $labels = is_array($label) ? $label : [$label];
if (! is_string($field) || ! in_array($field, $allowedFields, true) || count($labels) > 100 if (! is_string($field) || ! in_array($field, $allowedFields, true) || count($labels) > 100
|| collect($labels)->contains(fn ($value) => ! is_string($value) || mb_strlen($value) > 255)) { || collect($labels)->contains(fn ($value) => ! is_string($value) || mb_strlen($value) > 255)) {
$validator->errors()->add($path, 'Os rótulos de selecção não são válidos.'); $validator->errors()->add($path.'.'.(is_string($field) ? $field : 'draft'), 'Não foi possível guardar a opção apresentada neste campo. Volte a seleccioná-la; os outros dados do rascunho foram preservados.');
break 2; break 2;
} }
} }
@@ -3,6 +3,7 @@
namespace App\Http\Resources; namespace App\Http\Resources;
use App\Services\ExistingBusinessClassification; use App\Services\ExistingBusinessClassification;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -24,6 +25,10 @@ class PublicBusinessOpportunityResource extends JsonResource
'amount_max' => data_get($this->resource, 'amount_max'), 'amount_max' => data_get($this->resource, 'amount_max'),
'available_percentage' => data_get($this->resource, 'available_percentage'), 'available_percentage' => data_get($this->resource, 'available_percentage'),
'published_at' => data_get($this->resource, 'published_at'), 'published_at' => data_get($this->resource, 'published_at'),
'distance_km' => $this->resource->getAttribute('distance_km') !== null ? round((float) $this->resource->getAttribute('distance_km'), 1) : null,
'location_recorded_at' => $this->resource->getAttribute('location_recorded_at') ? CarbonImmutable::parse($this->resource->getAttribute('location_recorded_at'))->toIso8601String() : null,
'location_source_reference' => $this->resource->getAttribute('location_source_reference'),
'location_source_date' => $this->resource->getAttribute('location_source_date'),
'sector' => $this->whenLoaded('sector', fn () => data_get($this->resource, 'sector')?->only(['name', 'slug'])), 'sector' => $this->whenLoaded('sector', fn () => data_get($this->resource, 'sector')?->only(['name', 'slug'])),
'province' => $this->resource->getAttribute('province'), 'province' => $this->resource->getAttribute('province'),
'district' => $this->resource->getAttribute('district'), 'district' => $this->resource->getAttribute('district'),
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Jobs;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\PortalEditorialWorkflow;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/** Existing email transport and operational allowlist; no confidential payload. */
final class NotifyPrivateOfferDecision implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public int $timeout = 30;
public function __construct(public string $noticeId) {}
/** @return list<int> */
public function backoff(): array
{
return [60, 300, 900];
}
public function handle(): void
{
if (! config('portal.notifications_enabled')) {
return;
}
$notice = DB::table('portal_editorial_notifications')->where('id', $this->noticeId)->first();
$user = $notice ? User::query()->whereKey($notice->user_id)->first() : null;
$record = $notice ? Opportunity::query()->whereKey($notice->opportunity_id)->first() : null;
if (! $notice || ! $user || ! $record?->isPrivateOfferPreparation()
|| ! in_array($user->email, config('portal.notification_recipients', []), true)
|| ! app(PortalEditorialWorkflow::class)->visibleNotice($user, $notice)) {
return;
}
$body = 'Existe uma actualização na revisão privada da oferta '.$record->reference.'. Consulte a decisão e a versão na área protegida: '.url('/minhas-oportunidades/ofertas/'.$record->id);
Mail::raw($body, fn ($message) => $message->to($user->email)->subject('Actualização da oferta — '.$record->reference));
}
}
+112 -15
View File
@@ -2,7 +2,9 @@
namespace App\Jobs; namespace App\Jobs;
use App\Services\Malware\DocumentScanAttempts;
use App\Services\Malware\MalwareScanner; use App\Services\Malware\MalwareScanner;
use App\Services\OpportunityTechnicalIncidents;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
@@ -11,6 +13,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Throwable; use Throwable;
@@ -25,7 +28,28 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
public int $uniqueFor = 600; public int $uniqueFor = 600;
public function __construct(public readonly string $documentId) {} public ?string $executionId = null;
/** @var array<string,mixed>|null */
public ?array $opportunityContext = null;
/** @param array<string,mixed>|null $opportunityContext */
public function __construct(public readonly string $documentId, ?array $opportunityContext = null)
{
$this->executionId = (string) Str::uuid();
$this->opportunityContext = $opportunityContext;
}
/** Queue UUID also supports payloads serialized before executionId existed. */
public function runIdentifier(): string
{
if ($this->executionId !== null) {
return $this->executionId;
}
$queued = $this->job?->uuid();
return is_string($queued) && Str::isUuid($queued) ? $queued : ($this->executionId = (string) Str::uuid());
}
public function uniqueId(): string public function uniqueId(): string
{ {
@@ -51,11 +75,20 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
if ($row->malware_scan_status === 'infected') { if ($row->malware_scan_status === 'infected') {
return null; return null;
} }
$attempts = app(DocumentScanAttempts::class);
if ($attempts->completed($row->id, $this->runIdentifier())) {
return null;
}
if ($row->malware_scan_status === 'scanning' && $attempts->owns($row, $this->runIdentifier(), (int) $this->attempts())) {
return null;
}
$attempt = $attempts->start($row, $this->runIdentifier(), (int) $this->attempts());
DB::table('documents')->where('id', $this->documentId)->update([ DB::table('documents')->where('id', $this->documentId)->update([
'status' => 'quarantined', 'malware_scan_status' => 'scanning', 'malware_failure_reason' => null, 'status' => 'quarantined', 'malware_scan_status' => 'scanning', 'malware_failure_reason' => null,
'malware_scan_attempts' => DB::raw('malware_scan_attempts + 1'), 'updated_at' => now(), 'malware_scan_attempts' => $attempt, 'updated_at' => now(),
]); ]);
$row->malware_scan_attempts = $attempt;
return $row; return $row;
}); });
@@ -69,22 +102,32 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
$root = $disk->path(''); $root = $disk->path('');
$path = $disk->path($document->storage_key); $path = $disk->path($document->storage_key);
$temporary = null; $temporary = null;
$operationFailed = false;
try { try {
if (($document->storage_encryption ?? null) === 'laravel') { if (($document->storage_encryption ?? null) === 'laravel') {
$temporary = tempnam($root, 'scan-private-'); $temporary = tempnam($root, 'scan-private-');
if ($temporary === false) { if ($temporary === false) {
throw new \RuntimeException('Private scan workspace unavailable'); throw new \RuntimeException('Private scan workspace unavailable');
} }
chmod($temporary, 0600); if (! @chmod($temporary, 0600)) {
file_put_contents($temporary, Crypt::decryptString($disk->get($document->storage_key))); throw new \RuntimeException('Private scan workspace permissions unavailable');
}
$plain = Crypt::decryptString($disk->get($document->storage_key));
if (file_put_contents($temporary, $plain) !== strlen($plain)) {
throw new \RuntimeException('Private scan workspace write incomplete');
}
unset($plain);
$path = $temporary; $path = $temporary;
} }
$beforeHash = $this->fileHash($path); $beforeHash = $this->fileHash($path);
if ($beforeHash === null || ! hash_equals(trim($document->sha256), $beforeHash)) { if ($beforeHash === null || ! hash_equals(trim($document->sha256), $beforeHash)) {
$this->record($document, [ $applied = $this->record($document, [
'result' => 'inconclusive', 'reason_code' => 'file_hash_mismatch', 'engine' => 'ClamAV', 'result' => 'inconclusive', 'reason_code' => 'file_hash_mismatch', 'engine' => 'not_run',
'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => 0, 'detail' => null, 'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => 0, 'detail' => null,
], $startedAt, 'inconclusive'); ], $startedAt, 'inconclusive');
if ($applied) {
$this->notify('scan_inconclusive');
}
return; return;
} }
@@ -99,10 +142,29 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
} }
$result['file_sha256'] = $afterHash; $result['file_sha256'] = $afterHash;
$this->record($document, $result, $startedAt, $result['result']); $applied = $this->record($document, $result, $startedAt, $result['result']);
if (in_array($applied, ['inconclusive', 'failed'], true)) {
$this->notify($applied === 'failed' ? 'scan_worker_failed' : 'scan_inconclusive');
}
} catch (Throwable $error) {
$operationFailed = true;
throw $error;
} finally { } finally {
if (is_string($temporary) && is_file($temporary)) { if (is_string($temporary) && is_file($temporary)) {
unlink($temporary); try {
$removed = @unlink($temporary);
} catch (Throwable) {
$removed = false;
}
if (! $removed) {
try {
Log::warning('Private scan workspace cleanup requires verification.', ['reference' => $this->runIdentifier(), 'error_code' => 'scan_cleanup_unconfirmed']);
} catch (Throwable) {
}
if (! $operationFailed) {
$this->notify('scan_cleanup_unconfirmed');
}
}
} }
} }
} }
@@ -113,11 +175,38 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
if (! $document || $document->status === 'deleted' || $document->deleted_at !== null) { if (! $document || $document->status === 'deleted' || $document->deleted_at !== null) {
return; return;
} }
if ($document->malware_scan_status === 'pending') {
// A failure before claiming the row cannot overwrite another scan result.
$this->notify('scan_worker_failed');
$this->record($document, [ return;
'result' => 'failed', 'reason_code' => 'scanner_unavailable_after_retries', 'engine' => 'ClamAV', }
if ($document->malware_scan_status !== 'scanning' || ! app(DocumentScanAttempts::class)->owns($document, $this->runIdentifier(), (int) $this->attempts())) {
return;
}
$descriptor = app(DocumentScanAttempts::class)->descriptor($document, $this->runIdentifier(), (int) $this->attempts());
if ($descriptor === null) {
$this->notify('scan_worker_failed');
return;
}
$document->sha256 = $descriptor['sha256'];
$document->size_bytes = $descriptor['size_bytes'];
$applied = $this->record($document, [
'result' => 'failed', 'reason_code' => 'scan_failed_after_retries', 'engine' => 'unknown',
'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => null, 'detail' => null, 'engine_version' => 'unknown', 'signatures_at' => null, 'duration_ms' => null, 'detail' => null,
], now(), 'failed'); ], now(), 'failed');
if ($applied) {
$this->notify('scan_worker_failed');
}
}
private function notify(string $errorCode): void
{
if ($this->opportunityContext !== null) {
app(OpportunityTechnicalIncidents::class)->recordScan($this->opportunityContext, $this->runIdentifier(), $errorCode);
}
} }
private function fileHash(string $path): ?string private function fileHash(string $path): ?string
@@ -130,12 +219,17 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
} }
/** @param array<string,mixed> $result */ /** @param array<string,mixed> $result */
private function record(\stdClass $document, array $result, \DateTimeInterface $startedAt, string $state): void private function record(\stdClass $document, array $result, \DateTimeInterface $startedAt, string $state): ?string
{ {
DB::transaction(function () use ($document, $result, $startedAt, $state): void { return DB::transaction(function () use ($document, $result, $startedAt, $state): ?string {
$locked = DB::table('documents')->where('id', $this->documentId)->lockForUpdate()->first(); $locked = DB::table('documents')->where('id', $this->documentId)->lockForUpdate()->first();
if (! $locked || $locked->status === 'deleted' || $locked->deleted_at !== null) { if (! $locked || $locked->status === 'deleted' || $locked->deleted_at !== null) {
return; return null;
}
if ($locked->malware_scan_status !== 'scanning' || ! app(DocumentScanAttempts::class)->owns($locked, $this->runIdentifier(), (int) $this->attempts(), (int) $document->malware_scan_attempts)) {
app(DocumentScanAttempts::class)->discarded($locked, $this->runIdentifier(), (int) $this->attempts(), (int) $document->malware_scan_attempts);
return null;
} }
$sameBytes = hash_equals(trim($document->sha256), trim((string) $locked->sha256)); $sameBytes = hash_equals(trim($document->sha256), trim((string) $locked->sha256));
@@ -160,13 +254,16 @@ class ScanDocumentForMalware implements ShouldBeUnique, ShouldQueue
'updated_at' => $finishedAt, 'updated_at' => $finishedAt,
]); ]);
DB::table('document_malware_scans')->insert([ DB::table('document_malware_scans')->insert([
'id' => $scanId, 'document_id' => $this->documentId, 'file_sha256' => trim($locked->sha256), 'id' => $scanId, 'document_id' => $this->documentId, 'file_sha256' => trim($document->sha256),
'result' => $finalState, 'reason_code' => $reason, 'result' => $finalState, 'reason_code' => $reason,
'engine' => $result['engine'] ?? 'ClamAV', 'engine_version' => $result['engine_version'] ?? 'unknown', 'engine' => $result['engine'] ?? 'ClamAV', 'engine_version' => $result['engine_version'] ?? 'unknown',
'signatures_at' => $result['signatures_at'] ?? null, 'started_at' => $startedAt, 'signatures_at' => $result['signatures_at'] ?? null, 'started_at' => $startedAt,
'finished_at' => $finishedAt, 'duration_ms' => $result['duration_ms'] ?? null, 'finished_at' => $finishedAt, 'duration_ms' => $result['duration_ms'] ?? null,
'file_size_bytes' => $locked->size_bytes ?? null, 'created_at' => $finishedAt, 'updated_at' => $finishedAt, 'file_size_bytes' => $document->size_bytes ?? null, 'created_at' => $finishedAt, 'updated_at' => $finishedAt,
]); ]);
app(DocumentScanAttempts::class)->finish($document, $this->runIdentifier(), (int) $this->attempts(), $scanId, $state === 'failed');
return $finalState;
}); });
} }
} }
+21
View File
@@ -3,6 +3,8 @@
namespace App\Models; namespace App\Models;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Schema;
/** /**
* @property string|null $lead_id * @property string|null $lead_id
@@ -13,4 +15,23 @@ class CrmTask extends CrmRecord
protected $table = 'tasks'; protected $table = 'tasks';
protected $casts = ['due_at' => 'immutable_datetime']; protected $casts = ['due_at' => 'immutable_datetime'];
/**
* @param Builder<CrmTask> $query
* @return Builder<CrmTask>
*/
public function scopeAvailableForWork(Builder $query): Builder
{
$query->whereNull('tasks.deleted_at')->whereIn('tasks.status', ['open', 'in_progress']);
if (Schema::hasColumn('tasks', 'desk_case_id')) {
if (Schema::hasColumn('desk_cases', 'closed_at')) {
$query->where(fn ($q) => $q->whereNull('tasks.desk_case_id')->orWhereExists(fn ($desk) => $desk->selectRaw('1')->from('desk_cases')
->whereColumn('desk_cases.id', 'tasks.desk_case_id')->whereNull('desk_cases.closed_at')));
} else {
$query->whereNull('tasks.desk_case_id');
}
}
return $query;
}
} }
+18
View File
@@ -30,6 +30,23 @@ class Opportunity extends Model
{ {
use SoftDeletes; use SoftDeletes;
public function isPrivateOfferPreparation(): bool
{
return isset($this->workflow_context['private_offer_preparation']);
}
protected static function booted(): void
{
static::saving(function (self $record) {
$original = $record->getRawOriginal('workflow_context');
$wasPrivate = is_string($original) && isset(json_decode($original, true)['private_offer_preparation']);
abort_if($wasPrivate && ! $record->isPrivateOfferPreparation(), 403, 'A preparação privada não pode ser convertida neste percurso.');
if ($record->isPrivateOfferPreparation()) {
abort_unless($record->status === 'draft' && $record->published_at === null, 403, 'A publicação de Ofertas não está disponível nesta fase.');
}
});
}
protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once', 'owner_user_id', 'organization_id', 'workflow_context']; protected $hidden = ['management_draft', 'management_creation_key', 'management_version', 'first_submitted_at', 'management_closed_once', 'owner_user_id', 'organization_id', 'workflow_context'];
protected $appends = ['maturity_catalogue_version']; protected $appends = ['maturity_catalogue_version'];
@@ -115,6 +132,7 @@ class Opportunity extends Model
public function scopePublished(Builder $query): Builder public function scopePublished(Builder $query): Builder
{ {
if (Schema::hasColumn('opportunities', 'workflow_context')) { if (Schema::hasColumn('opportunities', 'workflow_context')) {
$query->whereNull('workflow_context->private_offer_preparation');
$query->where(fn ($q) => $q->whereNull('owner_user_id')->orWhere('workflow_context->publication->visibility', 'public')); $query->where(fn ($q) => $q->whereNull('owner_user_id')->orWhere('workflow_context->publication->visibility', 'public'));
} }
+2
View File
@@ -81,6 +81,8 @@ class AppServiceProvider extends ServiceProvider
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_pt');
Cache::forget('portal_home_sector_organization_v1_en'); Cache::forget('portal_home_sector_organization_v1_en');
Cache::forget('portal_home_territorial_v2_pt');
Cache::forget('portal_home_territorial_v2_en');
}; };
$model::saved($invalidate); $model::saved($invalidate);
$model::deleted($invalidate); $model::deleted($invalidate);
+3 -2
View File
@@ -69,7 +69,8 @@ final class AssistiveRules
foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereNull('owner_user_id')->orderBy('id')->limit(20)->get(['id']) as $lead) { foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereNull('owner_user_id')->orderBy('id')->limit(20)->get(['id']) as $lead) {
$alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_owner', 'source_url' => '/management/crm/leads/'.$lead->id]; $alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_owner', 'source_url' => '/management/crm/leads/'.$lead->id];
} }
foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['new', 'qualified'])->whereDoesntHave('tasks', fn ($q) => $q->whereIn('status', ['open', 'in_progress'])) foreach (Lead::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['new', 'qualified'])
->whereNotExists(CrmTask::availableForWork()->whereColumn('tasks.lead_id', 'leads.id')->selectRaw('1')->toBase())
->orderBy('id')->limit(20)->get(['id']) as $lead) { ->orderBy('id')->limit(20)->get(['id']) as $lead) {
$alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_next_action', 'source_url' => '/management/crm/leads/'.$lead->id]; $alerts[] = ['record_type' => 'lead', 'record_id' => $lead->id, 'rule' => 'missing_next_action', 'source_url' => '/management/crm/leads/'.$lead->id];
} }
@@ -91,7 +92,7 @@ final class AssistiveRules
/** @return list<array<string, mixed>> */ /** @return list<array<string, mixed>> */
public function sla(): array public function sla(): array
{ {
return array_values(CrmTask::whereIn('data_classification', ['public', 'internal'])->whereIn('status', ['open', 'in_progress'])->where('due_at', '<', now())->orderBy('due_at')->limit(50) return array_values(CrmTask::whereIn('data_classification', ['public', 'internal'])->availableForWork()->where('due_at', '<', now())->orderBy('due_at')->limit(50)
->get()->map(fn ($task) => [ ->get()->map(fn ($task) => [
'record_type' => 'task', 'record_id' => $task->id, 'rule' => 'overdue_open_task', 'record_type' => 'task', 'record_id' => $task->id, 'rule' => 'overdue_open_task',
'due_at' => $task->getAttribute('due_at')?->toIso8601String(), 'lead_id' => $task->lead_id, 'due_at' => $task->getAttribute('due_at')?->toIso8601String(), 'lead_id' => $task->lead_id,
+10 -2
View File
@@ -4,8 +4,10 @@ namespace App\Services\Ai;
use App\Models\CrmTask; use App\Models\CrmTask;
use App\Models\InvestmentSubmission; use App\Models\InvestmentSubmission;
use App\Models\Lead;
use App\Models\SimulationFormDraft; use App\Models\SimulationFormDraft;
use App\Models\User; use App\Models\User;
use App\Services\CrmNextAction;
use App\Services\InvestmentGeography; use App\Services\InvestmentGeography;
use App\Services\VirtualDesk; use App\Services\VirtualDesk;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
@@ -152,7 +154,7 @@ class InvestorGuidance
->get(['t.id', 't.title', 't.status', 't.due_at', 't.version_no', 't.desk_request_id', 't.accepted_by', 't.accepted_at', 't.assignee_user_id', 'u.name as assignee_name', 't.external_sync_status']); ->get(['t.id', 't.title', 't.status', 't.due_at', 't.version_no', 't.desk_request_id', 't.accepted_by', 't.accepted_at', 't.assignee_user_id', 'u.name as assignee_name', 't.external_sync_status']);
return ['version' => $case->version, 'rules_version' => InvestorGuidanceRules::VERSION, 'computed_at' => now()->toIso8601String(), return ['version' => $case->version, 'rules_version' => InvestorGuidanceRules::VERSION, 'computed_at' => now()->toIso8601String(),
...$context, 'phases' => $phases, 'tasks' => $tasks, 'actions' => $actions, 'can_write' => $this->desk->owns($actor, $case), ...$context, 'phases' => $phases, 'tasks' => $tasks, 'actions' => $actions, 'can_write' => ! $case->closed_at && $this->desk->owns($actor, $case), 'can_update_tasks' => ! $case->closed_at,
'external_ai' => ['status' => 'not_configured', 'model' => null, 'consulted' => []], 'external_ai' => ['status' => 'not_configured', 'model' => null, 'consulted' => []],
'calculator_versions' => ['business_financial_plan' => hash_file('sha256', resource_path('js/lib/business-financial-plan.ts')), 'financial_calculators' => hash_file('sha256', resource_path('js/lib/financial-calculators.ts')), 'project_dossier' => hash_file('sha256', resource_path('js/lib/project-dossier.ts'))], 'calculator_versions' => ['business_financial_plan' => hash_file('sha256', resource_path('js/lib/business-financial-plan.ts')), 'financial_calculators' => hash_file('sha256', resource_path('js/lib/financial-calculators.ts')), 'project_dossier' => hash_file('sha256', resource_path('js/lib/project-dossier.ts'))],
'crm' => ['internal' => 'available', 'external' => 'out_of_scope', 'reason' => 'O acompanhamento usa o CRM interno existente. A sincronização externa está fora desta fase; nenhum contacto, mensagem ou documento é transmitido.']]; 'crm' => ['internal' => 'available', 'external' => 'out_of_scope', 'reason' => 'O acompanhamento usa o CRM interno existente. A sincronização externa está fora desta fase; nenhum contacto, mensagem ou documento é transmitido.']];
@@ -235,10 +237,16 @@ class InvestorGuidance
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])], $data = Validator::make($input, ['version' => 'required|integer|min:1', 'status' => ['required', Rule::in(['open', 'in_progress', 'done', 'cancelled'])],
'reason' => 'required|string|min:3|max:3000', 'assignee_user_id' => 'nullable|integer|exists:users,id', 'due_at' => 'nullable|date|after:now'])->validate(); 'reason' => 'required|string|min:3|max:3000', 'assignee_user_id' => 'nullable|integer|exists:users,id', 'due_at' => 'nullable|date|after:now'])->validate();
DB::transaction(function () use ($actor, $id, $taskId, $data) { DB::transaction(function () use ($actor, $id, $taskId, $data) {
$case = $this->desk->case($actor, $id); $case = $this->desk->case($actor, $id, false, true);
$this->desk->assertOpen($case);
$candidate = CrmTask::where('desk_case_id', $id)->whereKey($taskId)->firstOrFail();
// Match CRM lock order, so two response channels cannot finish each other's only replacement.
$lead = $candidate->lead_id === null ? null : Lead::withTrashed()->whereKey($candidate->lead_id)->lockForUpdate()->firstOrFail();
$task = CrmTask::where('desk_case_id', $id)->whereKey($taskId)->lockForUpdate()->firstOrFail(); $task = CrmTask::where('desk_case_id', $id)->whereKey($taskId)->lockForUpdate()->firstOrFail();
abort_unless($task->lead_id === $candidate->lead_id, 409, 'O acompanhamento associado mudou. Recupere a tarefa actual.');
abort_unless($actor->can('manage-portal') || (int) $task->getAttribute('assignee_user_id') === $actor->id, 403); abort_unless($actor->can('manage-portal') || (int) $task->getAttribute('assignee_user_id') === $actor->id, 403);
abort_unless((int) $task->getAttribute('version_no') === (int) $data['version'], 409); abort_unless((int) $task->getAttribute('version_no') === (int) $data['version'], 409);
app(CrmNextAction::class)->assertMayFinish($lead, $task, $data['status']);
$updates = ['status' => $data['status'], 'version_no' => $data['version'] + 1]; $updates = ['status' => $data['status'], 'version_no' => $data['version'] + 1];
if ($data['assignee_user_id'] ?? null) { if ($data['assignee_user_id'] ?? null) {
abort_unless($actor->can('manage-portal'), 403); abort_unless($actor->can('manage-portal'), 403);
+42 -5
View File
@@ -15,7 +15,7 @@ final class BusinessFormSchema
'proponent_type' => ['step' => 1, 'pt' => 'Quem apresenta a oportunidade?', 'en' => 'Who is presenting the opportunity?', 'type' => 'select', 'max' => 30, 'options' => ['organization' => 'Empresa ou organização / Company or organization', 'sole_trader' => 'Empresário em nome individual / Sole trader', 'person' => 'Pessoa singular / Individual', 'public_entity' => 'Entidade pública / Public entity']], 'proponent_type' => ['step' => 1, 'pt' => 'Quem apresenta a oportunidade?', 'en' => 'Who is presenting the opportunity?', 'type' => 'select', 'max' => 30, 'options' => ['organization' => 'Empresa ou organização / Company or organization', 'sole_trader' => 'Empresário em nome individual / Sole trader', 'person' => 'Pessoa singular / Individual', 'public_entity' => 'Entidade pública / Public entity']],
'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200], 'proponent_name' => ['step' => 1, 'pt' => 'Nome ou denominação', 'en' => 'Name', 'type' => 'text', 'max' => 200],
'country' => ['step' => 1, 'pt' => 'País de origem ou constituição', 'en' => 'Country of origin or incorporation', 'type' => 'country', 'max' => 100], 'country' => ['step' => 1, 'pt' => 'País de origem ou constituição', 'en' => 'Country of origin or incorporation', 'type' => 'country', 'max' => 100],
'declared_origin_country_code' => ['step' => 1, 'pt' => 'País de origem declarado desta solicitação (opcional)', 'en' => 'Declared country of origin of this request (optional)', 'type' => 'country', 'max' => 2], 'declared_origin_country_code' => ['step' => 1, 'pt' => 'País de origem do pedido (opcional)', 'en' => 'Country from which you submit this request (optional)', 'type' => 'country', 'max' => 2],
'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador (interno, quando aplicável)', 'en' => 'NUIT or identifier (internal, when applicable)', 'type' => 'text', 'max' => 50], 'tax_identifier' => ['step' => 1, 'pt' => 'NUIT ou identificador (interno, quando aplicável)', 'en' => 'NUIT or identifier (internal, when applicable)', 'type' => 'text', 'max' => 50],
'contact_name' => ['step' => 1, 'pt' => 'Nome da pessoa de contacto', 'en' => 'Contact person name', 'type' => 'text', 'max' => 200], 'contact_name' => ['step' => 1, 'pt' => 'Nome da pessoa de contacto', 'en' => 'Contact person name', 'type' => 'text', 'max' => 200],
'contact_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254], 'contact_email' => ['step' => 1, 'pt' => 'Correio electrónico (indique email ou telefone)', 'en' => 'Email (provide email or phone)', 'type' => 'email', 'max' => 254],
@@ -23,8 +23,8 @@ final class BusinessFormSchema
'contact_preference' => ['step' => 1, 'pt' => 'Preferência de contacto', 'en' => 'Contact preference', 'type' => 'select', 'max' => 30, 'options' => ['through_portal' => 'Receber pedidos através da InvestMoz', 'approved_business_contact' => 'Mostrar contacto empresarial aprovado']], 'contact_preference' => ['step' => 1, 'pt' => 'Preferência de contacto', 'en' => 'Contact preference', 'type' => 'select', 'max' => 30, 'options' => ['through_portal' => 'Receber pedidos através da InvestMoz', 'approved_business_contact' => 'Mostrar contacto empresarial aprovado']],
'acting_capacity' => ['step' => 2, 'pt' => 'Qualidade em que actua', 'en' => 'Acting capacity', 'type' => 'select', 'max' => 30, 'options' => ['holder' => 'Titular / Holder', 'representative' => 'Representante / Representative']], 'acting_capacity' => ['step' => 2, 'pt' => 'Qualidade em que actua', 'en' => 'Acting capacity', 'type' => 'select', 'max' => 30, 'options' => ['holder' => 'Titular / Holder', 'representative' => 'Representante / Representative']],
'declared_holder' => ['step' => 2, 'pt' => 'Entidade ou pessoa representada', 'en' => 'Entity or person represented', 'type' => 'text', 'max' => 200], 'declared_holder' => ['step' => 2, 'pt' => 'Entidade ou pessoa representada', 'en' => 'Entity or person represented', 'type' => 'text', 'max' => 200],
'mandate_reference' => ['step' => 2, 'pt' => 'Referência do documento de autorização', 'en' => 'Authorization document reference', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]], 'mandate_reference' => ['step' => 2, 'pt' => 'Número ou referência da autorização de representação', 'en' => 'Representation authorization number or reference', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
'mandate_document_reference' => ['step' => 2, 'pt' => 'Referência interna do documento de autorização (não carregue aqui)', 'en' => 'Internal authorization document reference (do not upload here)', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]], 'mandate_document_reference' => ['step' => 2, 'pt' => 'Referência do comprovativo de representação no portal', 'en' => 'Reference of representation evidence in the portal', 'type' => 'text', 'max' => 500, 'when' => ['acting_capacity' => ['representative']]],
'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10, 'when' => ['acting_capacity' => ['representative']]], 'mandate_valid_until' => ['step' => 2, 'pt' => 'Validade do mandato', 'en' => 'Mandate expiry', 'type' => 'date', 'max' => 10, 'when' => ['acting_capacity' => ['representative']]],
'disclosure_scope' => ['step' => 2, 'pt' => 'Limites da autorização de divulgação', 'en' => 'Limits of disclosure authorization', 'type' => 'textarea', 'max' => 2000, 'when' => ['acting_capacity' => ['representative']]], 'disclosure_scope' => ['step' => 2, 'pt' => 'Limites da autorização de divulgação', 'en' => 'Limits of disclosure authorization', 'type' => 'textarea', 'max' => 2000, 'when' => ['acting_capacity' => ['representative']]],
'legitimacy_declaration' => ['step' => 2, 'pt' => 'Declaro legitimidade para esta submissão', 'en' => 'I declare authority to submit', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim / Yes', 'no' => 'Não / No']], 'legitimacy_declaration' => ['step' => 2, 'pt' => 'Declaro legitimidade para esta submissão', 'en' => 'I declare authority to submit', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim / Yes', 'no' => 'Não / No']],
@@ -64,6 +64,7 @@ final class BusinessFormSchema
'location_notes' => ['step' => 5, 'pt' => 'Endereço ou referência (interno)', 'en' => 'Address or reference (internal)', 'type' => 'textarea', 'max' => 2000], 'location_notes' => ['step' => 5, 'pt' => 'Endereço ou referência (interno)', 'en' => 'Address or reference (internal)', 'type' => 'textarea', 'max' => 2000],
'location_unknown' => ['step' => 5, 'pt' => 'Não conheço a localização exacta', 'en' => 'I do not know the exact location', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim', 'no' => 'Não'], 'when' => ['geography_scope' => ['specific', 'multiple']]], 'location_unknown' => ['step' => 5, 'pt' => 'Não conheço a localização exacta', 'en' => 'I do not know the exact location', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim', 'no' => 'Não'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
'disclosure_precision' => ['step' => 5, 'pt' => 'Precisão de divulgação', 'en' => 'Disclosure precision', 'type' => 'select', 'max' => 30, 'options' => ['exact' => 'Localização exacta (sujeita a aprovação)', 'approximate' => 'Localização aproximada', 'administrative' => 'Apenas território administrativo'], 'when' => ['geography_scope' => ['specific', 'multiple']]], 'disclosure_precision' => ['step' => 5, 'pt' => 'Precisão de divulgação', 'en' => 'Disclosure precision', 'type' => 'select', 'max' => 30, 'options' => ['exact' => 'Localização exacta (sujeita a aprovação)', 'approximate' => 'Localização aproximada', 'administrative' => 'Apenas território administrativo'], 'when' => ['geography_scope' => ['specific', 'multiple']]],
...self::pointFields(),
'asset_notes' => ['step' => 6, 'pt' => 'Resumo dos activos e direitos declarados', 'en' => 'Declared assets and rights summary', 'type' => 'textarea', 'max' => 2000], 'asset_notes' => ['step' => 6, 'pt' => 'Resumo dos activos e direitos declarados', 'en' => 'Declared assets and rights summary', 'type' => 'textarea', 'max' => 2000],
'source_reference' => ['step' => 7, 'pt' => 'Referência da fonte', 'en' => 'Source reference', 'type' => 'textarea', 'max' => 2000], 'source_reference' => ['step' => 7, 'pt' => 'Referência da fonte', 'en' => 'Source reference', 'type' => 'textarea', 'max' => 2000],
'source_provider' => ['step' => 7, 'pt' => 'Quem forneceu os dados?', 'en' => 'Who supplied the information?', 'type' => 'text', 'max' => 500], 'source_provider' => ['step' => 7, 'pt' => 'Quem forneceu os dados?', 'en' => 'Who supplied the information?', 'type' => 'text', 'max' => 500],
@@ -79,8 +80,27 @@ final class BusinessFormSchema
]; ];
} }
/** @return array<string, list<string|\Closure|In>> */ /** @return array<string, array{step:int,pt:string,en:string,type:string,max:int,options?:array<string,string>,when?:array<string,list<string>>}> */
public static function rules(): array private static function pointFields(): array
{
$when = ['geography_scope' => ['specific', 'multiple'], 'disclosure_precision' => ['exact'], 'location_unknown' => ['no']];
$active = [...$when, 'location_point_enabled' => ['yes']];
return [
'location_point_enabled' => ['step' => 5, 'pt' => 'Preparar um ponto exacto para publicação e pesquisa por raio?', 'en' => 'Prepare an exact point for publication and radius searches?', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim — o ponto substituirá a localização primária na publicação aprovada', 'no' => 'Não — conservar o cadastro de localizações existente'], 'when' => $when],
'location_point_territory' => ['step' => 5, 'pt' => 'Localização já declarada a que pertence o ponto primário', 'en' => 'Previously declared location for the primary point', 'type' => 'point_territory', 'max' => 150, 'when' => [...$active, 'geography_scope' => ['multiple']]],
'location_latitude' => ['step' => 5, 'pt' => 'Latitude WGS84 (graus decimais, -90 a 90)', 'en' => 'WGS84 latitude (decimal degrees, -90 to 90)', 'type' => 'decimal', 'max' => 16, 'when' => $active],
'location_longitude' => ['step' => 5, 'pt' => 'Longitude WGS84 (graus decimais, -180 a 180)', 'en' => 'WGS84 longitude (decimal degrees, -180 to 180)', 'type' => 'decimal', 'max' => 16, 'when' => $active],
'location_point_source_mode' => ['step' => 5, 'pt' => 'Fonte das coordenadas', 'en' => 'Coordinate source', 'type' => 'select', 'max' => 20, 'options' => ['listing' => 'Reutilizar referência e data da etapa Fontes, se também sustentam este ponto', 'custom' => 'Indicar uma fonte diferente para o ponto'], 'when' => $active],
'location_point_source_reference' => ['step' => 5, 'pt' => 'Referência da fonte específica do ponto', 'en' => 'Point-specific source reference', 'type' => 'textarea', 'max' => 2000, 'when' => [...$active, 'location_point_source_mode' => ['custom']]],
'location_point_source_date' => ['step' => 5, 'pt' => 'Data dessa fonte (deixe vazio se desconhecida)', 'en' => 'Source date (leave blank if unknown)', 'type' => 'date', 'max' => 10, 'when' => [...$active, 'location_point_source_mode' => ['custom']]],
'location_point_share_source' => ['step' => 5, 'pt' => 'Divulgar também a referência da fonte do ponto?', 'en' => 'Also disclose the point source reference?', 'type' => 'select', 'max' => 3, 'options' => ['yes' => 'Sim — referência sem contactos ou informação reservada, sujeita à publicação aprovada', 'no' => 'Não — manter a referência apenas no processo reservado'], 'when' => $active],
];
}
/** @param array<string,mixed> $payload
* @return array<string, list<string|\Closure|In>> */
public static function rules(array $payload = []): array
{ {
$rules = []; $rules = [];
foreach (self::fields() as $key => $field) { foreach (self::fields() as $key => $field) {
@@ -99,6 +119,23 @@ final class BusinessFormSchema
$rules['payload.investment_total'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/'; $rules['payload.investment_total'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.amount_sought'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/'; $rules['payload.amount_sought'][] = 'regex:/^\d{1,15}(\.\d{1,4})?$/';
$rules['payload.source_date'][] = 'date_format:Y-m-d'; $rules['payload.source_date'][] = 'date_format:Y-m-d';
foreach (['location_latitude', 'location_longitude'] as $coordinate) {
// Numeric rules make Laravel interpret max:16 as a numeric ceiling, not a text limit.
$rules['payload.'.$coordinate] = ['nullable', 'string', function ($attribute, $value, $fail) {
if (strlen((string) $value) > 16) {
$fail('Indique a coordenada com até 16 caracteres.');
}
}];
}
if (app(BusinessPointPublication::class)->applicable($payload)) {
if (($payload['location_point_source_mode'] ?? null) === 'custom') {
$rules['payload.location_point_source_date'][] = 'date_format:Y-m-d';
}
$rules['payload.location_latitude'][] = 'numeric';
$rules['payload.location_latitude'][] = 'between:-90,90';
$rules['payload.location_longitude'][] = 'numeric';
$rules['payload.location_longitude'][] = 'between:-180,180';
}
$rules['payload.official_source_url'][] = 'url'; $rules['payload.official_source_url'][] = 'url';
// 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',
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/** Optional supplement of the approved listing; never grants publication authority. */
final class BusinessPointPublication
{
public function available(): bool
{
return Schema::hasColumn('existing_business_locations', 'public_source_reference');
}
/** @param array<string,mixed> $payload */
public function applicable(array $payload): bool
{
return ($payload['location_point_enabled'] ?? null) === 'yes'
&& in_array($payload['geography_scope'] ?? null, ['specific', 'multiple'], true)
&& ($payload['disclosure_precision'] ?? null) === 'exact'
&& ($payload['location_unknown'] ?? null) === 'no';
}
/** @param array<string,mixed> $payload
* @return list<array<string,mixed>> */
public function paths(array $payload): array
{
if (($payload['geography_scope'] ?? null) === 'specific') {
return [array_intersect_key($payload, InvestmentGeography::FIELDS)];
}
if (($payload['geography_scope'] ?? null) !== 'multiple') {
return [];
}
$rows = json_decode((string) ($payload['locations_json'] ?? ''), true);
return is_array($rows) && array_is_list($rows) ? array_values(array_filter($rows, 'is_array')) : [];
}
/** @param array<string,mixed> $path */
public function pathKey(array $path): string
{
return implode('|', array_map(fn ($field) => (string) ($path[$field] ?? ''), array_keys(InvestmentGeography::FIELDS)));
}
/** @param array<string,mixed> $payload
* @return array<string,mixed>|null */
public function candidate(array $payload): ?array
{
if (! $this->applicable($payload)) {
return null;
}
abort_unless($this->available(), 409, 'O suplemento de localização ainda não está instalado neste destino. O ponto não será publicado.');
$rules = [
'location_unknown' => ['required', 'in:no'],
'location_latitude' => ['required', 'numeric', 'between:-90,90'],
'location_longitude' => ['required', 'numeric', 'between:-180,180'],
'location_point_source_mode' => ['required', 'in:listing,custom'],
'location_point_share_source' => ['nullable', 'in:yes,no'],
'location_point_source_reference' => ['required_if:location_point_source_mode,custom', 'nullable', 'string', 'max:2000'],
'location_point_source_date' => ($payload['location_point_source_mode'] ?? null) === 'custom' ? ['nullable', 'date_format:Y-m-d'] : ['nullable'],
'location_point_territory' => ['required_if:geography_scope,multiple', 'nullable', 'string', 'max:150'],
];
Validator::make($payload, $rules)->validate();
$paths = $this->paths($payload);
$path = ($payload['geography_scope'] ?? null) === 'specific' ? ($paths[0] ?? null)
: collect($paths)->first(fn ($row) => $this->pathKey($row) === $payload['location_point_territory']);
if (! $path || empty($path['province_id'])) {
throw ValidationException::withMessages(['location_point_territory' => 'Seleccione uma das localizações já declaradas para o ponto primário. Não é atribuída uma localização por ordem ou por nome.']);
}
$nodes = app(InvestmentGeography::class)->selection($path);
$listingSource = $payload['location_point_source_mode'] === 'listing';
$source = $listingSource ? ($payload['source_reference'] ?? null) : ($payload['location_point_source_reference'] ?? null);
$date = $listingSource ? ($payload['source_date'] ?? null) : ($payload['location_point_source_date'] ?? null);
Validator::make(['location_point_source_reference' => $source, 'location_point_source_date' => $date], [
'location_point_source_reference' => ['required', 'string', 'max:2000'], 'location_point_source_date' => ['nullable', 'date_format:Y-m-d'],
])->validate();
return ['path' => array_combine(array_keys(InvestmentGeography::FIELDS), array_map(fn ($field) => ($path[$field] ?? null) ?: null, array_keys(InvestmentGeography::FIELDS))),
'reference_snapshot' => array_map(fn ($node) => (array) $node, $nodes),
'latitude' => (float) $payload['location_latitude'], 'longitude' => (float) $payload['location_longitude'],
'source_reference' => $source, 'source_date' => $date ?: null,
'public_source_reference' => ($payload['location_point_share_source'] ?? null) === 'yes' ? $source : null];
}
/** Called only within the existing authorized, locked publication transaction.
* @return array<string,mixed> */
public function publish(ExistingBusiness $business): array
{
$point = $this->candidate($business->payload);
if ($point === null) {
return [];
}
$previous = DB::table('existing_business_locations')->where('existing_business_id', $business->id)->where('is_primary', true)
->select('*')->selectRaw('ST_AsEWKT(geom) AS geometry_snapshot')->first();
$geometry = DB::selectOne('SELECT ST_AsEWKT(ST_SetSRID(ST_MakePoint(?::float8, ?::float8),4326)) AS value', [$point['longitude'], $point['latitude']])->value;
$values = [...$point['path'], 'precision_level' => 'exact', 'is_public' => true,
'geom' => $geometry,
'public_source_reference' => $point['public_source_reference'], 'source_date' => $point['source_date'],
'source_system' => 'portal-business-form', 'source_payload_version' => $business->version_no + 1, 'updated_at' => now()];
if ($previous) {
DB::table('existing_business_locations')->where('id', $previous->id)->update($values);
} else {
DB::table('existing_business_locations')->insert([...$values, 'id' => (string) Str::uuid(), 'existing_business_id' => $business->id, 'is_primary' => true, 'created_at' => now()]);
}
return ['point_publication' => ['previous' => $previous ? (array) $previous : null, 'used' => $point,
'business_version' => $business->version_no + 1, 'source' => 'explicit_listing_point_supplement']];
}
/** Private view, only after the listing's normal view authorization.
* @return array<string,mixed>|null */
public function registered(ExistingBusiness $business): ?array
{
$row = DB::table('existing_business_locations')->where('existing_business_id', $business->id)->where('is_primary', true)
->select('id', 'precision_level', 'is_public', 'province_id', 'district_id', 'admin_post_id', 'locality_id')
->selectRaw("geom IS NOT NULL AS has_geometry, CASE WHEN GeometryType(geom)='POINT' THEN ST_Y(geom) END AS latitude, CASE WHEN GeometryType(geom)='POINT' THEN ST_X(geom) END AS longitude")->first();
return $row ? (array) $row : null;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Services;
use App\Models\ExistingBusiness;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class BusinessProximitySearch
{
/** @return array<string,mixed> */
public function origin(string $id): array
{
$row = DB::query()->fromSub(app(PublicBusinessLocations::class)->points(), 'origin_point')
->joinSub(ExistingBusiness::published()->select('id', 'public_title'), 'origin_business', 'origin_business.id', '=', 'origin_point.existing_business_id')
->where('origin_point.existing_business_id', $id)->whereNotNull('origin_point.point')
->select('origin_point.location_recorded_at', 'origin_point.location_source_reference', 'origin_point.location_source_date', 'origin_business.public_title')->selectRaw('ST_AsEWKT(origin_point.point) AS ewkt')->first();
if (! $row) {
throw ValidationException::withMessages(['near_business' => 'A ficha de referência não tem um ponto primário público exacto utilizável. Escolha outra referência ou pesquise por área.']);
}
return ['id' => $id, 'title' => $row->public_title, 'ewkt' => $row->ewkt, 'source_reference' => $row->location_source_reference, 'source_date' => $row->location_source_date, 'location_recorded_at' => $row->location_recorded_at ? CarbonImmutable::parse($row->location_recorded_at)->toIso8601String() : null];
}
public function available(string $id): bool
{
return DB::query()->fromSub(app(PublicBusinessLocations::class)->points(), 'point')
->whereIn('existing_business_id', ExistingBusiness::published()->select('id'))
->where('existing_business_id', $id)->whereNotNull('point')->exists();
}
/** @param Builder<ExistingBusiness> $query
* @param array<string,mixed> $origin
* @return array<string,mixed> */
public function constrain(Builder $query, array $origin, float $radius): array
{
$query->leftJoinSub(app(PublicBusinessLocations::class)->points(), 'public_point', 'public_point.existing_business_id', '=', 'existing_businesses.id');
$withPoint = (clone $query)->whereNotNull('public_point.point')->count();
$withoutPoint = (clone $query)->whereNull('public_point.point')->count();
$query->whereNotNull('public_point.point')->whereRaw('ST_DWithin(public_point.point::geography, ST_GeomFromEWKT(?)::geography, ?)', [$origin['ewkt'], $radius * 1000])
->addSelect('public_point.location_recorded_at')
->selectRaw('ST_Distance(public_point.point::geography, ST_GeomFromEWKT(?)::geography) / 1000.0 AS distance_km', [$origin['ewkt']])
->orderBy('distance_km')->orderBy('existing_businesses.id');
return ['origin_id' => $origin['id'], 'origin_title' => $origin['title'], 'radius_km' => $radius, 'origin_recorded_at' => $origin['location_recorded_at'],
'origin_source_reference' => $origin['source_reference'], 'origin_source_date' => $origin['source_date'],
'with_public_point' => $withPoint, 'without_public_point' => $withoutPoint,
'source' => 'Localizações primárias públicas do cadastro de negócios do portal',
'method' => 'Distância geodésica em linha recta entre pontos publicados; não é distância por estrada nem validação da localização real.'];
}
}
+116 -5
View File
@@ -3,10 +3,13 @@
namespace App\Services; namespace App\Services;
use App\Models\EconomicCluster; use App\Models\EconomicCluster;
use App\Models\User;
use Illuminate\Database\Query\Builder; use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Crypt;
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\Validation\ValidationException; use Illuminate\Validation\ValidationException;
final class ClusterCompetitiveness final class ClusterCompetitiveness
@@ -46,6 +49,12 @@ final class ClusterCompetitiveness
public function management(string $cluster): array public function management(string $cluster): array
{ {
$state = $this->current($cluster); $state = $this->current($cluster);
$state['editorial_enabled'] = $this->editorialEnabled();
if (isset($state['workflow'])) {
$record = EconomicCluster::findOrFail($cluster);
$state['workflow']['fresh'] = hash_equals($state['workflow']['hash'], $this->editionHash($record, $state['draft']));
$state['workflow']['independent_required'] = $this->independentRequired($state['workflow']);
}
$state['history'] = $this->events($cluster)->orderByRaw("(after_data->>'version')::integer DESC")->limit(50)->get() $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'], ->map(fn ($event) => ['version' => json_decode($event->after_data, true)['version'],
'action' => $event->action, 'at' => $event->occurred_at, 'actor' => $event->actor_user_id])->all(); 'action' => $event->action, 'at' => $event->occurred_at, 'actor' => $event->actor_user_id])->all();
@@ -106,12 +115,17 @@ final class ClusterCompetitiveness
*/ */
public function change(EconomicCluster $cluster, int $actor, int $expected, string $action, array $input = []): array public function change(EconomicCluster $cluster, int $actor, int $expected, string $action, array $input = []): array
{ {
abort_if(! in_array($action, ['saved', 'restored', 'approved', 'withdrawn'], true) && ! $this->editorialEnabled(), 503, 'Circuito editorial dos clusters ainda não activado.');
return DB::transaction(function () use ($cluster, $actor, $expected, $action, $input) { return DB::transaction(function () use ($cluster, $actor, $expected, $action, $input) {
EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail(); $cluster = EconomicCluster::whereKey($cluster->id)->lockForUpdate()->firstOrFail();
$before = $this->current($cluster->id); $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.'); 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; $state = $before;
if ($action === 'saved') { if ($this->editorialEnabled() || isset($before['workflow'])) {
abort_unless($this->editorialEnabled(), 503, 'Reactive o circuito editorial para continuar esta análise; o histórico e a publicação foram conservados.');
$state = $this->editorialChange($cluster, $actor, $action, $input, $before);
} elseif ($action === 'saved') {
$state['draft'] = $this->validateDraft($input['draft'], $cluster->id); $state['draft'] = $this->validateDraft($input['draft'], $cluster->id);
} elseif ($action === 'restored') { } elseif ($action === 'restored') {
$event = $this->events($cluster->id)->where('after_data->version', $input['revision'])->first(); $event = $this->events($cluster->id)->where('after_data->version', $input['revision'])->first();
@@ -127,13 +141,18 @@ final class ClusterCompetitiveness
throw new \LogicException('Unsupported competitiveness action'); throw new \LogicException('Unsupported competitiveness action');
} }
$state['version']++; $state['version']++;
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'entity_type' => 'economic_clusters', $eventId = (string) Str::uuid();
DB::table('audit_events')->insert(['id' => $eventId, 'source_system' => self::SOURCE, 'entity_type' => 'economic_clusters',
'entity_id' => $cluster->id, 'external_id' => $cluster->id.':'.$state['version'], 'actor_user_id' => $actor, 'entity_id' => $cluster->id, 'external_id' => $cluster->id.':'.$state['version'], 'actor_user_id' => $actor,
'action' => $action, 'data_classification' => 'restricted', 'action' => $action, 'data_classification' => 'restricted',
'before_data' => json_encode(['version' => $before['version']], JSON_THROW_ON_ERROR), 'before_data' => json_encode(['version' => $before['version']], JSON_THROW_ON_ERROR),
'after_data' => json_encode(['version' => $state['version'], 'restored_from' => $input['revision'] ?? null, 'after_data' => json_encode(['version' => $state['version'], 'editorial_state' => $state['workflow']['state'] ?? null, 'restored_from' => $input['revision'] ?? null,
'reason' => Crypt::encryptString($input['reason'] ?? ''), 'reason' => Crypt::encryptString($input['reason'] ?? ''),
'snapshot' => Crypt::encryptString(json_encode($state, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR)]); 'snapshot' => Crypt::encryptString(json_encode($state, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR)]);
if ($this->editorialEnabled()) {
$user = User::findOrFail($actor);
app(PortalEditorialNativeNotices::class)->emit($user, $eventId, $state['workflow']['contributors']);
}
return $this->management($cluster->id); return $this->management($cluster->id);
}); });
@@ -144,9 +163,101 @@ final class ClusterCompetitiveness
*/ */
public function publicData(string $cluster): ?array public function publicData(string $cluster): ?array
{ {
$approved = $this->current($cluster)['approved']; $state = $this->current($cluster);
$approved = isset($state['workflow']) ? $state['published'] : $state['approved'];
// Explicit projection: never return editor identity, approval evidence, history or the unapproved draft. // 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; return $approved ? ['draft' => $approved['draft'], 'version' => $approved['version'], 'at' => $approved['at']] : null;
} }
public function editorialEnabled(): bool
{
return (bool) config('editorial_workflow.cluster_competitiveness');
}
/** @param array<array-key,mixed>|null $draft */
private function editionHash(EconomicCluster $cluster, ?array $draft): string
{
$context = Arr::only($cluster->getAttributes(), ['id', 'code', 'name', 'sector', 'status', 'primary_territory_id', 'territory_version']);
return hash('sha256', json_encode(Arr::sortRecursive(['context' => $context, 'draft' => $draft]), JSON_THROW_ON_ERROR));
}
/** @param array<array-key,mixed> $input
* @param array<array-key,mixed> $state
* @return array<array-key,mixed>
*/
private function editorialChange(EconomicCluster $cluster, int $actorId, string $action, array $input, array $state): array
{
$actor = User::whereKey($actorId)->firstOrFail();
abort_unless($actor->can('manage-portal') && ! app(PortalProfileAccess::class)->has($actor, 'auditor'), 403);
abort_unless(app(PortalProfileAccess::class)->mfa($actor), 403, 'Confirme o MFA na sessão existente.');
if (! isset($state['workflow'])) {
abort_unless(in_array($action, ['saved', 'restored', 'withdrawn'], true), 409, 'Guarde uma edição privada antes de iniciar o novo circuito.');
// An accepted legacy publication remains public; no retrospective approval is invented.
$state['published'] = $state['approved'];
$state['approved'] = null;
$state['workflow'] = ['state' => 'draft', 'edition' => $state['version'], 'contributors' => [], 'approval' => null,
'hash' => $this->editionHash($cluster, $state['draft']), 'independent_required' => false];
}
$workflow = $state['workflow'];
if (in_array($action, ['saved', 'restored'], true)) {
if ($action === 'saved') {
$state['draft'] = $this->validateDraft($input['draft'], $cluster->id);
$restoredContributors = [];
} else {
$event = $this->events($cluster->id)->where('after_data->version', $input['revision'])->first();
abort_unless($event !== null, 404);
$restored = $this->decode($event);
$state['draft'] = $restored['draft'];
$restoredContributors = $restored['workflow']['contributors'] ?? [$event->actor_user_id];
}
$state['approved'] = null;
$state['workflow'] = ['state' => 'draft', 'edition' => $state['version'] + 1,
'contributors' => array_values(array_unique([...($workflow['state'] === 'published' ? [] : $workflow['contributors']), ...$restoredContributors, $actorId])),
'hash' => $this->editionHash($cluster, $state['draft']), 'approval' => null,
'independent_required' => $this->independentRequired($workflow)];
return $state;
}
validator($input, ['reason' => 'required|string|min:10|max:3000'])->validate();
$allowed = ['submitted' => ['draft', 'returned'], 'review_started' => ['submitted'], 'returned' => ['in_review'], 'rejected' => ['in_review'],
'approved' => ['in_review'], 'published' => ['approved'], 'archived' => ['draft', 'submitted', 'in_review', 'returned', 'rejected', 'approved', 'published'], 'withdrawn' => ['draft', 'submitted', 'in_review', 'returned', 'rejected', 'approved', 'published', 'archived']];
abort_unless(isset($allowed[$action]) && in_array($workflow['state'], $allowed[$action], true), 409, 'Transição incompatível com o estado da edição.');
if (in_array($action, ['submitted', 'approved', 'published'], true)) {
abort_unless(hash_equals($workflow['hash'], $this->editionHash($cluster, $state['draft'])), 409, 'O contexto do cluster mudou. Guarde nova edição e volte a conferir.');
}
if ($action === 'submitted' || $action === 'approved') {
$this->assertComplete($state['draft']);
}
if ($action === 'approved') {
abort_if($this->independentRequired($workflow) && in_array($actorId, $workflow['contributors'], true), 403, 'Aprovação independente necessária para esta edição.');
$workflow['approval'] = ['actor' => $actorId, 'edition' => $workflow['edition'], 'hash' => $workflow['hash'], 'at' => now()->toISOString(), 'reason' => $input['reason']];
$state['approved'] = ['draft' => $state['draft'], 'at' => now()->toISOString(), 'actor' => $actorId, 'version' => $state['version'] + 1, 'evidence' => $input['reason']];
}
if ($action === 'published') {
$decision = $workflow['approval'];
abort_unless($decision && $decision['edition'] === $workflow['edition'] && hash_equals($decision['hash'], $workflow['hash']), 422, 'Aprovação desta edição necessária.');
$reviewer = User::whereKey($decision['actor'])->first();
abort_unless($reviewer && $reviewer->can('manage-portal') && ! app(PortalProfileAccess::class)->has($reviewer, 'auditor'), 403, 'Autoridade da aprovação revogada.');
abort_if($this->independentRequired($workflow) && in_array($reviewer->id, $workflow['contributors'], true), 403, 'Aprovação independente necessária.');
$state['published'] = [...$state['approved'], 'at' => now()->toISOString(), 'version' => $state['version'] + 1];
}
if ($action === 'withdrawn' || ($action === 'archived' && $workflow['state'] === 'published')) {
$state['published'] = null;
}
$workflow['state'] = match ($action) {
'submitted' => 'submitted', 'review_started' => 'in_review', 'returned' => 'returned', 'rejected' => 'rejected',
'approved' => 'approved', 'published' => 'published', 'archived' => 'archived', 'withdrawn' => $workflow['state'] === 'published' ? 'archived' : $workflow['state'],
};
$state['workflow'] = $workflow;
return $state;
}
/** @param array<array-key,mixed> $workflow */
private function independentRequired(array $workflow): bool
{
return ($workflow['independent_required'] ?? false) || in_array('cluster_competitiveness', config('editorial_workflow.independent_approval.kinds', []), true);
}
} }
+216
View File
@@ -0,0 +1,216 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
/** Informative comparison, stored in the existing encrypted dossier and event history. */
final class CompanyComparison
{
public const EVENT = 'company_comparison_saved';
public function __construct(private readonly VirtualDesk $desk) {}
/** @return array<string,mixed> */
public function definition(): array
{
return config('company-comparison');
}
/** @param array<array-key,mixed> $questions
* @return list<string> */
private function questionKeys(array $questions): array
{
$keys = [];
foreach (array_keys($questions) as $key) {
if (! is_string($key)) {
throw new \LogicException('Comparison question identifiers must be strings.');
}
$keys[] = $key;
}
return $keys;
}
/** @param array<string,mixed> $input
* @return array<string,string> */
public function answers(array $input): array
{
return $this->normalize($input, $this->definition()['questions']);
}
/** @param array<string,mixed> $input
* @param array<array-key,mixed> $questions
* @return array<string,string> */
private function normalize(array $input, array $questions): array
{
$keys = $this->questionKeys($questions);
$rules = ['answers' => ['sometimes', 'array:'.implode(',', $keys)]];
foreach ($keys as $key) {
$rules['answers.'.$key] = ['nullable', 'string', Rule::in(array_keys($questions[$key]['options']))];
}
$values = Validator::make($input, $rules)->validate()['answers'] ?? [];
$answers = [];
foreach ($keys as $key) {
$answers[$key] = is_string($values[$key] ?? null) ? $values[$key] : 'unknown';
}
return $answers;
}
/** @param array<string,string> $answers
* @return list<string> */
public function active(array $answers): array
{
return in_array($answers['purpose'], ['representation', 'cooperation'], true) ? ['purpose', 'regulated'] : $this->questionKeys($this->definition()['questions']);
}
/** @param array<string,string> $answers
* @return array<string,mixed> */
public function evaluate(array $answers): array
{
$definition = $this->definition();
$active = $this->active($answers);
$pending = array_values(array_filter($active, fn ($key) => $key !== 'preferred' && $answers[$key] === 'unknown'));
$tasks = ['Definir contribuições, gestão, direitos e obrigações no acto a preparar.', 'Conferir os actos e o registo aplicáveis à alternativa escolhida.'];
if (in_array('capital', $active, true)) {
$tasks[] = $answers['capital'] === 'defined' ? 'Conferir os valores e o modo de realização das contribuições definidas.' : 'Definir o capital e as contribuições ainda em falta.';
if (in_array($answers['management'], ['participants', 'both'], true)) {
$tasks[] = 'Definir poderes de gestão e regras de deliberação dos participantes.';
}
if (in_array($answers['management'], ['appointed', 'both'], true)) {
$tasks[] = 'Definir a nomeação, o mandato e a prestação de contas da administração.';
}
if ($answers['responsibility'] !== 'unknown') {
$tasks[] = 'Conferir no registo e no contrato o regime de responsabilidade e as excepções aplicáveis.';
}
if ($answers['listing'] === 'yes') {
$tasks[] = 'Conferir os requisitos específicos da emissão e do mercado pretendido.';
}
}
if ($answers['regulated'] !== 'no') {
$tasks[] = 'Conferir as regras e habilitações específicas da actividade.';
}
$route = match ($answers['purpose']) {
'representation' => 'Compare a representação da sociedade existente; não é uma nova forma societária (artigo 69).',
'cooperation' => 'Prepare o acordo de cooperação; consórcio não é apresentado como uma forma societária autónoma.',
default => 'Compare alternativas para discutir a constituição; não existe uma forma universalmente preferível.',
};
$forms = [];
if (! in_array($answers['purpose'], ['representation', 'cooperation'], true)) {
foreach ($definition['forms'] as $code => $form) {
$constraints = [];
$notes = [];
if ($code === 'individual' && $answers['participants'] === 'several') {
$constraints[] = 'A titularidade individual não corresponde a vários titulares (artigo 3).';
}
if ($code === 'collective' && $answers['participants'] === 'one') {
$constraints[] = 'São necessários pelo menos dois sócios (artigo 264).';
}
if ($code === 'simplified' && $answers['listing'] === 'yes') {
$constraints[] = 'As acções desta forma não podem ser negociadas em Bolsa (artigo 444).';
}
if ($answers['participants'] === 'one' && in_array($code, ['quotas', 'anonymous', 'simplified'], true)) {
$notes[] = 'Comparar a modalidade unipessoal (artigo 257).';
}
if (($answers['participation'] === 'shares' && $code === 'quotas') || ($answers['participation'] === 'quotas' && in_array($code, ['anonymous', 'simplified'], true))) {
$notes[] = 'A estrutura de participação difere da preferência indicada.';
}
if ($answers['participation'] === 'work') {
$notes[] = $code === 'collective' ? 'Conferir a contribuição em trabalho (artigos 264–266).' : 'Conferir como realizar as contribuições pretendidas.';
}
$forms[] = ['code' => $code, ...$form, 'constraints' => $constraints, 'notes' => $notes,
'selected' => $answers['preferred'] === $code, 'source_href' => $definition['source']['url'].'#page='.$form['page']];
}
}
return ['engine_version' => $definition['version'], 'source' => $definition['source'], 'questions' => $definition['questions'], 'active' => $active,
'pending' => $pending, 'route' => $route, 'forms' => $forms, 'preparation' => $tasks,
'scope' => 'Comparação informativa da edição indicada; a actividade, o contrato e as regras especiais continuam a exigir conferência própria.'];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function view(User $actor, string $id, array $input): array
{
$case = $this->desk->case($actor, $id);
$payload = $this->desk->decode($case->payload);
$saved = $payload['company_comparison'] ?? null;
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1'])->validate();
if (! empty($v['revision'])) {
if (array_key_exists('answers', $input)) {
throw ValidationException::withMessages(['answers' => 'Abra a preparação actual para comparar outras respostas; a revisão histórica conserva os dados guardados.']);
}
$row = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->where('id', $v['revision'])->first();
abort_unless($row !== null, 404);
$saved = $this->desk->decode($row->payload)['snapshot'];
}
$answers = array_key_exists('answers', $input) ? $this->answers($input) : ($saved['answers'] ?? $this->answers([]));
$result = array_key_exists('answers', $input) || ! $saved ? $this->evaluate($answers) : $saved['result'];
$events = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)
->when(! empty($v['history_before']), fn ($q) => $q->where('event_order', '<', $v['history_before']))
->orderByDesc('event_order')->limit(26)->get(['id', 'payload', 'event_order']);
$history = $events->take(25)->map(function ($row) {
$snapshot = $this->desk->decode($row->payload)['snapshot'];
return ['id' => $row->id, 'revision' => $snapshot['revision'], 'at' => $snapshot['at'], 'engine_version' => $snapshot['result']['engine_version']];
})->all();
return ['entity_kind' => $payload['investor_path']['context']['promoter_entity']['kind'] ?? ($case->company_id ? 'company' : 'undetermined'), 'case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
'canWrite' => ! $case->closed_at && $this->desk->owns($actor, $case), 'answers' => $answers, 'result' => $result,
'saved' => $saved, 'history' => $history, 'historyNext' => $events->count() > 25 ? $events[24]->event_order : null,
'historical' => ! empty($v['revision']), 'workingCopy' => array_key_exists('answers', $input)];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function save(User $actor, string $id, array $input): array
{
$this->desk->case($actor, $id, true);
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid', 'continue_preparation' => 'nullable|boolean'])->validate();
$v['version'] = (int) $v['version'];
return DB::transaction(function () use ($actor, $id, $v, $input) {
$case = $this->desk->case($actor, $id, true, true);
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->orderByDesc('event_order')->cursor() as $event) {
$data = $this->desk->decode($event->payload);
if ($data['operation_key'] === $v['operation_key']) {
$answers = $this->normalize($input, $data['snapshot']['result']['questions']);
$hash = hash('sha256', json_encode(! empty($v['continue_preparation']) ? [$v['version'], $answers, 'continue_preparation'] : [$v['version'], $answers], JSON_THROW_ON_ERROR));
abort_unless(hash_equals($data['request_hash'], $hash), 409, 'Esta operação já guardou respostas diferentes. Reabra a comparação.');
return ['saved' => true, 'replayed' => true, 'revision' => $data['snapshot']['revision']];
}
}
$answers = $this->answers($input);
$hash = hash('sha256', json_encode(! empty($v['continue_preparation']) ? [$v['version'], $answers, 'continue_preparation'] : [$v['version'], $answers], JSON_THROW_ON_ERROR));
abort_if($case->closed_at || (int) $case->version !== (int) $v['version'], 409, 'O dossier mudou ou foi fechado. Conserve as respostas e recupere a versão actual antes de guardar.');
$payload = $this->desk->decode($case->payload);
if (! empty($v['continue_preparation'])) {
abort_if(in_array($payload['investor_path']['context']['promoter_entity']['kind'] ?? '', ['company', 'organization'], true), 422, 'A entidade existente pode continuar a viabilidade sem preparar nova constituição.');
abort_if(($answers['preferred'] ?? 'unknown') === 'unknown', 422, 'Escolha a alternativa que pretende preparar.');
}
$result = $this->evaluate($answers);
$previous = $payload['company_comparison'] ?? null;
if (empty($v['continue_preparation']) && $previous !== null && $previous['answers'] === $answers && $previous['result'] === $result) {
return ['saved' => true, 'replayed' => false, 'unchanged' => true, 'revision' => $previous['revision']];
}
$snapshot = ['revision' => (int) ($payload['company_comparison']['revision'] ?? 0) + 1, 'answers' => $answers,
'result' => $result, 'at' => now()->toIso8601String(), 'actor_id' => $actor->id];
$payload['company_comparison'] = $snapshot;
$case->version++;
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version, 'updated_at' => now()]);
$this->desk->event($case, $actor, self::EVENT, ['operation_key' => $v['operation_key'], 'request_hash' => $hash, 'snapshot' => $snapshot]);
if (! empty($v['continue_preparation'])) {
app(InvestorContext::class)->setPromoter($actor, $id, ['version' => $case->version, 'operation_key' => (string) \Illuminate\Support\Str::uuid(), 'kind' => 'being_formed']);
}
return ['saved' => true, 'replayed' => false, 'revision' => $snapshot['revision']];
});
}
}
+301
View File
@@ -0,0 +1,301 @@
<?php
namespace App\Services;
use App\Models\User;
use Brick\Math\BigDecimal;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
/** Factual preparation only. Actual contractual exemplars have not been supplied. */
final class CompanyPreparation
{
public const EVENT = 'company_preparation_saved';
public const VERSION = 'company-preparation-1';
public function __construct(private readonly VirtualDesk $desk) {}
/** @return array<string,mixed> */
public function definition(): array
{
return ['version' => self::VERSION, 'forms' => config('company-comparison.forms'),
'roles' => ['subscriber' => 'Titular, sócio ou accionista', 'administrator' => 'Administrador ou gerente', 'representative' => 'Representante', 'beneficial_owner' => 'Beneficiário efectivo declarado'],
'source' => config('company-comparison.source'),
'template_status' => 'source_pending', 'template_notice' => 'Os modelos contratuais não estão disponíveis nesta preparação. Prepare os dados para revisão; esta preparação não é uma minuta contratual, assinatura, registo ou licença.'];
}
/** Reuse only the already-authorized, frozen dossier values, never a fresh master lookup.
* @return array<string,array<string,mixed>> */
private function sources(\stdClass $case): array
{
$payload = $this->desk->decode($case->payload);
$sources = [];
if (! empty($payload['name'])) {
$sources['case_proponent'] = ['name' => $payload['name'], 'kind' => 'person', 'reference' => $case->id,
'version' => $payload['reuse_consent']['date'] ?? 'creation', 'origin' => 'Proponente conservado na criação do dossier'];
}
if (($case->company_id || ! empty($payload['investor_path']['context']['promoter_entity']['id'])) && ! empty($payload['company']['name'])) {
$sources['case_company'] = ['name' => $payload['company']['name'], 'kind' => 'entity', 'reference' => $case->company_id ?? $payload['investor_path']['context']['promoter_entity']['id'],
'version' => $payload['company_version'] ?? null, 'origin' => 'Declaração de empresa conservada no dossier'];
}
return $sources;
}
/** @param array<string,mixed> $input
* @param array<string,mixed>|null $definition
* @return array<string,mixed> */
public function facts(array $input, ?array $definition = null): array
{
$definition ??= $this->definition();
$text = ['nullable', 'string', 'max:2000'];
$number = ['nullable', 'string', 'regex:/^\d{1,18}(?:[.,]\d{1,6})?$/D'];
$rules = ['facts' => ['present', 'array:form,proposed_name,seat,activities,regulated,currency,capital,nominal_value,management,binding,notes,parties'],
'facts.form' => ['nullable', Rule::in(array_keys($definition['forms']))],
'facts.proposed_name' => ['nullable', 'string', 'max:250'], 'facts.seat' => $text, 'facts.activities' => $text,
'facts.regulated' => ['nullable', Rule::in(['unknown', 'yes', 'no'])],
'facts.currency' => ['nullable', 'string', 'regex:/^[A-Z]{3}$/D'], 'facts.capital' => $number, 'facts.nominal_value' => $number,
'facts.management' => $text, 'facts.binding' => $text, 'facts.notes' => $text,
'facts.parties' => ['sometimes', 'array', 'list', 'max:100'],
'facts.parties.*' => ['array:id,name,kind,source,roles,represented_id,cash,in_kind,paid,share_count,work,commitment'],
'facts.parties.*.id' => ['required', 'uuid', 'distinct'], 'facts.parties.*.name' => ['nullable', 'string', 'max:250'],
'facts.parties.*.kind' => ['required', Rule::in(['person', 'entity'])],
'facts.parties.*.source' => ['nullable', Rule::in(['case_proponent', 'case_company'])],
'facts.parties.*.roles' => ['present', 'array', 'list', 'max:4'],
'facts.parties.*.roles.*' => ['string', Rule::in(array_keys($definition['roles']))],
'facts.parties.*.represented_id' => ['nullable', 'uuid'],
'facts.parties.*.cash' => $number, 'facts.parties.*.in_kind' => $number, 'facts.parties.*.paid' => $number,
'facts.parties.*.share_count' => ['nullable', 'string', 'regex:/^\d{1,18}$/D'],
'facts.parties.*.work' => $text, 'facts.parties.*.commitment' => $text];
$v = Validator::make($input, $rules)->validate()['facts'];
$facts = [];
foreach (['form', 'proposed_name', 'seat', 'activities', 'currency', 'management', 'binding', 'notes'] as $key) {
$facts[$key] = $v[$key] ?? null;
}
$facts['regulated'] = $v['regulated'] ?? 'unknown';
foreach (['capital', 'nominal_value'] as $key) {
$facts[$key] = $this->decimal($v[$key] ?? null);
}
$facts['parties'] = [];
foreach ($v['parties'] ?? [] as $party) {
$p = [];
foreach (['id', 'name', 'kind', 'source', 'represented_id', 'work', 'commitment'] as $key) {
$p[$key] = $party[$key] ?? null;
}
$p['roles'] = array_values(array_unique($party['roles']));
sort($p['roles']);
foreach (['cash', 'in_kind', 'paid', 'share_count'] as $key) {
$p[$key] = $this->decimal($party[$key] ?? null);
}
$facts['parties'][] = $p;
}
return $facts;
}
private function decimal(?string $value): ?string
{
return $value === null ? null : (string) BigDecimal::of(str_replace(',', '.', $value))->strippedOfTrailingZeros();
}
/** @param array<string,mixed> $facts
* @param array<string,array<string,mixed>> $sources
* @param array<string,mixed>|null $previous
* @return array<string,mixed> */
private function resolve(array $facts, array $sources, ?array $previous): array
{
foreach ($facts['parties'] as &$party) {
if ($party['source'] !== null) {
$old = null;
foreach ($previous['facts']['parties'] ?? [] as $candidate) {
if ($candidate['id'] === $party['id'] && $candidate['source'] === $party['source']) {
$old = $candidate;
break;
}
}
$source = $old['source_snapshot'] ?? $sources[$party['source']] ?? null;
abort_unless($source !== null, 422, 'A origem seleccionada não existe neste dossier.');
$party['name'] = $source['name'];
$party['kind'] = $source['kind'];
$party['source_snapshot'] = $source;
}
}
return $facts;
}
/** @param array<string,mixed> $facts
* @return array<string,mixed> */
public function review(array $facts): array
{
$issues = [];
foreach (['form' => 'Definir a forma a preparar.', 'proposed_name' => 'Indicar a denominação proposta.', 'seat' => 'Indicar a sede proposta.', 'activities' => 'Descrever as actividades.', 'management' => 'Descrever a administração pretendida.', 'binding' => 'Indicar a forma de obrigar pretendida.'] as $key => $message) {
if (! $facts[$key]) {
$issues[] = $message;
}
}
$subscribers = array_values(array_filter($facts['parties'], fn ($p) => in_array('subscriber', $p['roles'], true)));
if ($subscribers === []) {
$issues[] = 'Identificar os titulares, sócios ou accionistas.';
}
if ($facts['form'] === 'collective' && count($subscribers) < 2) {
$issues[] = 'A forma colectiva exige pelo menos dois sócios (artigo 264).';
}
if ($facts['form'] === 'individual' && count($subscribers) > 1) {
$issues[] = 'A titularidade individual não corresponde a vários titulares.';
}
$corporate = $facts['form'] !== null && $facts['form'] !== 'individual';
$shares = in_array($facts['form'], ['anonymous', 'simplified'], true);
$total = BigDecimal::zero();
$paid = BigDecimal::zero();
$units = BigDecimal::zero();
$complete = $subscribers !== [];
$paymentsComplete = $complete;
$unitsComplete = $complete;
$ids = array_column($facts['parties'], 'id');
$usedSources = [];
foreach ($facts['parties'] as $party) {
if ($party['source'] && in_array($party['source'], $usedSources, true)) {
$issues[] = 'A mesma origem foi seleccionada em mais de uma linha; conferir duplicação sem fundir pessoas por nome.';
}
$usedSources[] = $party['source'];
if (! $party['name'] || $party['roles'] === []) {
$issues[] = 'Completar o nome e os papéis de cada interveniente.';
}
if (in_array('representative', $party['roles'], true) && (! $party['represented_id'] || $party['represented_id'] === $party['id'] || ! in_array($party['represented_id'], $ids, true))) {
$issues[] = 'Identificar quem cada representante representa, numa linha distinta.';
}
if (! in_array('subscriber', $party['roles'], true) || ! $corporate) {
continue;
}
$complete = $complete && $party['cash'] !== null && $party['in_kind'] !== null;
$subscription = BigDecimal::of($party['cash'] ?? '0')->plus($party['in_kind'] ?? '0');
$total = $total->plus($subscription);
$paymentsComplete = $paymentsComplete && $party['paid'] !== null;
$paid = $paid->plus($party['paid'] ?? '0');
if ($party['paid'] !== null && $party['cash'] !== null && $party['in_kind'] !== null && BigDecimal::of($party['paid'])->compareTo($subscription) > 0) {
$issues[] = 'Uma realização declarada excede a subscrição desse participante.';
}
$unitsComplete = $unitsComplete && $party['share_count'] !== null;
$units = $units->plus($party['share_count'] ?? '0');
if ($shares && $party['share_count'] !== null && $facts['nominal_value'] !== null && $party['cash'] !== null && $party['in_kind'] !== null && BigDecimal::of($party['share_count'])->multipliedBy($facts['nominal_value'])->compareTo($subscription) !== 0) {
$issues[] = 'O valor nominal das acções de um participante difere da sua subscrição.';
}
if ($party['work'] && $facts['form'] !== 'collective') {
$issues[] = 'Conferir a admissibilidade da contribuição em trabalho para a forma escolhida.';
}
}
$totals = null;
if ($corporate) {
if (! $facts['currency'] || $facts['capital'] === null || ! $complete) {
$issues[] = 'Completar moeda, capital e entradas em dinheiro/espécie; valores desconhecidos não são zero.';
}
if ($complete && $facts['capital'] !== null && $total->compareTo($facts['capital']) !== 0) {
$issues[] = 'A soma das subscrições difere do capital declarado.';
}
if (! $paymentsComplete) {
$issues[] = 'Completar a realização declarada de cada subscrição; não equivale a prova de pagamento.';
}
if ($shares && ($facts['nominal_value'] === null || ! $unitsComplete)) {
$issues[] = 'Completar o número de acções e o valor nominal para reconciliar as participações.';
}
$totals = ['currency' => $facts['currency'], 'subscribed' => $complete && $facts['currency'] ? (string) $total : null,
'paid' => $paymentsComplete && $facts['currency'] ? (string) $paid : null,
'unpaid' => $complete && $paymentsComplete && $facts['currency'] ? (string) $total->minus($paid) : null,
'shares_nominal' => $shares && $unitsComplete && $facts['nominal_value'] !== null && $facts['currency'] ? (string) $units->multipliedBy($facts['nominal_value']) : null];
}
if ($facts['regulated'] !== 'no') {
$issues[] = 'Conferir os requisitos sectoriais ou profissionais da actividade; o objecto não concede licença.';
}
return ['issues' => array_values(array_unique($issues)), 'totals' => $totals, 'status' => 'preparation',
'note' => $facts['form'] === 'collective' ? 'As contribuições em trabalho são conservadas separadamente e não integram o capital (artigo 266).' : 'Valores declarados para preparação; não comprovam entradas, poderes ou registo.'];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function view(User $actor, string $id, array $input): array
{
$case = $this->desk->case($actor, $id);
$payload = $this->desk->decode($case->payload);
$v = Validator::make($input, ['revision' => 'nullable|uuid', 'history_before' => 'nullable|integer|min:1', 'form' => ['nullable', Rule::in(array_keys(config('company-comparison.forms')))]])->validate();
$saved = $payload['company_preparation'] ?? null;
if (! empty($v['revision'])) {
$event = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->where('id', $v['revision'])->first();
abort_unless($event !== null, 404);
$saved = $this->desk->decode($event->payload)['snapshot'];
}
$facts = $saved['facts'] ?? $this->facts(['facts' => []]);
$entity = $payload['investor_path']['context']['promoter_entity'] ?? null;
$context = app(InvestorContext::class)->state($case)['fields'];
$existingEntity = in_array($entity['kind'] ?? '', ['company', 'organization'], true);
if (! $saved && empty($v['revision'])) {
foreach (['currency' => 'currency', 'activities' => 'products_services', 'seat' => 'location'] as $target => $source) {
if (empty($facts[$target]) && ! empty($context[$source])) $facts[$target] = $context[$source];
}
$facts['proposed_name'] = $entity['snapshot']['name'] ?? $facts['proposed_name'];
$knownForm = $entity['snapshot']['legal_form'] ?? null;
$facts['form'] = $existingEntity ? $knownForm : ($v['form'] ?? $facts['form']);
}
$events = DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)
->when(! empty($v['history_before']), fn ($q) => $q->where('event_order', '<', $v['history_before']))
->orderByDesc('event_order')->limit(26)->get(['id', 'payload', 'event_order']);
return ['entity' => $entity, 'proposedForm' => ! $existingEntity ? ($v['form'] ?? null) : null, 'case' => ['id' => $id, 'title' => $case->title, 'version' => (int) $case->version],
'canWrite' => ! $case->closed_at && $this->desk->owns($actor, $case), 'historical' => ! empty($v['revision']),
'definition' => $saved['definition'] ?? $this->definition(), 'facts' => $facts, 'review' => $saved['review'] ?? $this->review($facts), 'saved' => $saved,
'sources' => $this->sources($case), 'history' => $events->take(25)->map(function ($e) {
$s = $this->desk->decode($e->payload)['snapshot'];
return ['id' => $e->id, 'revision' => $s['revision'], 'at' => $s['at']];
})->all(), 'historyNext' => $events->count() > 25 ? $events[24]->event_order : null];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function save(User $actor, string $id, array $input): array
{
$this->desk->case($actor, $id, true);
$v = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid'])->validate();
return DB::transaction(function () use ($actor, $id, $v, $input) {
$case = $this->desk->case($actor, $id, true, true);
foreach (DB::table('desk_events')->where('case_id', $id)->where('action', self::EVENT)->orderByDesc('event_order')->cursor() as $event) {
$data = $this->desk->decode($event->payload);
if ($data['operation_key'] === $v['operation_key']) {
$facts = $this->facts($input, $data['snapshot']['definition']);
$hash = hash('sha256', json_encode([(int) $v['version'], $facts], JSON_THROW_ON_ERROR));
abort_unless(hash_equals($data['request_hash'], $hash), 409, 'A operação já guardou outros dados.');
return ['saved' => true, 'replayed' => true, 'revision' => $data['snapshot']['revision']];
}
}
$facts = $this->facts($input);
$hash = hash('sha256', json_encode([(int) $v['version'], $facts], JSON_THROW_ON_ERROR));
abort_if($case->closed_at || (int) $case->version !== (int) $v['version'], 409, 'O dossier mudou ou foi fechado. Os dados continuam no formulário; recupere a versão antes de guardar.');
$payload = $this->desk->decode($case->payload);
$entity = $payload['investor_path']['context']['promoter_entity'] ?? null;
$registeredForm = $entity['snapshot']['legal_form'] ?? null;
if (in_array($entity['kind'] ?? '', ['company', 'organization'], true) && $registeredForm) {
abort_unless($facts['form'] === $registeredForm, 422, 'A forma jurídica da entidade existente não é alterada nesta preparação. Use o percurso próprio de alteração do cadastro.');
}
$previous = $payload['company_preparation'] ?? null;
$resolved = $this->resolve($facts, $this->sources($case), $previous);
$definition = $this->definition();
$review = $this->review($resolved);
if ($previous && $previous['facts'] === $resolved && $previous['definition'] === $definition && $previous['review'] === $review) {
return ['saved' => true, 'unchanged' => true, 'revision' => $previous['revision']];
}
$snapshot = ['revision' => (int) ($previous['revision'] ?? 0) + 1, 'at' => now()->toIso8601String(), 'actor_id' => $actor->id,
'facts' => $resolved, 'definition' => $definition, 'review' => $review];
$payload['company_preparation'] = $snapshot;
$case->version++;
DB::table('desk_cases')->where('id', $id)->update(['payload' => $this->desk->encode($payload), 'version' => $case->version, 'updated_at' => now()]);
$this->desk->event($case, $actor, self::EVENT, ['operation_key' => $v['operation_key'], 'request_hash' => $hash, 'snapshot' => $snapshot]);
return ['saved' => true, 'replayed' => false, 'revision' => $snapshot['revision']];
});
}
}
+74
View File
@@ -24,6 +24,15 @@ final class ContentManagement
$editor = $documents->full($actor) || $documents->editorial($actor); $editor = $documents->full($actor) || $documents->editorial($actor);
$upload = $editor || $documents->limited($actor); $upload = $editor || $documents->limited($actor);
$result = []; $result = [];
if (app(PortalEditorialWorkflow::class)->demographyAccess($actor)) {
$result['demography'] = ['index' => '/management/demography'];
}
if (app(PortalEditorialWorkflow::class)->portfolioAvailable() && $actor->can('manage-portal') && ! $profiles->has($actor, 'auditor')) {
$result['portfolio'] = ['index' => '/management/portfolio'];
}
if (app(ClusterCompetitiveness::class)->editorialEnabled() && $actor->can('manage-portal') && ! $profiles->has($actor, 'auditor')) {
$result['clusters'] = ['index' => '/management/clusters'];
}
if (app(Procurement::class)->available() && app(Procurement::class)->access($actor)) { if (app(Procurement::class)->available() && app(Procurement::class)->access($actor)) {
$result['procurement'] = ['index' => '/management/concursos', 'create' => '/management/concursos/novo']; $result['procurement'] = ['index' => '/management/concursos', 'create' => '/management/concursos/novo'];
} }
@@ -35,9 +44,74 @@ final class ContentManagement
$result['documents'] = ['index' => '/management/portal-services', 'edit' => $editor]; $result['documents'] = ['index' => '/management/portal-services', 'edit' => $editor];
} }
if (($editor || isset($result['opportunities'])) && ! $profiles->has($actor, 'auditor') && app(PortalEditorialWorkflow::class)->available()) {
$result['editorial'] = ['index' => '/management/editorial'];
}
return $result; return $result;
} }
/** @param array<array-key,mixed> $access
* @return list<array{label:string,href:string}>
*/
public function administrationNavigation(?User $actor, array $access): array
{
if (! $actor || ! $actor->hasVerifiedEmail()) {
return [];
}
$items = [];
foreach (['documents' => 'Biblioteca e documentos', 'opportunities' => 'Oportunidades', 'clusters' => 'Competitividade', 'portfolio' => 'Carteira', 'demography' => 'Demografia', 'procurement' => 'Concursos e anúncios'] as $key => $label) {
if (isset($access[$key]['index'])) {
$items[] = ['label' => $label, 'href' => $access[$key]['index']];
}
}
if (app(PortalEditorialSubjects::class)->available() && $actor->can('manage-portal') && ! app(PortalProfileAccess::class)->has($actor, 'auditor')) {
$items[] = ['label' => 'Estruturas e relações', 'href' => '/management/editorial/subjects'];
}
$native = app(PortalEditorialNativeNotices::class);
if ($native->access($actor, 'territorial-editorial-v1')) {
$items[] = ['label' => 'Conteúdos territoriais', 'href' => '/management/territorial/editorial'];
}
if ($native->access($actor, 'investment-zones')) {
$items[] = ['label' => 'Zonas e indicadores', 'href' => '/management/investment/zones'];
}
return $items;
}
/** @param array<array-key,mixed> $access
* @return list<array{label:string,href:string}>
*/
public function dashboardNavigation(?User $actor, array $access): array
{
if (! $actor || ! $actor->hasVerifiedEmail() || (! $actor->can('manage-portal') && $access === [] && ! app(ScopedPortalAdministration::class)->administrative($actor))) {
return [];
}
$items = [['label' => 'Visão geral', 'href' => '/dashboard'], ['label' => 'O meu trabalho', 'href' => '/dashboard#meu-trabalho']];
if ($actor->can('manage-portal') && ! app(PortalProfileAccess::class)->has($actor, 'auditor')) {
foreach (['manifestacoes' => 'Manifestações de interesse', 'indicadores-oportunidades' => 'Indicadores de oportunidades', 'pedidos-recentes' => 'Pedidos recentes', 'accoes-rapidas' => 'Acções rápidas'] as $anchor => $label) {
$items[] = ['label' => $label, 'href' => '/dashboard#'.$anchor];
}
$items[] = ['label' => 'Indicadores de utilização', 'href' => '/management/product-usage'];
}
if (! $actor->can('manage-portal') && app(InvestorPath::class)->available()) {
$items[] = ['label' => 'Os meus investimentos', 'href' => '/dashboard#meus-investimentos'];
}
$workflow = app(PortalEditorialWorkflow::class);
if ($workflow->available() && $workflow->canEnter($actor)) {
$items[] = ['label' => 'Circuito editorial', 'href' => '/management/editorial'];
$documents = app(DocumentManagementAccess::class);
if ($documents->full($actor) || $documents->editorial($actor)) {
foreach (['article' => 'Revisão de artigos', 'legislation' => 'Revisão de legislação', 'document' => 'Revisão de documentos'] as $kind => $label) {
$items[] = ['label' => $label, 'href' => '/management/editorial?kind='.$kind];
}
}
$items[] = ['label' => 'Notificações editoriais', 'href' => '/management/editorial#notificacoes'];
}
return $items;
}
/** /**
* @return array<array-key, mixed> * @return array<array-key, mixed>
*/ */
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Services;
use App\Models\CrmTask;
use App\Models\Lead;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Validation\ValidationException;
final class CrmNextAction
{
/** @return Builder<CrmTask> */
public function future(Lead $lead, ?string $exceptTask = null): Builder
{
return CrmTask::availableForWork()->where('tasks.lead_id', $lead->id)->where('tasks.due_at', '>', now())
->when($exceptTask !== null, fn ($query) => $query->where('tasks.id', '!=', $exceptTask));
}
/** Both write paths lock the dossier (when linked), lead, then task before checking. */
public function assertMayFinish(?Lead $lead, CrmTask $task, string $status): void
{
if ($lead !== null && ! $lead->trashed() && in_array($lead->status, ['new', 'qualified'], true)
&& in_array($status, ['done', 'cancelled'], true) && ! $this->future($lead, $task->id)->exists()) {
throw ValidationException::withMessages(['status' => 'Crie a próxima acção com prazo futuro antes de encerrar a última tarefa de um acompanhamento activo. Tarefas num dossier encerrado não estão disponíveis.']);
}
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Services;
use App\Models\CrmTask;
use App\Models\Lead;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
final class CrmTaskCreation
{
private const SOURCE = 'portal-crm-task-creation';
/** @param array<string,mixed> $input
* @param array<int,int> $assignees
* @return array{task_id:string,version:int,replayed:bool}
*/
public function create(User $actor, Lead $lead, array $input, array $assignees): array
{
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
$data = Validator::make($input, ['client_key' => 'nullable|uuid', 'title' => 'required|string|max:200', 'due_at' => 'required|date', 'assignee_user_id' => 'required|integer'])->validate();
$key = is_string($data['client_key'] ?? null) ? strtolower($data['client_key']) : null;
$values = ['title' => trim($data['title']), 'due_at' => CarbonImmutable::parse($data['due_at'])->utc()->format('Y-m-d\TH:i:s.u\Z'), 'assignee_user_id' => (int) $data['assignee_user_id']];
$hash = hash('sha256', json_encode($values, JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $lead, $values, $key, $hash, $assignees) {
$lead = Lead::lockForUpdate()->findOrFail($lead->id);
if ($key !== null) {
$event = $this->query($actor, $lead)->whereRaw("after_data->'task_creation'->>'key' = ?", [$key])->selectRaw("entity_id,after_data->'task_creation'->>'hash' AS hash,after_data->'task_creation'->'version' AS version")->first();
if ($event) {
abort_unless($event->hash === $hash, 409, 'Esta tentativa já foi usada com outros dados. Compare as tarefas antes de continuar.');
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
abort_unless(is_string($event->entity_id) && Str::isUuid($event->entity_id) && is_int($version) && $version > 0, 409, 'A criação anterior não foi identificada com segurança.');
return ['task_id' => $event->entity_id, 'version' => $version, 'replayed' => true];
}
}
Validator::make($values, ['title' => 'required|string|max:200', 'due_at' => 'required|date|after:now', 'assignee_user_id' => ['required', 'integer', Rule::in($assignees)]])->validate();
$task = new CrmTask;
PortalAudit::save($task, [...$values, 'lead_id' => $lead->id, 'status' => 'open'], $actor->id);
if ($key !== null) {
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'actor_user_id' => $actor->id, 'entity_type' => 'tasks', 'entity_id' => $task->id, 'action' => 'created', 'data_classification' => 'internal',
'after_data' => json_encode(['task_creation' => ['lead_id' => $lead->id, 'key' => $key, 'hash' => $hash, 'version' => (int) $task->getAttribute('version_no')]], JSON_THROW_ON_ERROR)]);
}
return ['task_id' => $task->id, 'version' => (int) $task->getAttribute('version_no'), 'replayed' => false];
});
}
/** @return array{lead_id:string,actor_id:int,commands:list<array{key:string,task_id:string,version:int}>,preparation:array<string,mixed>} */
public function context(User $actor, Lead $lead): array
{
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
$commands = [];
foreach ($this->query($actor, $lead)->orderBy('occurred_at')->selectRaw("entity_id,after_data->'task_creation'->>'key' AS key,after_data->'task_creation'->'version' AS version")->get() as $event) {
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
if (is_string($event->key) && Str::isUuid($event->key) && is_string($event->entity_id) && Str::isUuid($event->entity_id) && is_int($version) && $version > 0) {
$commands[] = ['key' => $event->key, 'task_id' => $event->entity_id, 'version' => $version];
}
}
return ['lead_id' => $lead->id, 'actor_id' => $actor->id, 'commands' => $commands, 'preparation' => app(CrmTaskPreparations::class)->view($actor, $lead)];
}
private function query(User $actor, Lead $lead): Builder
{
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)->where('entity_type', 'tasks')->where('action', 'created')
->whereRaw("after_data->'task_creation'->>'lead_id' = ?", [$lead->id]);
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace App\Services;
use App\Models\Lead;
use App\Models\User;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
final class CrmTaskPreparations
{
public function installed(): bool
{
return Schema::hasTable('crm_task_preparations');
}
/** @return array<string,mixed> */
public function view(User $actor, Lead $lead): array
{
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
$row = $this->installed() ? DB::table('crm_task_preparations')->where('actor_id', $actor->id)->where('lead_id', $lead->id)->first() : null;
$snapshot = null;
$unavailable = false;
if ($row) {
try {
$decoded = json_decode(Crypt::decryptString($row->snapshot), true);
$validator = Validator::make(['snapshot' => $decoded], $this->rules());
if ($validator->fails()) {
$unavailable = true;
} else {
$snapshot = $this->normalize($validator->validated()['snapshot']);
}
} catch (DecryptException) {
$unavailable = true;
}
}
return ['installed' => $this->installed(), 'version' => (int) ($row->version ?? 0), 'snapshot' => $snapshot, 'operation_key' => $row->operation_key ?? null,
'updated_at' => $row->updated_at ?? null, 'unavailable' => $unavailable];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function save(User $actor, Lead $lead, array $input): array
{
abort_unless(Gate::forUser($actor)->allows('manage-portal'), 403);
abort_unless($this->installed(), 409, 'A recuperação persistente ainda não está instalada. A criação manual continua disponível.');
$data = Validator::make($input, [...$this->rules(), 'version' => 'required|integer|min:0', 'operation_key' => 'required|uuid'])->validate();
$data['snapshot'] = $this->normalize($data['snapshot']);
$key = strtolower($data['operation_key']);
$hash = hash('sha256', json_encode(Arr::sortRecursive(['version' => (int) $data['version'], 'snapshot' => $data['snapshot']]), JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $lead, $data, $key, $hash): array {
$lead = Lead::lockForUpdate()->findOrFail($lead->id);
$row = DB::table('crm_task_preparations')->where('actor_id', $actor->id)->where('lead_id', $lead->id)->lockForUpdate()->first();
if ($row && $row->operation_key === $key) {
abort_unless(hash_equals($row->operation_sha256, $hash), 409, 'Esta tentativa de guardar já foi usada com outros dados.');
return app(CrmTaskCreation::class)->context($actor, $lead);
}
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'A preparação mudou noutro separador. Compare antes de substituir.');
if ($row) {
abort_if($this->view($actor, $lead)['unavailable'], 409, 'A preparação guardada não pôde ser recuperada. Os dados anteriores foram preservados.');
}
$version = (int) ($row->version ?? 0) + 1;
DB::table('crm_task_preparations')->updateOrInsert(['actor_id' => $actor->id, 'lead_id' => $lead->id], [
'version' => $version, 'operation_key' => $key, 'operation_sha256' => $hash,
'snapshot' => Crypt::encryptString(json_encode($data['snapshot'], JSON_THROW_ON_ERROR)),
'created_at' => $row->created_at ?? now(), 'updated_at' => now(),
]);
DB::table('audit_events')->insert(['source_system' => 'portal-crm-task-preparation', 'entity_type' => 'crm_task_preparations', 'entity_id' => $lead->id,
'actor_user_id' => $actor->id, 'action' => 'draft_checkpoint_saved', 'data_classification' => 'restricted', 'after_data' => json_encode(['version' => $version], JSON_THROW_ON_ERROR)]);
return app(CrmTaskCreation::class)->context($actor, $lead);
});
}
/** @param array<string,mixed> $snapshot
* @return array<string,mixed> */
private function normalize(array $snapshot): array
{
foreach (['title', 'due_at', 'assignee_user_id'] as $field) {
$snapshot['generation'][$field] = (int) $snapshot['generation'][$field];
if (is_array($snapshot['pending'])) {
$snapshot['pending']['generation'][$field] = (int) $snapshot['pending']['generation'][$field];
}
}
if (is_array($snapshot['pending'])) {
$snapshot['pending']['values']['client_key'] = strtolower($snapshot['pending']['values']['client_key']);
}
return $snapshot;
}
/** @return array<string,string> */
private function rules(): array
{
$rules = ['snapshot' => 'required|array:values,generation,pending', 'snapshot.values' => 'required|array:title,due_at,assignee_user_id',
'snapshot.generation' => 'required|array:title,due_at,assignee_user_id', 'snapshot.pending' => 'present|nullable|array:values,generation',
'snapshot.pending.values' => 'required_with:snapshot.pending|array:title,due_at,assignee_user_id,client_key',
'snapshot.pending.generation' => 'required_with:snapshot.pending|array:title,due_at,assignee_user_id',
'snapshot.pending.values.client_key' => 'required_with:snapshot.pending|uuid'];
foreach (['title' => 200, 'due_at' => 100, 'assignee_user_id' => 20] as $field => $limit) {
$rules['snapshot.values.'.$field] = 'present|string|max:'.$limit;
$rules['snapshot.generation.'.$field] = 'present|integer|min:0|max:1000000000';
$rules['snapshot.pending.values.'.$field] = 'exclude_without:snapshot.pending|present|string|max:'.$limit;
$rules['snapshot.pending.generation.'.$field] = 'exclude_without:snapshot.pending|present|integer|min:0|max:1000000000';
}
return $rules;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Services;
use App\Models\CrmTask;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/** Personal follow-up only: assignment never grants authority beyond the destination. */
final class DashboardWorkQueue
{
/**
* @param array<string, int> $pages
* @return array<string, mixed>|null
*/
public function forActor(User $actor, array $pages): ?array
{
$now = CarbonImmutable::now()->startOfSecond();
$access = app(PortalProfileAccess::class);
$manager = $actor->can('manage-portal') && ! $access->has($actor, 'auditor');
$groups = [];
if (app(ScopedPortalAdministration::class)->interestOperator($actor)) {
$query = DB::table('interest_requests')->where('assigned_to', $actor->id)->whereNull('deleted_at')
->whereNotIn('status', ['closed', 'cancelled', 'refused', 'converted'])
->select(['id', 'reference', 'next_action as title', 'status', 'next_action_due_at as due_at']);
$groups['interests'] = $this->group($query, 'interests', $pages, $now);
}
if (app(VirtualDesk::class)->installed()) {
$assigned = DB::table('desk_requests')->where('analyst_id', $actor->id);
// Direct request consultation already permits the assigned analyst, independently of decision authority.
if ($manager || $assigned->exists()) {
$query = DB::table('desk_requests as r')->join('desk_cases as c', 'c.id', '=', 'r.case_id')
->where('r.analyst_id', $actor->id)->whereNull('c.closed_at')
->whereNotIn('r.status', ['draft', 'cancelled', 'closed'])
->select(['r.id', 'r.protocol as reference', 'c.title', 'r.status', 'r.due_at']);
$groups['desk'] = $this->group($query, 'desk', $pages, $now);
}
}
if ($manager && Schema::hasTable('tasks') && Schema::hasTable('leads')) {
$query = CrmTask::availableForWork()->join('leads as l', 'l.id', '=', 'tasks.lead_id')
->where('tasks.assignee_user_id', $actor->id)->whereNull('l.deleted_at')
->select(['tasks.id', 'tasks.title', 'tasks.status', 'tasks.due_at', 'l.id as parent_id', 'l.title as reference']);
$groups['crm_tasks'] = $this->group($query->toBase(), 'crm_tasks', $pages, $now);
}
return $groups === [] ? null : ['as_of' => $now->toISOString(), 'groups' => $groups, 'desk_states' => config('virtual-desk.request_states')];
}
/**
* @param 'interests'|'desk'|'crm_tasks' $kind
* @param array<string, int> $pages
* @return array<string, mixed>
*/
private function group(Builder $query, string $kind, array $pages, CarbonImmutable $now): array
{
[$deadline, $order, $idColumn] = match ($kind) {
'interests' => ['next_action_due_at', 'next_action_due_at ASC NULLS LAST', 'id'],
'desk' => ['r.due_at', 'r.due_at ASC NULLS LAST', 'r.id'],
'crm_tasks' => ['tasks.due_at', 'tasks.due_at ASC NULLS LAST', 'tasks.id'],
};
$pageName = $kind.'_page';
$page = $pages[$pageName] ?? 1;
$total = (clone $query)->count();
$overdue = (clone $query)->where($deadline, '<', $now)->count();
$lastPage = max(1, (int) ceil($total / 5));
// An assignment may disappear between visits. Recover to an existing page instead of trapping a stale URL.
$page = min($page, $lastPage);
$items = (clone $query)->orderByRaw($order)->orderBy($idColumn)
->offset(($page - 1) * 5)->limit(5)->get()->map(function (\stdClass $row) use ($kind, $now): array {
$due = $row->due_at === null ? null : CarbonImmutable::parse($row->due_at);
return ['id' => (string) $row->id, 'title' => $row->title ?: 'Acompanhar manifestação', 'reference' => $row->reference,
'status' => $row->status, 'due_at' => $due?->toISOString(), 'overdue' => $due?->lessThan($now) ?? false,
'href' => match ($kind) {
'interests' => '/management/interests/'.$row->id,
'desk' => '/balcao-virtual/pedidos/'.$row->id,
'crm_tasks' => '/management/crm/leads/'.$row->parent_id.'#crm-task-'.$row->id,
}];
})->all();
return ['total' => $total, 'overdue' => $overdue, 'items' => $items, 'page' => $page, 'last_page' => $lastPage,
'previous' => $page > 1 ? route('dashboard', [...$pages, $pageName => $page - 1], absolute: false) : null,
'next' => $page < $lastPage ? route('dashboard', [...$pages, $pageName => $page + 1], absolute: false) : null];
}
}
+156
View File
@@ -0,0 +1,156 @@
<?php
namespace App\Services;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
final class DemographicEvidence
{
public function territories(): Builder
{
$public = app(InvestmentGeography::class)->publicReferences();
return DB::table('geo_locations')->whereNull('deleted_at')->whereIn('location_type', ['province', 'district'])
->where(function ($q) use ($public) {
$q->whereIn('id', (clone $public)->select('id'));
if ($this->installed() && str_ends_with(DB::connection()->getDatabaseName(), '_test')) {
// Macate/Vanduzi: expressly authorised QA references, never active registry changes.
$q->orWhere(fn ($qa) => $qa->where('source_system', 'ine-demography-qa')->where('data_classification', 'public')->whereIn('parent_id', (clone $public)->select('id')));
}
});
}
public function installed(): bool
{
return (bool) config('demography.enabled', app()->environment('local', 'testing'))
&& Schema::hasTable('demographic_imports') && Schema::hasTable('demographic_observations');
}
/** @return array<string,string> */
public static function sectors(): array
{
return ['commerce' => 'Comércio e serviços', 'industry' => 'Indústria', 'agriculture' => 'Agricultura e agro-indústria', 'education' => 'Educação', 'health' => 'Saúde', 'general' => 'Contexto geral'];
}
/** Broader administrative evidence stays labelled as context, never local data.
* @return array<string,mixed>
*/
public function investmentContext(string $territory, int $start, int $end, string $sector = 'general', ?string $edition = null): array
{
$path = app(InvestmentGeography::class)->path($territory);
$requested = collect($path)->last();
$result = $this->analyse([], $start, $end, $sector, $edition);
foreach (array_reverse($path) as $node) {
if (! in_array($node->location_type, ['district', 'province'], true)) {
continue;
}
$result = $this->analyse([$node->id], $start, $end, $sector, $edition);
if ($result['state'] === 'available') {
break;
}
}
$result['requested_territory'] = $requested ? ['id' => $requested->id, 'name' => $requested->name, 'level' => $requested->location_type] : null;
$result['broader_context'] = $requested && count($result['territories']) && $requested->id !== $result['territories'][0]['id'];
return $result;
}
/** @param list<string> $territories
* @return array<string,mixed> */
public function analyse(array $territories, int $start, int $end, string $sector = 'general', ?string $edition = null): array
{
$result = ['state' => 'unavailable', 'start_year' => $start, 'end_year' => $end, 'sector' => $sector, 'territories' => [], 'differences' => [], 'comparisons' => [],
'limitations' => ['População residente não mede procura efectiva ou poder de compra.', 'Idade activa não demonstra disponibilidade ou qualificação de mão-de-obra.',
'Sem extrapolação: anos sem série oficial permanecem sem dados.', 'A demografia não altera impostos, incentivos ou probabilidades de sucesso.']];
if (! $this->installed() || $territories === []) {
return $result;
}
$locations = $this->territories()->whereIn('id', $territories)->get(['id', 'name', 'location_type']);
$records = DB::table('demographic_observations as o')->join('demographic_imports as b', 'b.id', '=', 'o.import_id')
->where('b.status', 'approved')->whereIn('o.geo_location_id', $locations->pluck('id'))->whereBetween('o.year', [$start, $end])
->where('o.sex', 'all')->when($edition, fn ($q) => $q->where('b.id', $edition))
->orderBy('o.year')->orderBy('o.import_id')->orderBy('o.id')
->get(['o.*', 'b.source', 'b.publication_version', 'b.sha256', 'b.file_name']);
$issuesByImport = DB::table('demographic_imports')->whereIn('id', $records->pluck('import_id')->unique()->all())
->get(['id', DB::raw("report->'issue_counts' AS issue_counts")])->keyBy('id');
foreach ($locations as $location) {
$series = [];
foreach ($records->where('geo_location_id', $location->id)->groupBy('import_id') as $importId => $rows) {
$first = $rows->first();
$issueCounts = json_decode($issuesByImport->get($importId)->issue_counts ?? '{}', true, 512, JSON_THROW_ON_ERROR);
$values = $rows->filter(function ($r) use ($sector) {
if ($r->indicator !== 'population') {
return in_array($sector, ['health', 'general'], true);
}
return $r->age_group === 'all' || in_array($sector, ['education', 'health', 'industry', 'agriculture', 'general'], true);
})->map(fn ($r) => ['year' => $r->year, 'indicator' => $r->indicator, 'age_group' => $r->age_group, 'residence' => $r->residence,
'value' => $r->numeric_value, 'original_value' => $r->original_value, 'unit' => $r->unit, 'data_kind' => $r->data_kind,
'sheet' => $r->sheet, 'cell' => $r->cell, 'validation_status' => $r->validation_status])->values()->all();
$years = array_values(array_unique(array_column($values, 'year')));
$series[] = ['import_id' => $importId, 'source' => $first->source, 'version' => $first->publication_version, 'sha256' => $first->sha256, 'file_name' => $first->file_name,
'values' => $values, 'missing_years' => array_values(array_diff(range($start, $end), $years)), 'issue_counts' => $issueCounts];
}
$result['territories'][] = ['id' => $location->id, 'name' => $location->name, 'level' => $location->location_type, 'series' => $series,
'factors_to_assess' => match ($sector) {
'industry' => ['Estrutura etária e evolução da população; verificar qualificações, mobilidade e emprego.'],
'agriculture' => ['População rural e mercados locais; relacionar com os clusters documentados.'],
'education' => ['Grupos etários da população-alvo; verificar cobertura e capacidade dos serviços.'],
'health' => ['Estrutura etária e estatísticas vitais com unidades conhecidas; verificar cobertura dos serviços.'],
default => ['Dimensão e evolução da população; confrontar com rendimento, acesso e condições sectoriais.'],
}];
}
// Identify concurrent values without summing editions or choosing a supposedly newer one.
foreach ($result['territories'] as $territory) {
$byDimension = [];
foreach ($territory['series'] as $series) {
foreach ($series['values'] as $row) {
$key = implode('|', [$row['year'], $row['indicator'], $row['age_group'], $row['residence'], $row['unit']]);
$byDimension[$key][] = ['import_id' => $series['import_id'], 'value' => $row['value'], 'data_kind' => $row['data_kind']];
}
}
foreach ($byDimension as $key => $values) {
if (count($values) > 1) {
$result['differences'][] = ['territory_id' => $territory['id'], 'dimension' => $key, 'state' => count(array_unique(array_column($values, 'value'))) === 1 ? 'matching_values' : 'divergent_values', 'values' => $values];
}
}
}
$result['state'] = $records->isEmpty() ? 'no_data' : 'available';
foreach ($result['territories'] as $i => $left) {
foreach (array_slice($result['territories'], $i + 1) as $right) {
foreach ($left['series'] as $a) {
foreach ($right['series'] as $b) {
foreach (array_unique([$start, $end]) as $year) {
$isTotal = fn ($r) => $r['year'] === $year && $r['indicator'] === 'population' && $r['age_group'] === 'all' && $r['residence'] === 'all';
$x = array_values(array_filter($a['values'], $isTotal))[0] ?? null;
$y = array_values(array_filter($b['values'], $isTotal))[0] ?? null;
if (! $x || ! $y) {
continue;
}
$comparable = $left['level'] === $right['level'] && $x['unit'] === $y['unit'] && $x['data_kind'] === $y['data_kind'] && $a['version'] === $b['version'];
$delta = $comparable ? DB::selectOne('SELECT (?::numeric - ?::numeric)::text AS value', [$x['value'], $y['value']])->value : null;
$result['comparisons'][] = ['year' => $year, 'left' => $left['name'], 'right' => $right['name'], 'left_value' => $x['value'], 'right_value' => $y['value'],
'left_import' => $a['import_id'], 'right_import' => $b['import_id'], 'difference' => $delta,
'explanation' => $comparable ? 'Diferença dos totais de população no mesmo ano, nível, tipo de dado, unidade e identificação de edição. Não mede procura efectiva.' : 'Âmbitos ou metadados distintos; não se calculou uma diferença como se fossem equivalentes.'];
}
}
}
}
}
return $result;
}
/** @param array<string,mixed> $context
* @return array<string,mixed> */
public function forContext(array $context): array
{
$fields = $context['fields'] ?? [];
$id = ($fields['district_id'] ?? null) ?: ($fields['province_id'] ?? null);
// No inference from an influence area to a project's implantation territory.
return $this->analyse($id ? [$id] : [], (int) date('Y'), (int) date('Y'), 'general');
}
}
+283
View File
@@ -0,0 +1,283 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Services\Malware\MalwareScanner;
use App\Support\CheckedFile;
use App\Support\IsolatedQaDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
final class DemographicImport
{
/**
* CLI preparation is read-only input, never an import or approval.
*
* @return array{preview:string,records:string,receipt:array<string,mixed>}|null
*/
public function preparedSource(string $sha, ?int $baselineYear, bool $verifyRecords = true): ?array
{
$root = config('demography.prepared_directory');
if (! is_string($root) || $root === '') {
return null;
}
abort_unless(preg_match('/^[a-f0-9]{64}$/', $sha) === 1, 422);
$directory = $root.'/'.$sha;
if (! is_file($directory.'/preparation.json')) {
return null;
}
abort_unless(is_readable($directory.'/preparation.json'), 409, 'Recibo CLI indisponível.');
try {
$receipt = json_decode(CheckedFile::read($directory.'/preparation.json'), true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
abort(409, 'Recibo CLI inválido.');
}
abort_unless(is_array($receipt), 409, 'Recibo CLI inválido.');
$preview = $directory.'/preview.json';
$records = $directory.'/records.ndjson';
abort_unless(($receipt['sha256'] ?? '') === $sha && array_key_exists('baseline_year', $receipt) && $receipt['baseline_year'] === $baselineYear
&& ($receipt['parser_sha256'] ?? '') === CheckedFile::sha256(base_path('tools/demography_workbook.py'))
&& is_file($preview) && CheckedFile::matches($preview, $receipt['preview_sha256'] ?? '') && is_file($records), 409, 'A preparação CLI mudou; conservar o original e preparar novamente fora do servidor web.');
try {
$report = json_decode(CheckedFile::read($preview), true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
abort(409, 'Prévia CLI inválida.');
}
abort_unless(is_array($report), 409, 'Prévia CLI inválida.');
abort_unless(($report['sha256'] ?? '') === $sha && ($report['record_count'] ?? null) === ($receipt['record_count'] ?? null)
&& ($report['records_file_sha256'] ?? '') === ($receipt['records_sha256'] ?? '')
&& (! $verifyRecords || CheckedFile::matches($records, $receipt['records_sha256'] ?? '')), 409, 'Resultados da preparação CLI alterados.');
return ['preview' => $preview, 'records' => $records, 'receipt' => $receipt];
}
/** @param array<string,array<string,mixed>> $files */
public function preparedSourcesReady(array $files): bool
{
try {
foreach ($files as $name => $expected) {
$source = $this->preparedSource($expected['sha256'], $name === 'Dados demograficos.xlsx' ? 2017 : null, false);
if ($source === null || $source['receipt']['record_count'] !== $expected['records']) {
return false;
}
}
return $files !== [];
} catch (\Throwable) {
return false;
}
}
public function authorize(User $actor): void
{
$access = app(PortalProfileAccess::class);
abort_unless(($actor->can('manage-portal') || $access->superuser($actor)) && ! $access->has($actor, 'auditor'), 403);
abort_unless($actor->two_factor_confirmed_at && $actor->two_factor_secret, 403, 'Confirme MFA para gerir dados demográficos.');
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
abort_unless(app(DemographicInstallation::class)->activeTarget() && app(DemographicEvidence::class)->installed(), 403, 'Destino demográfico não instalado ou não autorizado.');
abort_unless(app(PortalProfileAccess::class)->mfa($actor), 403, 'Conclua MFA nesta sessão para gerir dados demográficos.');
}
}
/** @return array<string,mixed> */
public function prepare(User $actor, string $file, string $name, string $version, ?int $baselineYear): array
{
$this->authorize($actor);
abort_unless(is_file($file) && filesize($file) <= 20_000_000 && strtolower(pathinfo($name, PATHINFO_EXTENSION)) === 'xlsx', 422);
$sha = CheckedFile::sha256($file);
$existing = DB::table('demographic_imports')->where('sha256', $sha)->first();
if ($existing) {
return $this->preview($actor, $existing->id);
}
$id = (string) Str::uuid();
$directory = 'demography/'.$id;
$disk = Storage::disk('local');
$disk->makeDirectory($directory);
$path = $disk->path($directory.'/original.xlsx');
abort_unless(copy($file, $path) && CheckedFile::matches($path, $sha), 409);
$scan = app(MalwareScanner::class)->scan($path, (int) filesize($path), $disk->path($directory));
abort_unless($scan['result'] === 'clean', 423, 'Análise antimalware pendente ou não limpa; original privado conservado.');
$output = $disk->path($directory.'/preview.json');
$prepared = $this->preparedSource($sha, $baselineYear);
if ($prepared !== null) {
abort_unless(copy($prepared['preview'], $output) && CheckedFile::matches($output, $prepared['receipt']['preview_sha256'])
&& copy($prepared['records'], $disk->path($directory.'/records.ndjson'))
&& CheckedFile::matches($disk->path($directory.'/records.ndjson'), $prepared['receipt']['records_sha256']), 409, 'Preparação CLI alterada durante a cópia.');
} else {
abort_unless(function_exists('proc_open'), 503, 'Este servidor web não executa o preparador. Prepare este original pelo importador CLI e confira o respectivo recibo antes de continuar.');
$command = [config('demography.python', 'python'), base_path('tools/demography_workbook.py'), $path, '--output', $output, '--records-output', $disk->path($directory.'/records.ndjson')];
if ($baselineYear !== null) {
array_push($command, '--baseline-year', (string) $baselineYear);
}
$process = new Process($command, base_path(), timeout: 120);
$process->run();
abort_unless($process->isSuccessful(), 422, 'Não foi possível reconhecer o Excel; confira a estrutura e o ano de referência.');
}
$report = json_decode(CheckedFile::read($output), true, 512, JSON_THROW_ON_ERROR);
abort_unless(hash_equals($sha, $report['sha256']) && CheckedFile::matches($path, $sha), 409);
$summary = array_diff_key($report, ['records' => true]);
$summary['scan'] = ['result' => $scan['result'], 'engine' => $scan['engine'], 'engine_version' => $scan['engine_version'], 'sha256' => $sha];
// The supplied publication label is provenance metadata, never an invented edition/date.
DB::table('demographic_imports')->insert(['id' => $id, 'sha256' => $sha, 'file_name' => basename($name),
'source' => $report['source'], 'publication_version' => $version, 'status' => 'prepared',
'report' => json_encode($summary, JSON_THROW_ON_ERROR), 'preview_sha256' => CheckedFile::sha256($output),
'prepared_by' => $actor->id, 'created_at' => now(), 'updated_at' => now()]);
$this->event($id, $actor, 'prepared', 'Pré-visualização do original; sem aprovação de utilização.', ['sha256' => $sha]);
return $this->preview($actor, $id);
}
public static function key(string $province, string $territory, string $level): string
{
return $province.'|'.$territory.'|'.$level;
}
/** @return array<string,mixed> */
public function preview(User $actor, string $id): array
{
$this->authorize($actor);
$batch = DB::table('demographic_imports')->where('id', $id)->first();
abort_unless($batch !== null, 404);
$report = json_decode($batch->report, true, 512, JSON_THROW_ON_ERROR);
$locations = DB::table('geo_locations')->whereIn('location_type', ['province', 'district'])->whereNull('deleted_at')->get(['id', 'name', 'parent_id', 'location_type']);
$matches = [];
foreach ($report['territories'] as [$province, $territory, $level]) {
$provinces = $locations->filter(fn ($g) => $g->location_type === 'province' && $this->normalize($g->name) === $this->normalize($province));
$candidates = $level === 'province' ? $provinces : $locations->filter(fn ($g) => $g->location_type === 'district' && $provinces->contains('id', $g->parent_id) && $this->normalize($g->name) === $this->normalize($territory));
$key = self::key($province, $territory, $level);
if ($level === 'district') {
$headers = $report['territory_headers'][$key] ?? [];
if ($headers !== [] && $candidates->count() > 1 && array_all($headers, fn ($h) => preg_match('/^Distrito de /i', $h) === 1)) {
$candidates = $candidates->filter(fn ($g) => ! preg_match('/^CIDADE /i', $g->name));
}
if ($headers !== [] && $candidates->count() > 1 && array_all($headers, fn ($h) => preg_match('/^Cidade (de|da) /i', $h) === 1)) {
$candidates = $candidates->filter(fn ($g) => preg_match('/^CIDADE /i', $g->name) === 1);
}
$manifest = DemographicInstallation::remainingManifest();
$hashes = array_column($manifest['files'], 'sha256');
$alias = in_array($batch->sha256, $hashes, true) ? ($manifest['aliases'][$key] ?? null) : null;
if ($alias !== null) {
$candidates = $locations->filter(fn ($g) => $g->location_type === 'district' && $provinces->contains('id', $g->parent_id) && $this->literal($g->name) === $this->literal($alias));
}
}
$matches[] = ['key' => self::key($province, $territory, $level), 'province' => $province, 'territory' => $territory, 'level' => $level,
'geo_location_id' => $candidates->count() === 1 ? $candidates->first()->id : null, 'state' => $candidates->count() === 1 ? 'matched' : ($candidates->isEmpty() ? 'missing' : 'ambiguous')];
}
return ['id' => $id, 'file_name' => $batch->file_name, 'sha256' => $batch->sha256, 'publication_version' => $batch->publication_version,
'status' => $batch->status, 'report' => $report, 'matches' => $matches,
'territory_options' => $locations->values()->all(), 'events' => DB::table('demographic_events')->where('import_id', $id)->orderBy('id')->get()];
}
private function normalize(string $name): string
{
return preg_replace('/^(cidade|distrito) (de|da) /', '', $this->literal($name));
}
private function literal(string $name): string
{
$name = str_replace(['`', '’', '‘', '´'], "'", Str::ascii($name));
return preg_replace('/\s+/', ' ', trim(strtolower(str_replace(['-', '–'], ' ', $name))));
}
/** @param array<string,string> $mapping
* @return array<string,mixed> */
public function confirm(User $actor, string $id, string $sha, array $mapping, string $reason): array
{
$this->authorize($actor);
return DB::transaction(function () use ($actor, $id, $sha, $mapping, $reason) {
$batch = DB::table('demographic_imports')->where('id', $id)->lockForUpdate()->first();
abort_unless($batch && hash_equals($batch->sha256, $sha), 409);
if ($batch->status !== 'prepared') {
return ['id' => $id, 'status' => $batch->status, 'records' => DB::table('demographic_observations')->where('import_id', $id)->count(), 'repeated' => true];
}
$disk = Storage::disk('local');
$file = $disk->path('demography/'.$id.'/preview.json');
abort_unless(is_file($file) && CheckedFile::matches($file, $batch->preview_sha256) && CheckedFile::matches($disk->path('demography/'.$id.'/original.xlsx'), $sha), 409, 'Prévia ou original alterados.');
$report = json_decode(CheckedFile::read($file), true, 512, JSON_THROW_ON_ERROR);
$blocking = array_intersect(array_keys($report['issue_counts']), ['conflicting_value', 'duplicate_value', 'unsupported_sheet', 'unsupported_population_headers', 'reference_year_required', 'title_year_mismatch', 'invalid_numeric_or_formula']);
abort_if($blocking !== [], 422, 'Corrija os erros estruturais antes de confirmar: '.implode(', ', $blocking));
$plan = $this->preview($actor, $id);
$resolved = [];
foreach ($plan['matches'] as $match) {
$locationId = $mapping[$match['key']] ?? $match['geo_location_id'];
$location = DB::table('geo_locations')->where('id', $locationId)->whereNull('deleted_at')->first();
abort_unless($location && $location->location_type === $match['level'], 422, 'Correspondência territorial por resolver.');
if ($match['level'] === 'district') {
$provinceKey = self::key($match['province'], $match['province'], 'province');
$provinceMatch = array_values(array_filter($plan['matches'], fn ($m) => $m['key'] === $provinceKey))[0] ?? null;
abort_unless($location->parent_id === ($mapping[$provinceKey] ?? $provinceMatch['geo_location_id'] ?? null), 422, 'Distrito fora da província indicada.');
}
abort_if(in_array($locationId, $resolved, true), 422, 'Duas designações não podem ser fundidas na mesma localização.');
$resolved[$match['key']] = $locationId;
}
$chunk = [];
$recordCount = 0;
foreach ($this->recordRows($report, $disk->path('demography/'.$id.'/records.ndjson')) as $row) {
$recordCount++;
$chunk[] = ['import_id' => $id, 'geo_location_id' => $resolved[self::key($row['province'], $row['territory'], $row['level'])],
...array_intersect_key($row, array_flip(['year', 'indicator', 'sex', 'residence', 'age_group', 'unit', 'data_kind', 'original_value', 'numeric_value', 'sheet', 'cell'])),
'validation_status' => $report['issues'] === [] ? 'valid' : 'warning'];
if (count($chunk) === 500) {
DB::table('demographic_observations')->insert($chunk);
$chunk = [];
}
}
if ($chunk !== []) {
DB::table('demographic_observations')->insert($chunk);
}
abort_unless($recordCount === $report['record_count'], 409, 'O número de observações difere da prévia.');
DB::table('demographic_imports')->where('id', $id)->update(['status' => 'imported', 'updated_at' => now()]);
$this->event($id, $actor, 'imported', $reason, ['mapping' => $resolved, 'records' => $recordCount, 'sha256' => $sha]);
return ['id' => $id, 'status' => 'imported', 'records' => $recordCount, 'repeated' => false];
});
}
/** @param array<string,mixed> $report
* @return iterable<array<string,mixed>> */
private function recordRows(array $report, string $path): iterable
{
if (! isset($report['records_file_sha256'])) {
yield from $report['records'];
return;
}
abort_unless(is_file($path) && CheckedFile::matches($path, $report['records_file_sha256']), 409, 'As observações diferem da prévia conferida.');
$stream = new \SplFileObject($path, 'r');
while (! $stream->eof()) {
$line = $stream->fgets();
if (trim($line) === '') {
continue;
}
yield json_decode($line, true, 512, JSON_THROW_ON_ERROR);
}
}
public function transition(User $actor, string $id, string $action, string $reason): void
{
$this->authorize($actor);
DB::transaction(function () use ($actor, $id, $action, $reason) {
$batch = DB::table('demographic_imports')->where('id', $id)->lockForUpdate()->first();
abort_unless($batch !== null, 404);
abort_unless(in_array($action, ['approved', 'disabled'], true) && $batch->status !== 'prepared', 422);
abort_if($action === 'approved' && $batch->status !== 'approved' && app(PortalEditorialWorkflow::class)->demographyWrites($id), 409, 'Use a aprovação e publicação separadas do lote no circuito editorial.');
abort_if($action === 'disabled' && Schema::hasColumn('portal_editorial_editions', 'demographic_import_id') && DB::table('portal_editorial_editions')->where('demographic_import_id', $id)->exists(), 409, 'Arquive a edição no circuito editorial para retirar a sua publicação.');
// No deletes, replacement of other editions, or automatic publication in production.
DB::table('demographic_imports')->where('id', $id)->update(['status' => $action, 'updated_at' => now()]);
$this->event($id, $actor, $action, $reason, ['previous_status' => $batch->status]);
});
}
/** @param array<string,mixed> $details */
private function event(string $id, User $actor, string $action, string $reason, array $details): void
{
DB::table('demographic_events')->insert(['import_id' => $id, 'actor_id' => $actor->id, 'action' => $action, 'reason' => $reason, 'details' => json_encode($details, JSON_THROW_ON_ERROR), 'created_at' => now()]);
}
}
+307
View File
@@ -0,0 +1,307 @@
<?php
namespace App\Services;
use App\Models\User;
use App\Support\CheckedFile;
use App\Support\IsolatedQaDatabase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Symfony\Component\Process\Exception\ExceptionInterface;
use Symfony\Component\Process\Process;
/** Owner-authorised release; schema and data still require existing session MFA. */
final class DemographicInstallation
{
public const MIGRATION = '2026_11_13_100000_create_demographic_series';
public const MANICA_SHA256 = '0c6d8feaefaed797fa57d61f923af5a86f37ac4b16f12d7d72ae1be8087ea698';
public const FILES = [
'Manica.xlsx' => ['sha256' => self::MANICA_SHA256, 'records' => 71604],
'Inhambane.xlsx' => ['sha256' => '51a9b91dfb6e32e5b49def115cb007f21faa97b3d0584b16ef911b22b89bd818', 'records' => 82620],
'Dados demograficos.xlsx' => ['sha256' => '4763aaa7476f3ae24564e9750ac2ac8babb07dfbba67473a180fb9b1f47eb335', 'records' => 482],
];
/** @return array<string,mixed> */
public static function remainingManifest(): array
{
return json_decode(CheckedFile::read(database_path('data/demography-remaining-20261113.json')), true, 512, JSON_THROW_ON_ERROR);
}
/** @return array<string,mixed> */
public static function zambeziaManifest(): array
{
return json_decode(CheckedFile::read(database_path('data/demography-zambezia-20261113.json')), true, 512, JSON_THROW_ON_ERROR);
}
/** @return list<string> */
public static function publicDistrictRefs(): array
{
$refs = [self::MANICA_SHA256.':Macate', self::MANICA_SHA256.':Vanduzi'];
foreach ([self::remainingManifest(), self::zambeziaManifest()] as $manifest) {
foreach ($manifest['new_districts'] as $province => $names) {
$source = array_values(array_filter($manifest['files'], fn ($f) => $f['province'] === $province))[0]['sha256'];
foreach ($names as $name) { $refs[] = $source.':'.$name; }
}
}
return $refs;
}
/** @return list<string> */
public function files(): array
{
return ['database/data/demography-zambezia-20261113.json', 'database/data/demography-remaining-20261113.json', 'app/Services/DemographicInstallation.php', 'app/Services/DemographicImport.php', 'app/Services/DemographicEvidence.php',
'app/Services/InvestmentGeography.php', 'app/Services/InvestmentPreparationWorkspace.php', 'app/Http/Controllers/DemographyController.php',
'database/migrations/'.self::MIGRATION.'.php', 'config/demography.php', 'routes/demography.php', 'routes/web.php', 'tools/demography_workbook.py',
'resources/js/components/demographic-context.tsx', 'resources/js/components/demographic-evidence.tsx', 'resources/js/components/simulation-form.tsx',
'resources/js/components/structure-geography.tsx', 'resources/js/pages/investment/demography.tsx', 'resources/js/pages/investment/catalogue.tsx',
'resources/js/pages/investment/detail.tsx', 'resources/js/pages/management/demography.tsx', 'resources/js/pages/management/demography-install.tsx',
'resources/js/pages/management/shared.tsx'];
}
public function fingerprint(): string
{
$files = [];
foreach ($this->files() as $path) {
$files[$path] = CheckedFile::sha256(base_path($path));
}
return hash('sha256', json_encode($files, JSON_THROW_ON_ERROR));
}
public function activeTarget(): bool
{
$c = config('database.connections.pgsql');
$homologation = config('app.url') === 'https://teste-investidor.tempo.co.mz'
&& config('demography.enabled', false) && $c['database'] === 'teste_investidor';
if (app()->environment('testing') || config('database.default') !== 'pgsql' || ! empty($c['url'])
|| ! in_array($c['host'], ['127.0.0.1', 'localhost'], true) || (int) $c['port'] !== 5432
|| ($c['database'] !== 'investemoz' && ! $homologation)) {
return false;
}
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
return $target->database === $c['database'] && (int) $target->port === 5432;
}
public function schemaAllowed(): bool
{
if (IsolatedQaDatabase::allowsSchemaChanges()) {
return true;
}
$actor = auth()->user();
if (! config('demography.authenticated_installation', false) || ! $actor || ! $this->activeTarget()) {
return false;
}
app(PortalProfileInstallation::class)->authorize($actor, true);
return true;
}
private function authorize(User $actor, bool $write): void
{
app(PortalProfileInstallation::class)->authorize($actor, $write);
abort_unless($this->activeTarget() || IsolatedQaDatabase::allowsSchemaChanges(), 403, 'Destino não autorizado para esta entrega.');
}
/** @return array<string,mixed> */
public function preview(User $actor): array
{
$this->authorize($actor, false);
$proofFile = storage_path('app/private/demography-deployment/readiness.json');
$proof = is_file($proofFile) ? json_decode(CheckedFile::read($proofFile), true, 512, JSON_THROW_ON_ERROR) : [];
$code = $this->fingerprint();
$target = (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
$qa = IsolatedQaDatabase::allowsSchemaChanges();
$ready = $qa || (($proof['code_sha256'] ?? '') === $code && ($proof['qa_passed'] ?? false) && ($proof['compatibility_verified'] ?? false)
&& ($proof['restore_verified'] ?? false) && ($proof['files_verified'] ?? false) && ($proof['target']['database'] ?? '') === $target['database']
&& (int) ($proof['target']['port'] ?? 0) === (int) $target['port'] && ($proof['decision'] ?? '') !== ''
&& strtotime($proof['verified_at'] ?? '') >= time() - 86400 && strtotime($proof['verified_at'] ?? '') <= time());
if (! $qa) {
foreach (['dump', 'files'] as $kind) {
$file = $proof[$kind.'_path'] ?? '';
$ready = $ready && is_file($file) && CheckedFile::matches($file, $proof[$kind.'_sha256'] ?? '');
}
$ready = $ready && CheckedFile::matches(base_path('.env'), $proof['environment_sha256'] ?? '')
&& is_file(public_path('build/manifest.json')) && CheckedFile::matches(public_path('build/manifest.json'), $proof['release_manifest_sha256'] ?? '');
foreach ($proof['release_files'] ?? [] as $relative => $sha) {
$file = public_path('build/'.$relative);
$ready = $ready && ! str_contains($relative, '..') && ! str_contains($relative, ':') && is_file($file) && CheckedFile::matches($file, $sha);
}
}
$tables = array_map(fn ($t) => Schema::hasTable($t), ['demographic_imports', 'demographic_observations', 'demographic_events']);
$ledger = DB::table('migrations')->where('migration', self::MIGRATION)->exists();
$consistent = ($ledger && ! in_array(false, $tables, true)) || (! $ledger && ! in_array(true, $tables, true));
$preparedFiles = self::FILES + self::remainingManifest()['files'] + self::zambeziaManifest()['files'];
$runtimeReady = app(DemographicImport::class)->preparedSourcesReady($preparedFiles);
try {
if (! $runtimeReady && function_exists('proc_open')) {
$runtime = new Process([config('demography.python', 'python'), '-c', 'import sys; assert sys.version_info >= (3, 9)'], base_path(), timeout: 15);
$runtime->run();
$runtimeReady = $runtime->isSuccessful();
}
} catch (ExceptionInterface) {
$runtimeReady = false;
}
$mode = $ledger ? 'remaining' : 'initial';
$manifest = self::remainingManifest();
if ($ledger && DB::table('demographic_imports')->whereIn('sha256', array_column($manifest['files'], 'sha256'))->where('status', 'approved')->count() === count($manifest['files'])) { $mode = 'zambezia'; $manifest = self::zambeziaManifest(); }
$files = $mode !== 'initial' ? $manifest['files'] : self::FILES;
$already = $ledger ? DB::table('demographic_imports')->whereIn('sha256', array_column($files, 'sha256'))->where('status', 'approved')->pluck('sha256')->all() : [];
$pending = array_filter($files, fn ($f) => ! in_array($f['sha256'], $already, true));
$state = ['mode' => $mode, 'pending_count' => count($pending), 'aliases' => $mode !== 'initial' ? $manifest['aliases'] : [], 'alias_sources' => $mode !== 'initial' ? $manifest['sources'] : [], 'missing_province_source' => $manifest['missing_province_source'], 'target' => (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'),
'migration' => self::MIGRATION, 'code_sha256' => $code, 'backup_verified' => $ready, 'consistent' => $consistent,
'ready' => $ready && $consistent && $runtimeReady && count($pending) > 0, 'runtime_ready' => $runtimeReady, 'installed' => $ledger, 'files' => $files, 'new_districts' => $mode !== 'initial' ? array_merge(...array_values($manifest['new_districts'])) : ['Macate', 'Vanduzi'],
'mfa_confirmed' => app(PortalProfileAccess::class)->mfa($actor),
'notice' => ($runtimeReady ? '' : 'O interpretador do importador está indisponível; a execução permanece bloqueada. ').'Preservar seis advertências de Manica/2031, unidades ausentes e versões estatísticas. A instalação não corrige os originais nem concede permissões.'];
return [...$state, 'hash' => hash_hmac('sha256', json_encode([$actor->id, session()->getId(), $state], JSON_THROW_ON_ERROR), config('app.key'))];
}
/** @param list<string> $preservedHashes
* @return array<string,array{count:int,sha256:string}> */
private function protectedState(array $preservedHashes = []): array
{
$state = [];
foreach (['desk_cases', 'simulation_form_drafts', 'funding_programmes', 'funding_programme_versions', 'funding_programme_interests',
'labour_demands', 'training_capacities', 'opportunities', 'investment_dossiers', 'projects', 'economic_clusters'] as $table) {
if (Schema::hasTable($table)) {
$rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.$table.'" t ORDER BY row_to_json(t)::text');
$state[$table] = ['count' => count($rows), 'sha256' => hash('sha256', implode("\n", array_map(fn ($r) => $r->row, $rows)))];
}
}
if (Schema::hasTable('demographic_imports')) {
$ids = DB::table('demographic_imports')->whereIn('sha256', $preservedHashes ?: array_column(self::FILES, 'sha256'))->pluck('id');
foreach (['demographic_imports' => 'id', 'demographic_observations' => 'import_id', 'demographic_events' => 'import_id'] as $table => $key) {
$digest = hash_init('sha256');
$count = 0;
DB::table($table)->whereIn($key, $ids)->chunkById(500, function ($rows) use ($digest, &$count) {
foreach ($rows as $row) {
if ($count > 0) { hash_update($digest, "\n"); }
hash_update($digest, json_encode($row, JSON_THROW_ON_ERROR));
$count++;
}
});
$state['accepted_'.$table] = ['count' => $count, 'sha256' => hash_final($digest)];
}
}
return $state;
}
private function territories(User $actor): void
{
$province = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->whereRaw('lower(name)=?', ['manica'])->get(['id']);
abort_unless($province->count() === 1, 422, 'Província de Manica ambígua ou indisponível.');
foreach (['Macate', 'Vanduzi'] as $name) {
$matches = DB::table('geo_locations')->where('parent_id', $province->first()->id)->where('location_type', 'district')->whereRaw('lower(trim(name))=?', [strtolower($name)])->get();
if ($matches->isNotEmpty()) {
abort_unless($matches->count() === 1 && $matches->first()->deleted_at === null, 409, 'Cadastro territorial divergente; não restaurar nem fundir automaticamente.');
continue;
}
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $province->first()->id, 'name' => $name, 'location_type' => 'district',
'code' => 'INE-DEMOGRAPHY-'.strtoupper($name), 'source_system' => 'ine-demography', 'external_id' => self::MANICA_SHA256.':'.$name,
'data_classification' => 'public', 'version_no' => 1, 'created_at' => now(), 'updated_at' => now()]);
app(PortalProfileAccess::class)->audit($actor, 'demography_territory_created', ['territory_id' => $id, 'name' => $name,
'source_sha256' => self::MANICA_SHA256, 'decision' => 'Autorização expressa do proprietário em 13/11/2026; destino conferido pelo instalador.',
'scope' => 'Identificação territorial da série INE; sem limites geográficos ou direitos territoriais presumidos.']);
}
}
/** @param array<string,mixed> $manifest */
private function remainingTerritories(User $actor, array $manifest): void
{
foreach ($manifest['new_districts'] as $province => $names) {
$parents = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->whereRaw('lower(name)=?', [mb_strtolower($province)])->pluck('id');
abort_unless($parents->count() === 1, 409);
$source = array_values(array_filter($manifest['files'], fn ($f) => $f['province'] === $province))[0]['sha256'];
foreach ($names as $name) {
$existing = DB::table('geo_locations')->where('parent_id', $parents[0])->where('location_type', 'district')->whereRaw('lower(trim(name))=?', [mb_strtolower($name)])->get();
if ($existing->isNotEmpty()) { abort_unless($existing->count() === 1 && $existing[0]->deleted_at === null, 409); continue; }
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parents[0], 'name' => $name, 'location_type' => 'district', 'code' => 'INE-DEMOGRAPHY-'.strtoupper($name), 'source_system' => 'ine-demography', 'external_id' => $source.':'.$name, 'data_classification' => 'public', 'version_no' => 1]);
app(PortalProfileAccess::class)->audit($actor, 'demography_territory_created', ['territory_id' => $id, 'name' => $name, 'source_sha256' => $source, 'basis' => $manifest['authority']]);
}
}
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function apply(User $actor, array $input): array
{
$this->authorize($actor, true);
$data = Validator::make($input, ['hash' => 'required|string|size:64', 'operation_key' => 'required|uuid',
'mode' => 'nullable|in:initial,remaining,zambezia', 'confirm' => 'required|accepted', 'reason' => 'required|string|min:20|max:1000'])->validate();
$mode = $data['mode'] ?? 'initial';
$files = $mode === 'initial' ? self::FILES : ($mode === 'zambezia' ? self::zambeziaManifest()['files'] : self::remainingManifest()['files']);
$preservedHashes = $mode === 'zambezia' ? array_column([...self::FILES, ...self::remainingManifest()['files']], 'sha256') : array_column(self::FILES, 'sha256');
$action = $mode === 'zambezia' ? 'extend_zambezia' : ($mode === 'remaining' ? 'extend_provinces' : 'install_and_import');
$payload = hash('sha256', json_encode($mode === 'initial' ? [$actor->id, $data['reason']] : [$actor->id, $data['reason'], $mode, $files], JSON_THROW_ON_ERROR));
$existing = DB::table('audit_events')->where('source_system', 'demography-installation')->where('action', $action)->where('correlation_id', $data['operation_key'])->first();
if ($existing) {
$event = json_decode($existing->after_data, true, 512, JSON_THROW_ON_ERROR);
abort_unless((int) $existing->actor_user_id === $actor->id && hash_equals($event['payload_sha256'], $payload), 409);
return [...$event['result'], 'repeated' => true];
}
$plan = $this->preview($actor);
abort_unless($plan['ready'] && $plan['mode'] === $mode && hash_equals($plan['hash'], $data['hash']), 409, 'Consulte a prévia actual; código, destino ou provas mudaram.');
set_time_limit(300);
return DB::transaction(function () use ($actor, $data, $payload, $mode, $files, $action, $preservedHashes) {
DB::select('SELECT pg_advisory_xact_lock(131126, 100000)');
// Recheck after the lock as another request may have completed while we waited.
$existing = DB::table('audit_events')->where('source_system', 'demography-installation')->where('action', $action)->where('correlation_id', $data['operation_key'])->first();
if ($existing) {
$event = json_decode($existing->after_data, true, 512, JSON_THROW_ON_ERROR);
abort_unless((int) $existing->actor_user_id === $actor->id && hash_equals($event['payload_sha256'], $payload), 409);
return [...$event['result'], 'repeated' => true];
}
$before = $this->protectedState($preservedHashes);
$previous = config('demography.authenticated_installation');
config(['demography.authenticated_installation' => true]);
try {
if ($mode === 'initial') {
abort_unless(Artisan::call('migrate', ['--path' => 'database/migrations/'.self::MIGRATION.'.php', '--force' => true]) === 0, 500, 'Falha ao instalar a estrutura demográfica.');
} else { abort_unless(Schema::hasTable('demographic_observations'), 409); }
} finally {
config(['demography.authenticated_installation' => $previous]);
}
if ($mode === 'initial') { $this->territories($actor); } else { $this->remainingTerritories($actor, $mode === 'zambezia' ? self::zambeziaManifest() : self::remainingManifest()); }
$receipts = [];
$directory = config('demography.source_directory', 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Servicos Tempo/portal do investidor/demografia/Provincias');
$service = app(DemographicImport::class);
foreach ($files as $name => $expected) {
$old = DB::table('demographic_imports')->where('sha256', $expected['sha256'])->first();
if ($old && $old->status === 'approved') {
$count = DB::table('demographic_observations')->where('import_id', $old->id)->count();
abort_unless($count === $expected['records'], 409);
$receipts[] = ['file' => $name, 'sha256' => $expected['sha256'], 'id' => $old->id, 'records' => $count, 'preserved' => true];
continue;
}
$file = $directory.'/'.$name;
abort_unless(is_file($file) && CheckedFile::matches($file, $expected['sha256']), 409, 'O exemplar aprovado mudou: '.$name);
$plan = $service->prepare($actor, $file, $name, 'Exemplar INE fornecido pela Tempo; edição não indicada; SHA256 identifica a versão', $name === 'Dados demograficos.xlsx' ? 2017 : null);
$receipt = $service->confirm($actor, $plan['id'], $expected['sha256'], [], $data['reason']);
abort_unless($receipt['records'] === $expected['records'], 409, 'Contagem divergente da homologação: '.$name);
$service->transition($actor, $plan['id'], 'approved', $data['reason']);
$receipts[] = ['file' => $name, 'sha256' => $expected['sha256'], 'id' => $plan['id'], 'records' => $receipt['records']];
}
abort_unless($before === ($mode === 'initial' ? array_filter($this->protectedState($preservedHashes), fn ($key) => ! str_starts_with($key, 'accepted_'), ARRAY_FILTER_USE_KEY) : $this->protectedState($preservedHashes)), 409, 'Estado protegido alterado; instalação revertida.');
$result = ['installed' => true, 'target' => (array) DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port'),
'imports' => $receipts, 'protected_state' => $before, 'record_count' => array_sum(array_column($receipts, 'records')), 'at' => now()->toIso8601String()];
DB::table('audit_events')->insert(['source_system' => 'demography-installation', 'entity_type' => 'demographic_series',
'actor_user_id' => $actor->id, 'action' => $action, 'correlation_id' => $data['operation_key'], 'data_classification' => 'restricted',
'after_data' => json_encode(['payload_sha256' => $payload, 'reason' => $data['reason'], 'result' => $result], JSON_THROW_ON_ERROR)]);
return $result;
});
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
final class DeskAttachments
{
public const MIME_TYPES = ['application/pdf', 'image/png', 'image/jpeg', 'text/plain'];
public function scopedLinksInstalled(): bool
{
$indexes = DB::selectOne("SELECT to_regclass('public.desk_documents_scope_unique') AS scope, to_regclass('public.desk_documents_dossier_unique') AS dossier");
return $indexes->scope !== null && $indexes->dossier !== null;
}
/** @param array<string,mixed> $definition
* @return array<string,mixed> */
public function field(array $definition, string $key): array
{
$field = $definition['fields'][$key] ?? null;
if (! $field || $field['type'] !== 'attachment') {
throw ValidationException::withMessages(['field_key' => 'Seleccione uma pergunta de anexo da versão deste pedido.']);
}
return $field;
}
/** @param array<string,mixed> $field */
public function checkMetadata(\stdClass $document, array $field, string $path, bool $allowUnknown = false): void
{
$mime = strtolower(trim(explode(';', (string) ($document->media_type ?? ''), 2)[0]));
if (($mime === '' && ! $allowUnknown) || ($mime !== '' && ! in_array($mime, $field['mime_types'], true)) || ($document->size_bytes === null && ! $allowUnknown) || ($document->size_bytes !== null && ($document->size_bytes === false || $document->size_bytes < 0 || $document->size_bytes > $field['max_size_kb'] * 1024))) {
throw ValidationException::withMessages([$path => 'O ficheiro não corresponde aos formatos ou ao tamanho máximo desta pergunta. Escolha outro suporte; o original é conservado.']);
}
}
/** Validate references through the existing case/request boundary; no parallel document store.
* @param array<string,mixed> $payload
* @param array<string,mixed> $definition
* @return array<string,mixed> */
public function snapshot(\stdClass $request, array $payload, array $definition, bool $submitting): array
{
$applicable = app(VirtualDesk::class)->applicableFields($payload, $definition);
$snapshot = [];
$verified = [];
foreach ($definition['fields'] as $key => $field) {
if ($field['type'] !== 'attachment') {
continue;
}
$files = [];
$seen = [];
foreach ($payload[$key] ?? [] as $linkId) {
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.id', $linkId)->where('l.case_id', $request->case_id)->whereNull('d.deleted_at')
->where(fn ($q) => $q->whereNull('l.request_id')->orWhere('l.request_id', $request->id))
->first(['d.*', 'l.id as link_id', 'l.source_reference', 'l.category', 'l.valid_until as declared_valid_until', 'l.stage as linked_stage']);
if (! $document) {
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione documentos associados a este dossier e disponíveis neste pedido.']);
}
if (isset($seen[$document->id])) {
throw ValidationException::withMessages(['payload.'.$key => 'Seleccione cada ficheiro apenas uma vez nesta pergunta. Pode reutilizá-lo noutras perguntas aplicáveis.']);
}
$seen[$document->id] = true;
$active = isset($applicable[$key]);
// Hidden answers are preserved; they are not accepted as applicable evidence.
if ($active) {
$this->checkMetadata($document, $field, 'payload.'.$key, true);
}
$usable = $document->status === 'active' && $document->malware_scan_status === 'clean'
&& hash_equals(trim($document->sha256), trim((string) $document->malware_scanned_sha256));
if ($submitting && $active) {
if (! $usable) {
throw ValidationException::withMessages(['payload.'.$key => 'O suporte seleccionado ainda não está disponível com análise de segurança válida. Actualize o estado dos documentos antes de submeter.']);
}
if (! isset($verified[$document->id])) {
try {
$verificationDocument = clone $document;
$verificationDocument->media_type = $verificationDocument->media_type ?: 'application/octet-stream';
$response = app(VerifiedDocumentBinary::class)->respond($verificationDocument);
if ($response instanceof BinaryFileResponse) {
$verified[$document->id] = ['size_bytes' => $response->getFile()->getSize(), 'media_type' => (new \finfo(FILEINFO_MIME_TYPE))->file($response->getFile()->getPathname())];
} else {
$content = $response->getContent();
if (! is_string($content)) {
throw ValidationException::withMessages(['payload.'.$key => 'Não foi possível conferir o original deste suporte.']);
}
$verified[$document->id] = ['size_bytes' => strlen($content), 'media_type' => (new \finfo(FILEINFO_MIME_TYPE))->buffer($content)];
}
} catch (HttpExceptionInterface $error) {
throw ValidationException::withMessages(['payload.'.$key => 'O suporte não está disponível com a autorização e integridade exigidas. Recupere ou seleccione outro documento.']);
}
}
$this->checkMetadata((object) $verified[$document->id], $field, 'payload.'.$key);
$recordedMime = strtolower(trim(explode(';', (string) ($document->media_type ?? ''), 2)[0]));
if (($document->size_bytes !== null && $verified[$document->id]['size_bytes'] !== (int) $document->size_bytes) || ($recordedMime !== '' && $verified[$document->id]['media_type'] !== $recordedMime)) {
throw ValidationException::withMessages(['payload.'.$key => 'O formato ou tamanho do original diverge dos dados registados. Recupere ou seleccione outro documento.']);
}
}
$measured = $submitting && $active ? $verified[$document->id] : null;
$files[] = ['link_id' => $document->link_id, 'document_id' => $document->id, 'file_name' => $document->file_name,
'sha256' => trim($document->sha256), 'version_no' => $document->version_no, 'media_type' => $measured['media_type'] ?? $document->media_type,
'size_bytes' => $measured['size_bytes'] ?? $document->size_bytes, 'recorded_media_type' => $document->media_type, 'recorded_size_bytes' => $document->size_bytes, 'metadata_measured' => $measured !== null, 'source_reference' => $document->source_reference,
'valid_until' => $document->declared_valid_until, 'stage' => $document->linked_stage, 'status' => $document->status, 'malware_scan_status' => $document->malware_scan_status, 'usable_at_submission' => $submitting && $active && $usable];
}
$snapshot[$key] = ['label' => $field['label'], 'applicable' => isset($applicable[$key]), 'service_version_id' => $request->service_version_id,
'limits' => ['mime_types' => $field['mime_types'], 'max_size_kb' => $field['max_size_kb'], 'max_files' => $field['max_files']], 'files' => $files];
}
return $snapshot;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
/** Payment facts stay in desk_payments; the existing encrypted events preserve documentary uses. */
class DeskPaymentEvidence
{
/** @param array<string,mixed> $input
* @return array<string,mixed>|null
*/
public function snapshot(string $caseId, string $requestId, array $input): ?array
{
if (! ($input['document_link_id'] ?? null) && ! ($input['document_id'] ?? null)) {
return null;
}
$document = DB::table('desk_documents as l')->join('documents as d', 'd.id', '=', 'l.document_id')
->where('l.case_id', $caseId)->whereNull('d.deleted_at')
->where(fn ($q) => $q->whereNull('l.request_id')->orWhere('l.request_id', $requestId))
->when($input['document_link_id'] ?? null, fn ($q, $id) => $q->where('l.id', $id))
->when($input['document_id'] ?? null, fn ($q, $id) => $q->where('d.id', $id))
->orderBy('l.created_at')->orderBy('l.id')->first(['d.*', 'l.id as link_id', 'l.source_reference', 'l.category', 'l.stage', 'l.valid_until as declared_valid_until']);
abort_unless($document !== null, 422, 'Seleccione um comprovativo associado a este pedido ou ao seu dossier.');
app(VerifiedDocumentBinary::class)->authorizeOpportunityAttachment($document);
return ['link_id' => $document->link_id, 'document_id' => $document->id, 'file_name' => $document->file_name, 'document_version' => (int) $document->version_no,
'sha256' => trim($document->sha256), 'source_reference' => $document->source_reference, 'category' => $document->category, 'stage' => $document->stage,
'valid_until' => $document->declared_valid_until, 'status_at_association' => $document->status, 'scan_at_association' => $document->malware_scan_status,
'scope' => 'registered_document_metadata_not_binary_or_payment_confirmation'];
}
/** @return array<string,array<string,mixed>> */
public function forRequest(string $requestId): array
{
$current = [];
foreach (DB::table('desk_events')->where('request_id', $requestId)->whereIn('action', ['payment_declared', 'payment_document_linked'])->orderBy('event_order')->get(['payload']) as $event) {
$payload = app(VirtualDesk::class)->decode($event->payload);
if (is_string($payload['payment_id'] ?? null) && is_array($payload['document_evidence'] ?? null)) {
$current[$payload['payment_id']] = $payload['document_evidence'];
}
}
return $current;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
final class DeskRequestCheckpoints
{
public function installed(): bool
{
return Schema::hasTable('desk_request_checkpoints');
}
/** @return array<string,mixed> */
public function show(User $actor, string $id): array
{
$desk = app(VirtualDesk::class);
$request = $desk->request($actor, $id, true);
$case = $desk->case($actor, $request->case_id, true);
$row = $this->installed() ? DB::table('desk_request_checkpoints')->where('request_id', $id)->where('actor_id', $actor->id)->first() : null;
return ['installed' => $this->installed(), 'request' => ['id' => $id, 'version' => (int) $request->version, 'status' => $request->status,
'protocol' => $request->protocol, 'analyst_id' => $request->analyst_id, 'due_at' => $request->due_at,
'editable_fields' => json_decode($request->editable_fields ?? '[]', true), 'payload' => $desk->decode($request->payload),
'can_edit' => ! $case->closed_at && in_array($request->status, ['draft', 'returned'], true)],
'checkpoint' => $row ? ['version' => (int) $row->version, 'request_version' => (int) $row->request_version,
'updated_at' => $row->updated_at, ...$desk->decode($row->snapshot)] : null];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function save(User $actor, string $id, array $input): array
{
abort_unless($this->installed(), 409, 'A gravação automática requer a actualização de rascunhos. A gravação manual continua disponível.');
$data = Validator::make(['checkpoint' => $input], [
'checkpoint' => 'required|array:version,request_version,operation_key,payload,edited_keys,reason',
'checkpoint.version' => 'required|integer|min:0', 'checkpoint.request_version' => 'required|integer|min:1',
'checkpoint.operation_key' => 'required|uuid', 'checkpoint.payload' => 'present|array',
'checkpoint.edited_keys' => 'present|array|list|max:65', 'checkpoint.edited_keys.*' => 'required|string|distinct|max:100',
'checkpoint.reason' => 'nullable|string|max:3000',
])->validate()['checkpoint'];
return DB::transaction(function () use ($actor, $id, $data): array {
$desk = app(VirtualDesk::class);
$request = $desk->request($actor, $id, true, true);
$case = $desk->case($actor, $request->case_id, true, true);
abort_unless(! $case->closed_at && in_array($request->status, ['draft', 'returned'], true), 409, 'Este pedido já não permite alterar o rascunho.');
abort_unless((int) $request->version === (int) $data['request_version'], 409, 'O pedido mudou. Compare a versão actual antes de recuperar as suas alterações.');
$payload = $desk->checkpointFields($data['payload'], $desk->definition($request));
app(DeskAttachments::class)->snapshot($request, $payload, $desk->definition($request), false);
$allowed = [...array_keys($desk->definition($request)['fields']), 'country', 'declared_origin_country_code', 'context_reuse', 'context_opportunity', 'context_opportunity_snapshot'];
Validator::make($data, ['edited_keys.*' => [Rule::in($allowed)]])->validate();
$base = $desk->decode($request->payload);
$edited = array_values(array_unique([...$data['edited_keys'], ...array_filter(array_unique([...array_keys($base), ...array_keys($payload)]), fn ($key) => ($base[$key] ?? null) !== ($payload[$key] ?? null))]));
if ($request->status === 'returned') {
$editable = json_decode($request->editable_fields ?? '[]', true);
foreach (array_unique([...array_keys($base), ...array_keys($payload), ...$data['edited_keys']]) as $key) {
abort_if(! in_array($key, $editable, true) && ((($base[$key] ?? null) !== ($payload[$key] ?? null)) || in_array($key, $data['edited_keys'], true)), 422, 'O rascunho só pode corrigir os campos autorizados.');
}
}
$operationHash = hash('sha256', json_encode(Arr::sortRecursive(['version' => (int) $data['version'], 'request_version' => (int) $data['request_version'],
'operation_key' => $data['operation_key'], 'payload' => $payload, 'edited_keys' => $data['edited_keys'], 'reason' => $data['reason'] ?? '']), JSON_THROW_ON_ERROR));
$row = DB::table('desk_request_checkpoints')->where('request_id', $id)->where('actor_id', $actor->id)->lockForUpdate()->first();
if ($row && $row->operation_key === $data['operation_key']) {
abort_unless(hash_equals($row->operation_sha256, $operationHash), 409, 'Esta tentativa já foi usada com outros dados.');
return $this->show($actor, $id);
}
abort_unless((int) ($row->version ?? 0) === (int) $data['version'], 409, 'O rascunho mudou noutro separador. Compare antes de substituir.');
$version = (int) ($row->version ?? 0) + 1;
DB::table('desk_request_checkpoints')->updateOrInsert(['request_id' => $id, 'actor_id' => $actor->id], [
'version' => $version, 'request_version' => $request->version, 'operation_key' => $data['operation_key'], 'operation_sha256' => $operationHash,
'snapshot' => $desk->encode(['payload' => $payload, 'base_payload' => $base, 'edited_keys' => $edited, 'reason' => $data['reason'] ?? '']),
'created_at' => $row->created_at ?? now(), 'updated_at' => now(),
]);
DB::table('audit_events')->insert(['source_system' => 'virtual-desk', 'entity_type' => 'desk_request_checkpoints', 'entity_id' => $id,
'actor_user_id' => $actor->id, 'action' => 'draft_checkpoint_saved', 'data_classification' => 'restricted',
'after_data' => json_encode(['version' => $version, 'request_version' => (int) $request->version], JSON_THROW_ON_ERROR)]);
return $this->show($actor, $id);
});
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Services;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/** One applicable edition per service. Existing requests keep their immutable version FK. */
final class DeskServiceAvailability
{
public function scheduled(): bool
{
return Schema::hasColumn('desk_service_versions', 'effective_from');
}
public function current(): Builder
{
$query = DB::table('desk_service_versions')->where('status', 'published')
->where(fn (Builder $date) => $date->whereNull('published_at')->orWhere('published_at', '<=', now()))
->selectRaw('DISTINCT ON (code) *')->orderBy('code');
if ($this->scheduled()) {
$query->where(fn (Builder $date) => $date->whereNull('effective_from')->orWhere('effective_from', '<=', now()->toDateString()))
->orderByRaw('effective_from DESC NULLS LAST');
}
return $query->orderByDesc('version');
}
public function upcoming(): Builder
{
$query = DB::table('desk_service_versions');
if (! $this->scheduled()) {
return $query->whereRaw('false')->select('code', 'version')->selectRaw('NULL::date AS effective_from');
}
return $query->where('status', 'published')->where('effective_from', '>', now()->toDateString())
->where(fn (Builder $date) => $date->whereNull('published_at')->orWhere('published_at', '<=', now()))
->selectRaw('DISTINCT ON (code,effective_from) code,version,effective_from')->orderBy('code')->orderBy('effective_from')->orderByDesc('version');
}
/** @return literal-string */
public function dateProjection(): string
{
return $this->scheduled() ? 'effective_from' : 'NULL::date AS effective_from';
}
}
+274
View File
@@ -0,0 +1,274 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
final class DeskServiceEditor
{
/** @return list<array<string,mixed>> */
public function listing(): array
{
$availability = app(DeskServiceAvailability::class);
$active = $availability->current()->get()->keyBy('code');
$upcoming = $availability->upcoming()->get()->groupBy('code')->map(fn ($rows) => $rows->map(fn ($row) => ['version' => (int) $row->version, 'effective_from' => $row->effective_from])->all());
$rows = DB::table('desk_service_versions')->selectRaw('DISTINCT ON (code) code, version, definition')
->selectRaw($availability->dateProjection())
->orderBy('code')->orderByDesc('version')->get()->keyBy('code');
$services = [];
foreach (config('virtual-desk.services') as $code => $initial) {
$row = $rows->get($code);
$services[] = ['code' => $code, 'version' => (int) ($row->version ?? 0), 'editable' => true,
'effective_from' => $row->effective_from ?? null, 'activeVersion' => (int) ($active->get($code)->version ?? 0),
'upcoming' => $upcoming->get($code, []),
'fixedTypes' => array_map(fn (array $field) => $field['type'], $initial['fields']),
'definition' => $row ? json_decode($row->definition, true, 512, JSON_THROW_ON_ERROR) : $initial];
}
foreach ($rows as $code => $row) {
if (! array_key_exists($code, config('virtual-desk.services'))) {
$services[] = ['code' => $code, 'version' => (int) $row->version, 'editable' => false,
'effective_from' => $row->effective_from ?? null, 'activeVersion' => (int) ($active->get($code)->version ?? 0),
'upcoming' => $upcoming->get($code, []),
'definition' => json_decode($row->definition, true, 512, JSON_THROW_ON_ERROR)];
}
}
return $services;
}
/** @return array<string,mixed> */
public function history(string $code, int $requestedPage): array
{
abort_unless(array_key_exists($code, config('virtual-desk.services')) || DB::table('desk_service_versions')->where('code', $code)->exists(), 404);
$query = DB::table('desk_service_versions')->where('code', $code);
$total = (clone $query)->count();
$pages = max(1, (int) ceil($total / 10));
$page = min(max(1, $requestedPage), $pages);
$rows = $query->orderByDesc('version')->forPage($page, 10)->select(['id', 'version', 'status', 'author_id', 'published_by', 'published_at', 'definition', 'source'])
->selectRaw(app(DeskServiceAvailability::class)->dateProjection())->get();
$events = DB::table('audit_events')->where('source_system', 'virtual-desk')->where('entity_type', 'desk_service_versions')
->where('action', 'service_definition_version_published')->whereIn('entity_id', $rows->pluck('id')->all())
->get(['entity_id', 'after_data'])->keyBy('entity_id');
return ['page' => $page, 'pages' => $pages, 'total' => $total, 'data' => $rows->map(function ($row) use ($events): array {
$event = $events->get($row->id);
$audit = $event ? json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR) : [];
return ['id' => $row->id, 'version' => (int) $row->version, 'status' => $row->status,
'author_id' => $row->author_id, 'published_by' => $row->published_by, 'published_at' => $row->published_at,
'definition' => json_decode($row->definition, true, 512, JSON_THROW_ON_ERROR),
'effective_from' => $row->effective_from,
'source' => json_decode($row->source, true, 512, JSON_THROW_ON_ERROR), 'reason' => $audit['reason'] ?? null];
})->all()];
}
/** @param array<string,mixed> $input */
public function publish(User $actor, string $code, array $input): \stdClass
{
abort_unless(array_key_exists($code, config('virtual-desk.services')), 404);
$data = Validator::make($input, [
'base_version' => ['required', 'integer', 'min:0'], 'confirm' => ['accepted'],
'effective_from' => ['nullable', 'date_format:Y-m-d'],
'reason' => ['required', 'string', 'min:20', 'max:2000'],
'definition' => ['required', 'array:title,theme,profile,stage,entity,result,fields'],
'definition.title' => ['required', 'string', 'max:200'],
'definition.theme' => ['required', 'string', 'max:150'],
'definition.profile' => ['required', 'string', 'max:200'],
'definition.stage' => ['required', 'string', 'max:20'],
'definition.entity' => ['required', 'string', 'max:300'],
'definition.result' => ['required', 'string', 'max:2000'],
'definition.fields' => ['required', 'array', 'min:1', 'max:60'],
'definition.fields.*' => ['required', 'array:label,type,required,min,options,when,statement,mime_types,max_size_kb,max_files'],
'definition.fields.*.label' => ['required', 'string', 'max:300'],
'definition.fields.*.type' => ['required', Rule::in(['text', 'textarea', 'email', 'tel', 'url', 'number', 'date', 'select', 'multiselect', 'consent', 'territory', 'attachment'])],
'definition.fields.*.mime_types' => ['sometimes', 'array', 'list', 'min:1', 'max:4'],
'definition.fields.*.mime_types.*' => ['required', 'string', Rule::in(DeskAttachments::MIME_TYPES)],
'definition.fields.*.max_size_kb' => ['sometimes', 'integer', 'min:1', 'max:10240'],
'definition.fields.*.max_files' => ['sometimes', 'integer', 'min:1', 'max:100'],
'definition.fields.*.statement' => ['sometimes', 'string', 'min:3', 'max:5000'],
'definition.fields.*.required' => ['required', 'boolean'],
'definition.fields.*.min' => ['sometimes', 'numeric', 'min:0', 'max:999999999999'],
'definition.fields.*.options' => ['sometimes', 'array', 'min:1', 'max:100'],
'definition.fields.*.options.*' => ['required', 'string', 'max:300'],
'definition.fields.*.when' => ['sometimes', 'array:field,equals,operator', 'required_array_keys:field,equals'],
'definition.fields.*.when.operator' => ['sometimes', Rule::in(['equals', 'contains'])],
'definition.fields.*.when.field' => ['required_with:definition.fields.*.when', 'string', 'max:64'],
'definition.fields.*.when.equals' => ['required_with:definition.fields.*.when', 'string', 'max:1000'],
])->validate();
$this->checkFields($data['definition']['fields']);
return DB::transaction(function () use ($actor, $code, $data): \stdClass {
DB::select('select pg_advisory_xact_lock(261008, 2)');
$scheduled = app(DeskServiceAvailability::class)->scheduled();
if (! $scheduled && ($data['effective_from'] ?? null) !== null) {
throw ValidationException::withMessages(['effective_from' => 'Instale a actualização das datas de entrada em vigor antes de agendar uma versão.']);
}
$latest = DB::table('desk_service_versions')->where('code', $code)->orderByDesc('version')->first();
$previous = $latest ? json_decode($latest->definition, true, 512, JSON_THROW_ON_ERROR) : config('virtual-desk.services.'.$code);
if ($data['definition']['stage'] !== $previous['stage']) {
throw ValidationException::withMessages(['definition.stage' => 'A etapa pertence ao percurso existente e não pode ser alterada neste editor.']);
}
foreach (config('virtual-desk.services.'.$code.'.fields') as $key => $canonical) {
if (isset($data['definition']['fields'][$key]) && $data['definition']['fields'][$key]['type'] !== $canonical['type']) {
throw ValidationException::withMessages(['definition.fields.'.$key.'.type' => 'Este identificador é interpretado pelo motor existente. Conserve o tipo ou acrescente um novo campo com outro identificador.']);
}
}
// Retry of the same confirmed publication preserves the first version and authorship.
if ($latest && (int) $latest->version === (int) $data['base_version'] + 1 && $latest->status === 'published'
&& $this->sameEffectiveRequest($latest, $data, $scheduled)
&& $this->definitionHash(json_decode($latest->definition, true, 512, JSON_THROW_ON_ERROR)) === $this->definitionHash($data['definition'])) {
return $latest;
}
abort_unless((int) ($latest->version ?? 0) === (int) $data['base_version'], 409, 'O formulário foi alterado. Recarregue e compare a versão actual antes de publicar.');
if (($data['effective_from'] ?? null) !== null && $data['effective_from'] < now()->toDateString()) {
throw ValidationException::withMessages(['effective_from' => 'Uma nova publicação começa hoje ou numa data futura; não altera a vigência de pedidos anteriores.']);
}
$effective = ($data['effective_from'] ?? null) ?: now()->toDateString();
if ($latest && $latest->status === 'published' && $this->definitionHash($previous) === $this->definitionHash($data['definition'])
&& (! $scheduled || ($latest->effective_from ?? null) === $effective || (! ($data['effective_from'] ?? null) && (! ($latest->effective_from ?? null) || $latest->effective_from <= now()->toDateString())))) {
throw ValidationException::withMessages(['definition' => 'Não há alterações na definição ou na data de início para publicar uma nova versão.']);
}
$id = (string) Str::uuid();
DB::table('desk_service_versions')->insert([
'id' => $id, 'code' => $code, 'version' => (int) $data['base_version'] + 1, 'status' => 'published',
...($scheduled ? ['effective_from' => $effective] : []),
'definition' => json_encode($data['definition'], JSON_THROW_ON_ERROR),
'source' => $latest->source ?? json_encode(config('virtual-desk.source'), JSON_THROW_ON_ERROR),
'author_id' => $actor->id, 'published_by' => $actor->id, 'published_at' => now(), 'created_at' => now(), 'updated_at' => now(),
]);
DB::table('audit_events')->insert([
'source_system' => 'virtual-desk', 'entity_type' => 'desk_service_versions', 'entity_id' => $id, 'actor_user_id' => $actor->id,
'action' => 'service_definition_version_published',
'before_data' => json_encode(['id' => $latest?->id, 'version' => (int) $data['base_version']], JSON_THROW_ON_ERROR),
'after_data' => json_encode(['code' => $code, 'version' => (int) $data['base_version'] + 1, 'reason' => $data['reason'],
'effect' => 'new_requests_only', 'effective_from' => $scheduled ? $effective : null,
'effective_request_mode' => ($data['effective_from'] ?? null) ? 'dated' : 'immediate',
'selection' => 'latest_started_effective_date_then_version; undated_legacy_fallback',
'definition_sha256' => $this->definitionHash($data['definition'])], JSON_THROW_ON_ERROR),
]);
return DB::table('desk_service_versions')->where('id', $id)->firstOrFail();
});
}
/** @param array<array-key,mixed> $definition */
private function definitionHash(array $definition): string
{
return hash('sha256', json_encode(Arr::sortRecursive($definition), JSON_THROW_ON_ERROR));
}
/** PostgreSQL JSONB does not retain object-key order.
* @param array<array-key,mixed> $left
* @param array<array-key,mixed> $right */
public function sameDefinition(array $left, array $right): bool
{
return $this->definitionHash($left) === $this->definitionHash($right);
}
/** @param array<string,mixed> $data */
private function sameEffectiveRequest(\stdClass $latest, array $data, bool $scheduled): bool
{
if (! $scheduled || ($latest->effective_from ?? null) === null) {
return ! ($data['effective_from'] ?? null);
}
if ($data['effective_from'] ?? null) {
return $latest->effective_from === $data['effective_from'];
}
$event = DB::table('audit_events')->where('source_system', 'virtual-desk')->where('entity_type', 'desk_service_versions')
->where('entity_id', $latest->id)->where('action', 'service_definition_version_published')->orderByDesc('id')->value('after_data');
return $event && (json_decode($event, true, 512, JSON_THROW_ON_ERROR)['effective_request_mode'] ?? null) === 'immediate';
}
/** @param array<string,array<string,mixed>> $fields */
private function checkFields(array $fields): void
{
foreach ($fields as $key => $field) {
$path = 'definition.fields.'.$key;
if ($field['type'] === 'attachment') {
if (count(array_unique($field['mime_types'] ?? [])) !== count($field['mime_types'] ?? [])) {
throw ValidationException::withMessages([$path.'.mime_types' => 'Escolha cada formato apenas uma vez nesta pergunta.']);
}
if (! isset($field['mime_types'],$field['max_size_kb'],$field['max_files'])) {
throw ValidationException::withMessages([$path => 'Defina os formatos, tamanho por ficheiro e quantidade máxima desta pergunta.']);
}
if (! app(DeskAttachments::class)->scopedLinksInstalled()) {
throw ValidationException::withMessages([$path => 'Instale a actualização dos vínculos documentais antes de publicar perguntas de anexos. Os formulários existentes continuam disponíveis.']);
}
} elseif (array_intersect(['mime_types', 'max_size_kb', 'max_files'], array_keys($field))) {
throw ValidationException::withMessages([$path => 'Os limites de ficheiros pertencem apenas a perguntas de anexos.']);
}
if (! preg_match('/^[a-z][a-z0-9_]{0,63}$/D', (string) $key) || in_array($key, ['country', 'declared_origin_country_code', 'context_reuse', 'context_opportunity', 'context_opportunity_snapshot'], true)) {
throw ValidationException::withMessages(['definition.fields' => 'Use identificadores de campo distintos dos campos comuns de país e contexto, com letras minúsculas, números e sublinhado.']);
}
if (in_array($field['type'], ['select', 'multiselect'], true) && empty($field['options'])) {
throw ValidationException::withMessages([$path.'.options' => 'Indique as opções deste campo.']);
}
if ((isset($field['min']) && $field['type'] !== 'number') || (isset($field['options']) && ! in_array($field['type'], ['select', 'multiselect'], true))) {
throw ValidationException::withMessages([$path => 'O mínimo aplica-se apenas a números e as opções apenas a listas de respostas.']);
}
if (($field['type'] === 'consent' && trim($field['statement'] ?? '') === '') || (isset($field['statement']) && $field['type'] !== 'consent')) {
throw ValidationException::withMessages([$path.'.statement' => 'Uma declaração de consentimento exige o texto exacto a apresentar; esse texto pertence apenas a campos de consentimento.']);
}
foreach (array_keys($field['options'] ?? []) as $option) {
if (! preg_match('/^[a-zA-Z0-9_-]{1,80}$/D', (string) $option)) {
throw ValidationException::withMessages([$path.'.options' => 'Use códigos de opção sem espaços ou pontuação especial.']);
}
}
$visited = [$key];
$node = $field;
while (isset($node['when'])) {
$parent = $node['when']['field'];
if (! isset($fields[$parent]) || in_array($parent, $visited, true)) {
throw ValidationException::withMessages([$path.'.when' => 'A condição deve referir outro campo existente, sem dependências circulares.']);
}
if (in_array($fields[$parent]['type'], ['number', 'attachment'], true)) {
throw ValidationException::withMessages([$path.'.when' => 'Use uma resposta de texto, lista ou declaração como origem da condição; números e anexos não são respostas comparáveis por estas condições.']);
}
$operator = $node['when']['operator'] ?? 'equals';
if (($fields[$parent]['type'] === 'multiselect') !== ($operator === 'contains')) {
throw ValidationException::withMessages([$path.'.when' => 'Use inclusão de uma opção para uma selecção múltipla e igualdade para respostas simples.']);
}
if (in_array($fields[$parent]['type'], ['select', 'multiselect'], true) && ! array_key_exists($node['when']['equals'], $fields[$parent]['options'] ?? [])) {
throw ValidationException::withMessages([$path.'.when' => 'O valor da condição deve corresponder a uma opção do campo escolhido.']);
}
if ($fields[$parent]['type'] === 'consent' && ! in_array($node['when']['equals'], ['accepted', 'declined'], true)) {
throw ValidationException::withMessages([$path.'.when' => 'Compare a declaração com accepted ou declined; uma resposta por preencher não é aceitação.']);
}
$visited[] = $parent;
$node = $fields[$parent];
}
}
if (isset($fields['territory_id'])) {
if (! isset($fields['location_source'])) {
throw ValidationException::withMessages(['definition.fields.location_source' => 'A localização exige a respectiva fonte. Mantenha o campo da fonte ou retire também a localização.']);
}
$locationConditions = $this->conditions('territory_id', $fields);
$sourceConditions = $this->conditions('location_source', $fields);
if (array_diff_assoc($sourceConditions, $locationConditions) !== []) {
throw ValidationException::withMessages(['definition.fields.location_source.when' => 'A fonte tem de estar disponível sempre que a localização se aplica. Use as mesmas condições ou condições mais abrangentes.']);
}
}
}
/** Conditions have already been checked for valid references and cycles.
* @param array<string,array<string,mixed>> $fields
* @return array<string,string> */
private function conditions(string $key, array $fields): array
{
$conditions = [];
while (isset($fields[$key]['when'])) {
$when = $fields[$key]['when'];
$conditions[$when['field']] = ($when['operator'] ?? 'equals').':'.$when['equals'];
$key = $when['field'];
}
return $conditions;
}
}
@@ -11,6 +11,13 @@ use Illuminate\Support\Str;
class DocumentManagementAccess class DocumentManagementAccess
{ {
/** Existing editorial publication authority; it does not grant financial decision powers. */
public function catalogueEditor(?User $actor): bool
{
return $actor && $actor->hasVerifiedEmail() && ! app(PortalProfileAccess::class)->has($actor, 'auditor')
&& ($this->full($actor) || $this->editorial($actor));
}
public function full(User $actor): bool public function full(User $actor): bool
{ {
return Gate::forUser($actor)->allows('manage-portal'); return Gate::forUser($actor)->allows('manage-portal');
+22
View File
@@ -11,6 +11,28 @@ use Illuminate\Support\Facades\Schema;
/** Shared read contract. It deliberately has no dependency on the installation controller/service. */ /** Shared read contract. It deliberately has no dependency on the installation controller/service. */
class EconomicReferenceCatalog class EconomicReferenceCatalog
{ {
/** Accepted source hierarchy for the private aggregate adapter; no catalogue publication or writes.
* @return array{source_sha256:string,nodes:list<array{id:string,code:string,label:string,group:string,group_code:string,group_label:string}>}
*/
public function supplyClassification(): array
{
$data = json_decode(CheckedFile::read(database_path('data/proactive-supply-classification.json')), true, 512, JSON_THROW_ON_ERROR);
abort_unless(($data['format'] ?? null) === 'accepted-source-classification-v1'
&& ($data['source_sha256'] ?? null) === '83b4f1200988e99834c2ae3915346fbf237d128308554b67b5a080d4956bf506', 503);
$nodes = [];
foreach ($data['nodes'] ?? [] as $node) {
if (! is_array($node) || ! is_string($node['id'] ?? null) || ! is_string($node['code'] ?? null)
|| ! is_string($node['label'] ?? null) || ! is_string($node['group'] ?? null)
|| ! is_string($node['group_code'] ?? null) || ! is_string($node['group_label'] ?? null)) {
abort(503, 'Referência de classificação indisponível.');
}
$nodes[] = ['id' => $node['id'], 'code' => $node['code'], 'label' => $node['label'], 'group' => $node['group'], 'group_code' => $node['group_code'], 'group_label' => $node['group_label']];
}
return ['source_sha256' => '83b4f1200988e99834c2ae3915346fbf237d128308554b67b5a080d4956bf506', 'nodes' => $nodes];
}
public const LOT = 'lot-01'; public const LOT = 'lot-01';
public const SOURCE = 'economic-reference-lot-01'; public const SOURCE = 'economic-reference-lot-01';
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Services;
use App\Models\User;
/** Existing internal administration; does not establish an institutional mandate. */
final class EducationAccess
{
public function allows(User $actor): bool
{
return $actor->hasVerifiedEmail() && ! app(PortalProfileAccess::class)->has($actor, 'auditor')
&& ($actor->can('manage-portal') || app(ScopedPortalAdministration::class)->administrative($actor));
}
public function authorize(User $actor): void
{
abort_unless(config('education.enabled'), 404);
abort_unless($this->allows($actor), 403);
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Services;
use App\Models\LabourDemand;
use App\Models\TrainingCapacity;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
final class EducationDeclarationDrafts
{
public function installed(): bool
{
return Schema::hasTable('education_declaration_drafts');
}
public function guard(User $actor, string $kind): void
{
abort_unless(config('education.enabled') && $this->installed() && in_array($kind, ['demands', 'capacities'], true), 404);
app(EducationAccess::class)->authorize($actor);
}
/** @return array<string,mixed> */
public function show(User $actor, string $kind, string $id): array
{
$this->guard($actor, $kind);
$row = DB::table('education_declaration_drafts')->where('id', $id)->where('owner_user_id', $actor->id)->where('kind', $kind)->firstOrFail();
return ['id' => $id, 'kind' => $kind, 'version_no' => (int) $row->version_no, 'state' => $row->state,
'payload' => $this->decode($row->payload),
'references' => $row->reference_snapshot ? json_decode(Crypt::decryptString($row->reference_snapshot), true, 512, JSON_THROW_ON_ERROR) : null,
'record_id' => $row->demand_id ?? $row->capacity_id, 'updated_at' => CarbonImmutable::parse($row->updated_at)->toIso8601String()];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function save(User $actor, string $kind, ?string $id, array $input): array
{
$this->guard($actor, $kind);
$data = Validator::make($input, ['version_no' => 'required|integer|min:0', 'client_key' => $id ? 'sometimes|uuid' : 'required|uuid', 'payload' => 'present|array'])->validate();
$payload = $this->partial($kind, $data['payload']);
return DB::transaction(function () use ($actor, $kind, $id, $data, $payload): array {
DB::table('users')->where('id', $actor->id)->lock('FOR NO KEY UPDATE')->firstOrFail();
$query = DB::table('education_declaration_drafts')->where('owner_user_id', $actor->id);
$row = $id ? $query->where('id', $id)->where('kind', $kind)->lockForUpdate()->firstOrFail()
: $query->where('client_key', $data['client_key'])->lockForUpdate()->first();
abort_if($row && ($row->kind !== $kind || $row->state !== 'draft'), 409, 'Este rascunho já foi submetido ou pertence a outro tipo de declaração.');
if ($row && Arr::sortRecursive($this->decode($row->payload)) === Arr::sortRecursive($payload)
&& in_array((int) $data['version_no'], [(int) $row->version_no, (int) $row->version_no - 1], true)) {
return $this->show($actor, $kind, $row->id);
}
abort_unless((int) ($row->version_no ?? 0) === (int) $data['version_no'], 409, 'O rascunho mudou. Recupere a versão actual antes de guardar.');
$id = $row->id ?? (string) Str::uuid();
DB::table('education_declaration_drafts')->updateOrInsert(['id' => $id], ['owner_user_id' => $actor->id, 'client_key' => $row->client_key ?? $data['client_key'],
'kind' => $kind, 'version_no' => (int) ($row->version_no ?? 0) + 1, 'payload' => Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR)),
'state' => 'draft', 'created_at' => $row->created_at ?? now(), 'updated_at' => now()]);
$this->audit($actor, $id, 'draft_saved', (int) ($row->version_no ?? 0) + 1, $kind);
return $this->show($actor, $kind, $id);
});
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function submit(User $actor, string $kind, string $id, array $input): array
{
$this->guard($actor, $kind);
$data = Validator::make($input, ['version_no' => 'required|integer|min:1', 'payload' => 'present|array'])->validate();
$payload = $this->partial($kind, $data['payload']);
return DB::transaction(function () use ($actor, $kind, $id, $data, $payload): array {
DB::table('users')->where('id', $actor->id)->lock('FOR NO KEY UPDATE')->firstOrFail();
$row = DB::table('education_declaration_drafts')->where('id', $id)->where('owner_user_id', $actor->id)->where('kind', $kind)->lockForUpdate()->firstOrFail();
if ($row->state === 'submitted') {
abort_unless(in_array((int) $data['version_no'], [(int) $row->version_no, (int) $row->version_no - 1], true)
&& Arr::sortRecursive($this->decode($row->payload)) === Arr::sortRecursive($payload), 409);
return $this->show($actor, $kind, $id);
}
abort_unless((int) $row->version_no === (int) $data['version_no'], 409, 'O rascunho mudou. Recupere a versão actual antes de submeter.');
$validated = Validator::make($payload, EducationDeclarationRules::forKind($kind))->validate();
$references = [];
foreach (['occupation_id' => 'occupations', 'skill_id' => 'skills', $kind === 'demands' ? 'project_id' : 'course_id' => $kind === 'demands' ? 'projects' : 'courses'] as $field => $table) {
$source = DB::table($table)->where('id', $validated[$field])->firstOrFail();
$references[$field] = array_intersect_key((array) $source, array_flip(['id', 'name', 'title', 'code', 'provider_id', 'updated_at']));
}
$references['territory_path'] = array_map(fn ($node) => ['id' => $node->id, 'name' => $node->name, 'type' => $node->location_type], app(InvestmentGeography::class)->path($validated['geo_location_id'], true));
$record = $kind === 'demands' ? new LabourDemand : new TrainingCapacity;
PortalAudit::save($record, [...$validated, 'submitted_by' => $actor->id, 'status' => 'submitted'], $actor->id);
DB::table('education_declaration_drafts')->where('id', $id)->update(['payload' => Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR)),
'reference_snapshot' => Crypt::encryptString(json_encode($references, JSON_THROW_ON_ERROR)),
'state' => 'submitted', 'version_no' => (int) $row->version_no + 1, $kind === 'demands' ? 'demand_id' : 'capacity_id' => $record->id, 'updated_at' => now()]);
$this->audit($actor, $id, 'draft_submitted', (int) $row->version_no + 1, $kind);
return $this->show($actor, $kind, $id);
});
}
/** @param array<string,mixed> $payload
* @return array<string,mixed> */
private function partial(string $kind, array $payload): array
{
unset($payload[$kind === 'demands' ? 'course_id' : 'project_id']);
if ($kind === 'capacities') {
unset($payload['employer']);
}
$rules = ['occupation_id' => 'nullable|uuid', 'skill_id' => 'nullable|uuid', 'geo_location_id' => 'nullable|uuid',
$kind === 'demands' ? 'project_id' : 'course_id' => 'nullable|uuid', 'qualification' => 'nullable|string|max:150',
'quantity' => 'nullable|integer|min:0|max:10000000', 'period_start' => 'nullable|date_format:Y-m-d', 'period_end' => 'nullable|date_format:Y-m-d',
'source' => 'nullable|string|max:5000', 'reference_date' => 'nullable|date_format:Y-m-d', 'valid_until' => 'nullable|date_format:Y-m-d'];
if ($kind === 'demands') {
$rules['employer'] = 'nullable|string|max:200';
}
Validator::make(['payload' => $payload], ['payload' => 'array:'.implode(',', array_keys($rules))])->validate();
return Validator::make($payload, $rules)->validate();
}
private function audit(User $actor, string $id, string $action, int $version, string $kind): void
{
DB::table('audit_events')->insert(['source_system' => 'education-drafts', 'entity_type' => 'education_declaration_drafts', 'entity_id' => $id,
'actor_user_id' => $actor->id, 'action' => $action, 'data_classification' => 'restricted', 'after_data' => json_encode(['version_no' => $version, 'kind' => $kind], JSON_THROW_ON_ERROR)]);
}
/** @return array<string,mixed> */
private function decode(string $encrypted): array
{
$payload = json_decode(Crypt::decryptString($encrypted), true, 512, JSON_THROW_ON_ERROR);
if (! is_array($payload)) {
throw new \UnexpectedValueException('Invalid education draft payload.');
}
return $payload;
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Services;
use App\Models\TrainingProvider;
use Illuminate\Validation\Rule;
final class EducationDeclarationRules
{
/** @return array<string,mixed> */
public static function forKind(string $kind): array
{
abort_unless(in_array($kind, ['demands', 'capacities'], true), 404);
$demand = $kind === 'demands';
return [
'occupation_id' => ['required', 'uuid', Rule::exists('occupations', 'id')->whereNull('deleted_at')],
'skill_id' => ['required', 'uuid', Rule::exists('skills', 'id')->whereNull('deleted_at')],
'geo_location_id' => ['required', 'uuid', Rule::exists('geo_locations', 'id')->whereNull('deleted_at')->whereIn('location_type', ['province', 'district', 'admin_post', 'locality'])],
$demand ? 'project_id' : 'course_id' => ['required', 'uuid', $demand ? Rule::exists('projects', 'id')->whereNull('deleted_at')
: Rule::exists('courses', 'id')->whereNull('deleted_at')->whereNot('status', 'retired')->where(fn ($query) => $query->whereIn('provider_id', TrainingProvider::where('status', '!=', 'inactive')->select('id')))],
'employer' => [$demand ? 'required' : 'exclude', 'string', 'max:200'],
'qualification' => ['required', 'string', 'max:150'], 'quantity' => ['required', 'integer', 'min:1', 'max:10000000'],
'period_start' => ['required', 'date_format:Y-m-d'], 'period_end' => ['required', 'date_format:Y-m-d', 'after_or_equal:period_start'],
'source' => ['required', 'string', 'min:10', 'max:5000'], 'reference_date' => ['required', 'date_format:Y-m-d', 'before_or_equal:today'],
'valid_until' => ['required', 'date_format:Y-m-d', 'after_or_equal:reference_date'],
];
}
}
+232
View File
@@ -0,0 +1,232 @@
<?php
namespace App\Services;
use App\Models\LabourDemand;
use App\Models\TrainingCapacity;
use App\Models\User;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use JsonException;
final class EducationReviews
{
private const SOURCE = 'portal-education-review';
/** @param array<string,mixed> $input
* @return array{version:int,replayed:bool} */
public function decide(User $actor, string $kind, string $id, array $input): array
{
app(EducationAccess::class)->authorize($actor);
$data = Validator::make($input, ['client_key' => 'nullable|uuid', 'version_no' => 'required|integer|min:1', 'status' => 'required|in:reviewed,rejected', 'review_reason' => 'required|string|min:15|max:3000'])->validate();
$key = is_string($data['client_key'] ?? null) ? strtolower($data['client_key']) : null;
$hash = hash('sha256', json_encode(['version_no' => (int) $data['version_no'], 'status' => $data['status'], 'review_reason' => trim($data['review_reason'])], JSON_THROW_ON_ERROR));
$model = match ($kind) {
'demands' => LabourDemand::class,'capacities' => TrainingCapacity::class,default => abort(404)
};
return DB::transaction(function () use ($actor, $model, $id, $data, $key, $hash) {
$record = $model::lockForUpdate()->findOrFail($id);
if ($key !== null) {
$event = DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)->where('entity_type', $record->getTable())->where('entity_id', $id)->where('action', 'review_committed')
->whereRaw("after_data->'education_review'->>'key' = ?", [$key])->selectRaw("after_data->'education_review'->>'hash' AS hash,after_data->'education_review'->'version' AS version")->first();
if ($event) {
abort_unless($event->hash === $hash, 409, 'Esta tentativa de revisão já foi usada com outros dados. Compare antes de continuar.');
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
abort_unless(is_int($version) && $version > 0, 409, 'A revisão anterior não pôde ser identificada com segurança.');
return ['version' => $version, 'replayed' => true];
}
}
abort_if((int) $record->getAttribute('submitted_by') === $actor->id, 403, 'Outro gestor deve efectuar a revisão.');
abort_if((int) $record->getAttribute('version_no') !== (int) $data['version_no'], 409, 'A versão foi alterada. Compare os dados actuais antes de decidir.');
abort_if($record->getAttribute('valid_until') < now()->toDateString(), 422, 'A fonte expirou.');
$version = (int) $data['version_no'] + 1;
$before = ['version' => (int) $record->getAttribute('version_no'), 'status' => $record->getAttribute('status'), 'review_reason' => $record->getAttribute('review_reason'), 'reviewed_by' => $record->getAttribute('reviewed_by')];
$subject = Arr::only($record->getAttributes(), ['id', 'project_id', 'course_id', 'occupation_id', 'skill_id', 'geo_location_id', 'employer', 'qualification', 'quantity', 'period_start', 'period_end', 'source', 'reference_date', 'valid_until', 'submitted_by']);
PortalAudit::save($record, ['status' => $data['status'], 'review_reason' => trim($data['review_reason']), 'version_no' => $version, 'reviewed_by' => $actor->id], $actor->id);
$snapshot = ['subject' => $subject, 'before' => $before, 'after' => ['version' => $version, 'status' => $data['status'], 'review_reason' => $record->getAttribute('review_reason'), 'reviewed_by' => $actor->id]];
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'actor_user_id' => $actor->id, 'entity_type' => $record->getTable(), 'entity_id' => $id, 'action' => 'review_committed', 'data_classification' => 'restricted',
'after_data' => json_encode(['education_review' => ['key' => $key, 'hash' => $key !== null ? $hash : null, 'version' => $version, 'snapshot' => Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR))]], JSON_THROW_ON_ERROR)]);
return ['version' => $version, 'replayed' => false];
});
}
/** Private preparation only; never a decision or an authority grant.
* @return array<string,mixed> */
public function preparation(User $actor, LabourDemand|TrainingCapacity $record): array
{
app(EducationAccess::class)->authorize($actor);
$event = $this->preparations($actor, $record)->orderByRaw("CASE WHEN (after_data->'education_preparation'->>'version') ~ '^[0-9]{1,10}$' THEN (after_data->'education_preparation'->>'version')::bigint END DESC NULLS LAST")->orderByDesc('occurred_at')->orderByDesc('id')->first(['after_data']);
$value = $event ? json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR)['education_preparation'] : null;
$snapshot = null;
$unavailable = false;
if ($value) {
try {
$decoded = json_decode(Crypt::decryptString($value['snapshot']), true, 512, JSON_THROW_ON_ERROR);
$snapshot = Validator::make(['snapshot' => $decoded], $this->preparationRules($decoded))->validate()['snapshot'];
} catch (DecryptException|JsonException|ValidationException) {
$unavailable = true;
}
}
// Empty reference maps remain JSON objects in the browser, like the declaration props.
if (is_array($snapshot)) {
if ($snapshot['base']['references'] === []) {
$snapshot['base']['references'] = (object) [];
}
if (is_array($snapshot['pending']) && $snapshot['pending']['base']['references'] === []) {
$snapshot['pending']['base']['references'] = (object) [];
}
}
return ['actor_id' => $actor->id, 'kind' => $record instanceof LabourDemand ? 'demands' : 'capacities', 'record_id' => $record->id, 'version' => (int) ($value['version'] ?? 0), 'operation_key' => $value['operation_key'] ?? null,
'snapshot' => $snapshot, 'unavailable' => $unavailable];
}
/** @param array<string,mixed> $input
* @return array<string,mixed> */
public function savePreparation(User $actor, string $kind, string $id, array $input): array
{
app(EducationAccess::class)->authorize($actor);
$model = match ($kind) {
'demands' => LabourDemand::class, 'capacities' => TrainingCapacity::class, default => abort(404)
};
$data = Validator::make($input, [...$this->preparationRules($input['snapshot'] ?? null),
'actor_id' => 'required|integer|min:1', 'version' => 'required|integer|min:0', 'operation_key' => 'required|uuid'])->validate();
abort_unless((int) $data['actor_id'] === $actor->id, 409, 'A conta mudou. Actualize a entrada antes de guardar a preparação.');
$key = strtolower($data['operation_key']);
$snapshot = $data['snapshot'];
foreach (['values', 'base'] as $field) {
$snapshot[$field]['version_no'] = (int) $snapshot[$field]['version_no'];
}
$snapshot['base']['quantity'] = (int) $snapshot['base']['quantity'];
foreach (['status', 'review_reason'] as $field) {
$snapshot['generation'][$field] = (int) $snapshot['generation'][$field];
}
if ($snapshot['pending'] !== null) {
$snapshot['pending']['values']['version_no'] = (int) $snapshot['pending']['values']['version_no'];
$snapshot['pending']['base']['version_no'] = (int) $snapshot['pending']['base']['version_no'];
$snapshot['pending']['base']['quantity'] = (int) $snapshot['pending']['base']['quantity'];
$snapshot['pending']['values']['client_key'] = strtolower($snapshot['pending']['values']['client_key']);
foreach (['reasonGeneration', 'statusGeneration'] as $field) {
$snapshot['pending'][$field] = (int) $snapshot['pending'][$field];
}
abort_unless($snapshot['pending']['values']['version_no'] === $snapshot['pending']['base']['version_no'], 422);
abort_unless($snapshot['pending']['reasonGeneration'] <= $snapshot['generation']['review_reason'] && $snapshot['pending']['statusGeneration'] <= $snapshot['generation']['status'], 422);
}
abort_unless($snapshot['values']['version_no'] === $snapshot['base']['version_no'], 422);
$hash = hash('sha256', json_encode(Arr::sortRecursive(['actor' => $actor->id, 'kind' => $kind, 'id' => $id,
'version' => (int) $data['version'], 'snapshot' => $snapshot]), JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $model, $id, $data, $snapshot, $key, $hash): array {
$record = $model::lockForUpdate()->findOrFail($id);
$previous = $this->preparations($actor, $record)->whereRaw("after_data->'education_preparation'->>'operation_key' = ?", [$key])->first(['after_data']);
if ($previous) {
$receipt = json_decode($previous->after_data, true, 512, JSON_THROW_ON_ERROR)['education_preparation'];
abort_unless(hash_equals($receipt['hash'], $hash), 409, 'Esta tentativa de guardar já foi usada com outros dados.');
return $this->preparation($actor, $record);
}
$current = $this->preparation($actor, $record);
abort_unless($current['version'] === (int) $data['version'], 409, 'A preparação mudou noutra janela. Compare antes de substituir.');
abort_if($current['unavailable'], 409, 'A preparação anterior não pôde ser recuperada e foi preservada.');
abort_if($snapshot['base']['version_no'] > (int) $record->getAttribute('version_no'), 422, 'A versão analisada não existe nesta declaração.');
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'actor_user_id' => $actor->id,
'entity_type' => $record->getTable(), 'entity_id' => $id, 'action' => 'review_preparation_saved', 'data_classification' => 'restricted',
'after_data' => json_encode(['education_preparation' => ['version' => $current['version'] + 1, 'operation_key' => $key, 'hash' => $hash,
'snapshot' => Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR))]], JSON_THROW_ON_ERROR)]);
return $this->preparation($actor, $record);
});
}
private function preparations(User $actor, LabourDemand|TrainingCapacity $record): Builder
{
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)
->where('entity_type', $record->getTable())->where('entity_id', $record->id)->where('action', 'review_preparation_saved');
}
/** @return array<string,string> */
private function preparationRules(mixed $snapshot): array
{
$rules = ['snapshot' => 'required|array:values,generation,base,pending', 'snapshot.values' => 'required|array:version_no,status,review_reason',
'snapshot.generation' => 'required|array:status,review_reason', 'snapshot.pending' => 'present|nullable|array:values,reasonGeneration,statusGeneration,base'];
$roots = ['snapshot'];
if (is_array($snapshot) && is_array($snapshot['pending'] ?? null)) {
$roots[] = 'snapshot.pending';
$rules['snapshot.pending.values'] = 'required|array:version_no,status,review_reason,client_key';
$rules['snapshot.pending.values.client_key'] = 'required|uuid';
foreach (['reasonGeneration', 'statusGeneration'] as $field) {
$rules['snapshot.pending.'.$field] = 'required|integer|min:0|max:1000000000';
}
}
foreach (['status', 'review_reason'] as $field) {
$rules['snapshot.generation.'.$field] = 'required|integer|min:0|max:1000000000';
}
foreach ($roots as $root) {
$rules[$root.'.values.version_no'] = 'required|integer|min:1';
$rules[$root.'.values.status'] = 'required|in:reviewed,rejected';
$rules[$root.'.values.review_reason'] = 'present|string|max:3000';
$rules[$root.'.base'] = 'required|array:version_no,qualification,quantity,status,period_start,period_end,valid_until,source,reference_date,employer,references';
$rules[$root.'.base.version_no'] = 'required|integer|min:1';
$rules[$root.'.base.quantity'] = 'required|integer|min:0';
foreach (['qualification' => 250, 'status' => 40, 'period_start' => 40, 'period_end' => 40, 'valid_until' => 40, 'source' => 5000, 'reference_date' => 40, 'employer' => 1000] as $field => $max) {
$rules[$root.'.base.'.$field] = 'present|string|max:'.$max;
}
$rules[$root.'.base.references'] = 'present|array:occupation,skill,project,course,location';
$rules[$root.'.base.references.*'] = 'nullable|string|max:1000';
}
return $rules;
}
/** @return array{actor_id:int,commands:list<array{key:string,version:int}>} */
public function context(User $actor, LabourDemand|TrainingCapacity $record): array
{
app(EducationAccess::class)->authorize($actor);
$commands = [];
foreach (DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)->where('entity_type', $record->getTable())->where('entity_id', $record->id)->where('action', 'review_committed')
->selectRaw("after_data->'education_review'->>'key' AS key,after_data->'education_review'->'version' AS version")->get() as $event) {
$version = is_string($event->version) ? json_decode($event->version, true, 512, JSON_THROW_ON_ERROR) : $event->version;
if (is_string($event->key) && is_int($version) && $version > 0) {
$commands[] = ['key' => $event->key, 'version' => $version];
}
}
return ['actor_id' => $actor->id, 'commands' => $commands];
}
/** Paginated private view data; no mutable paginator escapes the service.
* @return array<string,mixed> */
public function history(User $actor, LabourDemand|TrainingCapacity $record): array
{
app(EducationAccess::class)->authorize($actor);
return DB::table('audit_events as event')->leftJoin('users', 'users.id', '=', 'event.actor_user_id')->where('event.source_system', self::SOURCE)
->where('event.entity_type', $record->getTable())->where('event.entity_id', $record->id)->where('event.action', 'review_committed')
->selectRaw("event.id,event.occurred_at,users.name AS actor,event.after_data->'education_review'->'version' AS version,event.after_data->'education_review'->>'snapshot' AS snapshot")
->orderByRaw("CASE WHEN (event.after_data->'education_review'->>'version') ~ '^[0-9]{1,10}$' THEN (event.after_data->'education_review'->>'version')::bigint END DESC NULLS LAST")
->orderByDesc('event.occurred_at')->orderByDesc('event.id')->paginate(10, ['*'], 'history_page')->withQueryString()->through(function ($event) {
$version = is_string($event->version) ? json_decode($event->version, true) : $event->version;
$content = null;
try {
if (is_string($event->snapshot)) {
$content = json_decode(Crypt::decryptString($event->snapshot), true);
}
} catch (DecryptException) {/* Retain metadata and encrypted original; do not invent a past reason. */
}
$available = is_array($content) && isset($content['after']) && is_array($content['after']) && ($content['after']['version'] ?? null) === $version && is_string($content['after']['review_reason'] ?? null)
&& in_array($content['after']['status'] ?? null, ['reviewed', 'rejected'], true);
return ['id' => $event->id, 'version' => is_int($version) && $version > 0 ? $version : null, 'actor' => $event->actor, 'occurred_at' => $event->occurred_at, 'available' => $available,
'status' => $available ? $content['after']['status'] : null, 'reason' => $available ? $content['after']['review_reason'] : null,
'previous_reason' => $available && is_string($content['before']['review_reason'] ?? null) ? $content['before']['review_reason'] : null];
})->toArray();
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
final class EducationWorkQueue
{
/** @return array{actor_id:int,drafts:int|null,demands:array<string,int>,capacities:array<string,int>} */
public function summary(User $actor): array
{
app(EducationAccess::class)->authorize($actor);
return ['actor_id' => $actor->id, 'drafts' => app(EducationDeclarationDrafts::class)->installed() ? DB::table('education_declaration_drafts')->where('owner_user_id', $actor->id)->where('state', 'draft')->count() : null,
'demands' => $this->counts('labour_demands', $actor), 'capacities' => $this->counts('training_capacities', $actor)];
}
/** @return array<string,int> */
private function counts(string $table, User $actor): array
{
$today = now()->toDateString();
$id = $actor->id;
$row = DB::table($table)->whereNull('deleted_at')->selectRaw("count(*) FILTER(WHERE submitted_by=?) AS total,
count(*) FILTER(WHERE submitted_by=? AND valid_until>=? AND status='submitted') AS submitted,
count(*) FILTER(WHERE submitted_by=? AND valid_until>=? AND status='reviewed') AS reviewed,
count(*) FILTER(WHERE submitted_by=? AND valid_until>=? AND status='rejected') AS rejected,
count(*) FILTER(WHERE submitted_by=? AND valid_until<?) AS expired,
count(*) FILTER(WHERE submitted_by<>? AND valid_until>=? AND status='submitted') AS to_review", [$id, $id, $today, $id, $today, $id, $today, $id, $today, $id, $today])->first();
if ($row === null) {
throw new \LogicException('Education aggregate result missing.');
}
$result = [];
foreach (['total', 'submitted', 'reviewed', 'rejected', 'expired', 'to_review'] as $key) {
$result[$key] = (int) $row->$key;
}
return $result;
}
}

Some files were not shown because too many files have changed in this diff Show More