first commit
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-09-28 10:01:09 +02:00
commit 250ac35fd1
481 changed files with 92144 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
*.sqlite*
+295
View File
@@ -0,0 +1,295 @@
{
"source": "upgrade do portal de investimentos v4 programacao.docx",
"sections": ["4.3.4", "4.5.2", "6.1", "6.6"],
"notice": "Proposta documental; valores, mapas, prioridades e disponibilidade sujeitos a validacao institucional.",
"projects": [
{
"code": "A01",
"name": "MozParks – 20 Parques Industriais",
"region": "Nacional",
"location": "Âmbito nacional: parques industriais distribuídos pelas províncias de Moçambique; localização específica de cada parque sujeita a validação institucional.",
"sector": "Indústria e comércio",
"promotion": "Campanha nacional para investidores industriais, PME, operadores logísticos e empresas âncora.",
"description": "Plataforma nacional de industrialização descentralizada para instalar empresas, desenvolver fornecedores locais e integrar cadeias de valor em todas as províncias.",
"facts": "Âmbito nacional; indústria e comércio; investimento âncora indicado de USD 100 milhões; horizonte 2026–2030; potencial superior a 200 mil empregos directos e indirectos, sujeito a validação oficial.",
"partners": "Fabricantes, operadores de parques, empresas âncora, fundos industriais, logística, energia, água, tecnologia e PME fornecedoras.",
"cta": "Solicitar o dossier nacional, seleccionar uma província ou manifestar interesse em instalar, operar, financiar ou fornecer serviços."
},
{
"code": "A02",
"name": "Linha Ferroviária Norte–Sul",
"region": "Nacional",
"location": "Corredor ferroviário de âmbito nacional, ligando as regiões Norte, Centro e Sul; traçado e pontos exactos dependentes dos estudos técnicos.",
"sector": "Transportes e logística",
"promotion": "Promoção como projecto estruturante de integração territorial, logística e PPP.",
"description": "Ligação ferroviária contínua entre Norte, Centro e Sul para reduzir custos logísticos, integrar mercados e reforçar Moçambique como plataforma regional.",
"facts": "Extensão estimada de 3 808 km; custo ainda dependente de estudos; horizonte 2026–2030; projecto estruturante de transportes e logística.",
"partners": "Operadores ferroviários, fundos de infra-estrutura, construtoras, fornecedores de material circulante, portos, mineração, agricultura e PPP.",
"cta": "Registar interesse em estudos, estruturação, financiamento, construção, operação ou fornecimento tecnológico."
},
{
"code": "A03",
"name": "Programa de Desenvolvimento Integrado do Corredor de Nacala",
"region": "Norte",
"location": "Corredor de Nacala: Nampula, Cabo Delgado, Niassa, Tete e Norte da Zambézia, incluindo Nacala, Nampula, Cuamba, Palma e áreas ligadas ao corredor.",
"sector": "Logística, indústria, energia e agricultura",
"promotion": "Campanhas por corredor económico, exportação, parques industriais, energia, água e formação.",
"description": "Programa integrado que combina porto, ferrovia, indústria, agricultura, energia, água e serviços para transformar o Norte num corredor produtivo e exportador.",
"facts": "Nampula, Cabo Delgado, Niassa, Tete e Norte da Zambézia; custo global indicado de USD 2,43 mil milhões; cerca de 48 projectos complementares identificados.",
"partners": "Logística, portos, ferrovias, parques industriais, energia, água, agronegócio, formação, comércio regional e parceiros multilaterais.",
"cta": "Escolher um subprojecto, solicitar informação técnica ou propor financiamento, operação, construção ou parceria."
},
{
"code": "A04",
"name": "Crusse Jamali – Zona Económica Especial de Turismo",
"region": "Norte",
"location": "Crusse Jamali, zona de Nacala, província de Nampula.",
"sector": "Turismo e serviços",
"promotion": "Promoção orientada a turismo sustentável, resorts, marinas, hotelaria e operadores internacionais.",
"description": "Destino turístico integrado de alta gama na costa de Nampula, articulando resorts, marina, residência, conectividade e serviços sustentáveis.",
"facts": "Nacala, Nampula; projecto âncora privado indicado em USD 99,2 milhões; rede complementar de porto, aeroporto, estrada, energia, água, formação e telecomunicações.",
"partners": "Grupos hoteleiros, promotores imobiliários, operadores turísticos, aviação, marinas, fundos de turismo, utilities e tecnologia.",
"cta": "Solicitar o dossier turístico, agendar apresentação ou propor desenvolvimento, operação, financiamento ou serviço complementar."
},
{
"code": "A05",
"name": "Linha de Transmissão Namialo–Metoro (400 kV)",
"region": "Norte",
"location": "Eixo Namialo–Metoro, entre as províncias de Nampula e Cabo Delgado, com ligações a Pemba e Palma.",
"sector": "Energia e infra-estrutura",
"promotion": "Promoção junto de investidores em energia, EPC, manutenção, equipamentos e indústria eléctrica.",
"description": "Infra-estrutura energética para estabilizar o fornecimento ao Norte e suportar indústria, gás, mineração, cidades e novos investimentos.",
"facts": "Nampula–Cabo Delgado; custo âncora indicado de USD 550 milhões; inclui transmissão, subestações e interligações; horizonte 2026–2030.",
"partners": "Produtores e transmissores de energia, EPC, fabricantes de equipamento, fundos climáticos, manutenção, automação e formação técnica.",
"cta": "Manifestar interesse em financiamento, EPC, equipamentos, operação, manutenção ou componentes complementares."
},
{
"code": "A06",
"name": "Cadeia de Valor do Arroz por Projecto de Processamento",
"region": "Centro",
"location": "Províncias de Tete, Manica, Zambézia e Sofala, articuladas pelos corredores da Beira e de Nacala e pelas bacias de irrigação identificadas.",
"sector": "Agro-indústria e agricultura",
"promotion": "Captação de investidores em processamento, irrigação, logística agrícola e substituição de importações.",
"description": "Programa de produção irrigada, processamento e logística para reduzir importações, aumentar produtividade e criar emprego rural no Centro.",
"facts": "Tete, Manica, Zambézia e Sofala; projecto âncora privado indicado em USD 36,71 milhões; complementares de irrigação, ferrovia, estrada, porto, energia e água.",
"partners": "Produtores, processadores, armazenagem, irrigação, maquinaria, logística, retalho alimentar, bancos e fundos de impacto.",
"cta": "Solicitar oportunidades por elo da cadeia ou propor capital, tecnologia, compra de produção, processamento ou logística."
},
{
"code": "A07",
"name": "Parque Têxtil Integrado",
"region": "Centro",
"location": "Região Centro, com incidência principal em Sofala e articulação produtiva com Manica e Tete, junto ao Corredor da Beira.",
"sector": "Indústria transformadora",
"promotion": "Promoção para investidores têxteis, algodão, confecção, certificação, exportação e emprego industrial.",
"description": "Reindustrialização da fileira do algodão, da produção à fiação, tecelagem, confecção, certificação e exportação.",
"facts": "Zona Centro, com foco em Sofala, Manica e Tete; investimento âncora indicado em USD 42 milhões; integração com Porto e Corredor da Beira.",
"partners": "Fabricantes têxteis, marcas, fundos industriais, algodoeiras, equipamentos, logística, certificação, formação e compradores internacionais.",
"cta": "Manifestar interesse em instalar unidade, participar na cadeia, financiar, fornecer equipamento ou estabelecer contrato de compra."
},
{
"code": "A08",
"name": "Zona Económica Especial de Mocuba",
"region": "Centro",
"location": "Mocuba e Munhamade, província da Zambézia, com ligações a Quelimane, Nacala, Caia e Milange.",
"sector": "Indústria, energia, logística e agro-indústria",
"promotion": "Campanha para instalação industrial, agro-processamento, logística, energia e serviços de suporte.",
"description": "Ecossistema industrial e agro-logístico para transformar a Zambézia num pólo de processamento, inovação, energia e exportação.",
"facts": "Mocuba e Munhamade; projecto âncora indicado em USD 37,4 milhões; complementares de porto, ferrovia, estrada, energia, água, formação e plataforma digital.",
"partners": "Agro-indústria, silvicultura, pecuária, logística, parques industriais, utilities, tecnologia, certificação e fundos regionais.",
"cta": "Seleccionar lote, cadeia de valor ou activo complementar e solicitar reunião com a entidade promotora."
},
{
"code": "A09",
"name": "Construção da Cidadela Parlamentar de Mocuba",
"region": "Centro",
"location": "Cidade de Mocuba, província da Zambézia.",
"sector": "Infra-estruturas institucionais e urbanas",
"promotion": "Promoção voltada a construção, imobiliário, TIC, segurança, serviços urbanos e hotelaria de apoio.",
"description": "Complexo institucional e urbano destinado a reforçar a descentralização, serviços públicos, actividade económica e desenvolvimento urbano da Zambézia.",
"facts": "Mocuba; investimento âncora indicado em USD 120 milhões; componentes residenciais, administrativas, viárias, hoteleiras, segurança e TIC.",
"partners": "Construção, imobiliário, gestão de instalações, hotelaria, segurança, TIC, energia eficiente e serviços urbanos.",
"cta": "Registar capacidade e interesse em construção, fornecimento, tecnologia, operação de serviços ou parceria autorizada."
},
{
"code": "A10",
"name": "Mphanda Nkuwa HPP – Hidroeléctrica",
"region": "Centro",
"location": "Rio Zambeze, província de Tete, a jusante da Hidroeléctrica de Cahora Bassa; área exacta sujeita à documentação oficial do projecto.",
"sector": "Energia",
"promotion": "Promoção junto de financiadores, investidores energéticos, equipamentos, transmissão e compradores de energia.",
"description": "Central hidroeléctrica de grande escala para ampliar energia limpa, reforçar a industrialização e consolidar exportações eléctricas regionais.",
"facts": "Tete, rio Zambeze; 1 500 MW; custo âncora indicado de USD 4,5 mil milhões; associado a transmissão, expansão de rede e electrificação.",
"partners": "Investidores energéticos, financiadores, EPC, turbinas, transmissão, compradores de energia, fundos climáticos e seguradoras.",
"cta": "Solicitar informação pública validada ou manifestar interesse em financiamento, fornecimento, construção ou serviços especializados."
},
{
"code": "A11",
"name": "Corredor Ferroviário e Portuário de Macuse–Moatize",
"region": "Centro",
"location": "Corredor entre Moatize, na província de Tete, e Macuse, no distrito de Nicoadala, província da Zambézia, incluindo Mutarara, Mopeia e Quelimane.",
"sector": "Ferrovia, porto e logística",
"promotion": "Captação de parceiros para ferrovia, porto, terminais, mineração, carga geral e serviços logísticos.",
"description": "Corredor ferroviário e porto de águas profundas para ligar Tete à costa, diversificar rotas e aumentar a capacidade exportadora.",
"facts": "Tete–Zambézia; custo âncora indicado de USD 1,524 mil milhões; inclui porto, ferrovia, terminais, controlo, oficinas e mitigação social e ambiental.",
"partners": "Portos, ferrovias, mineração, carga geral, combustíveis, fundos de infra-estrutura, engenharia, tecnologia e operadores logísticos.",
"cta": "Manifestar interesse em estruturação, financiamento, construção, operação, carga contratual ou serviços complementares."
},
{
"code": "A12",
"name": "Programa de Conectividade e Resiliência Costeira (Compacto II)",
"region": "Centro",
"location": "Província da Zambézia, com incidência em zonas rurais, no rio Licungo, na Circular de Mocuba e em comunidades e ecossistemas costeiros.",
"sector": "Infra-estrutura, agricultura, ambiente e clima",
"promotion": "Promoção para parceiros de conectividade rural, agricultura, resiliência climática e economia azul.",
"description": "Programa integrado para melhorar conectividade rural, investimento agrícola e resiliência de comunidades e ecossistemas costeiros da Zambézia.",
"facts": "Zambézia; Compacto II com componentes de transportes rurais, reforma e investimento agrícola e meios de vida costeiros; valores sujeitos a harmonização oficial.",
"partners": "Fundos climáticos, cooperação, agricultura, estradas, economia azul, conservação, tecnologia de monitoria e fundos de impacto.",
"cta": "Solicitar oportunidades de parceria, assistência técnica, co-financiamento, fornecimento ou inovação climática."
},
{
"code": "A13",
"name": "Vilanculos – Região Integrada de Turismo",
"region": "Sul",
"location": "Corredor turístico Vilanculos–Inhassoro–Bazaruto, província de Inhambane, incluindo áreas costeiras e ilhas associadas.",
"sector": "Turismo e serviços",
"promotion": "Campanha para turismo costeiro, hotelaria, marina, aviação, formação e serviços digitais turísticos.",
"description": "Destino turístico costeiro integrado que combina hotelaria, acessibilidade, energia, água, formação, economia azul e serviços digitais.",
"facts": "Vilanculos–Inhassoro–Bazaruto; projecto âncora indicado em USD 20 milhões; 12 projectos complementares; horizonte 2026–2030.",
"partners": "Hotelaria, resorts, aviação, marinas, operadores turísticos, fundos imobiliários, utilities, formação e tecnologia.",
"cta": "Solicitar dossier, agendar apresentação ou propor investimento em alojamento, mobilidade, serviços, infra-estrutura ou formação."
},
{
"code": "A14",
"name": "Zona Económica Especial de Agronegócio do Limpopo",
"region": "Sul",
"location": "Vale do Limpopo, província de Gaza: Chókwè, Xai-Xai, Guijá, Chongoene, Chibuto, Limpopo e Bilene.",
"sector": "Agro-indústria, irrigação e logística",
"promotion": "Promoção para investidores em produção agrícola, processamento, armazenagem, crédito e equipamentos.",
"description": "Ecossistema agro-industrial integrado para ligar irrigação, produção, processamento, armazenamento, energia, crédito e mercados.",
"facts": "Gaza; Chókwè, Xai-Xai, Guijá, Chongoene, Chibuto, Limpopo e Bilene; custo âncora indicado de USD 354 milhões.",
"partners": "Produtores, processadores, irrigação, armazenagem, logística, energia, maquinaria, bancos, fundos agrícolas e compradores.",
"cta": "Seleccionar componente, cultura ou serviço e manifestar interesse em capital, operação, fornecimento, crédito ou compra."
},
{
"code": "A15",
"name": "Regadio na Bacia Hidrográfica do Rio Maputo",
"region": "Sul",
"location": "Bacia Hidrográfica do Rio Maputo, província de Maputo, com incidência nos distritos de Boane, Moamba e Namaacha e ligação às bacias do Maputo e Incomáti.",
"sector": "Agricultura irrigada, água e energia",
"promotion": "Captação de operadores agrícolas, tecnologia de irrigação, energia, infra-estrutura hídrica e gestão digital.",
"description": "Programa hídrico e agrícola para aumentar segurança de água, irrigação moderna, produtividade, processamento e resiliência climática.",
"facts": "Boane, Moamba e Namaacha; custo âncora indicado de USD 480 milhões; barragens, canais, drenagem, energia, estradas, formação e SCADA.",
"partners": "Operadores agrícolas, irrigação, engenharia hídrica, energia, tecnologia, fundos climáticos, logística, processamento e formação.",
"cta": "Propor financiamento, tecnologia, operação agrícola, fornecimento, assistência técnica ou parceria num componente validado."
}
],
"clusters": [
{
"code": "CLU-01",
"name": "Agro-indústria e segurança alimentar",
"anchors": "A06, A14 e A15; arroz, regadio, processamento, armazenamento, logística e comercialização.",
"gaps": "Irrigação, sementes, mecanização, frio, silos, embalagem, certificação, financiamento e compradores.",
"priority": "91 — MVP completo."
},
{
"code": "CLU-02",
"name": "Energia e industrialização",
"anchors": "A01, A05, A08 e A10; parques, transmissão, geração e grandes consumidores.",
"gaps": "Subestações, geração complementar, manutenção, equipamentos, utilities, competências e contratos de compra.",
"priority": "89 — MVP completo."
},
{
"code": "CLU-03",
"name": "Logística, corredores e exportação",
"anchors": "A02, A03 e A11; Nacala, Macuse–Moatize, Norte–Sul, portos, terminais e armazenagem.",
"gaps": "Última milha, intermodalidade, terminais, plataformas logísticas, digitalização, fronteiras e carga contratual.",
"priority": "88 — MVP completo."
},
{
"code": "CLU-04",
"name": "Turismo costeiro e economia azul",
"anchors": "A04 e A13; Crusse Jamali, Vilanculos, Bazaruto, hotelaria, marinas e aviação.",
"gaps": "Alojamento, formação, mobilidade, água, energia, serviços digitais, conservação e experiências locais.",
"priority": "77 — Fase 2."
},
{
"code": "CLU-05",
"name": "Têxtil, vestuário e algodão",
"anchors": "A07; algodão, fiação, tecelagem, confecção, marcas e exportação.",
"gaps": "Qualidade, equipamento, formação, certificação, logística, compradores, design e marcas.",
"priority": "74 — Fase 2."
},
{
"code": "CLU-06",
"name": "Mineração e transformação mineral",
"anchors": "Exploração, processamento, laboratórios, certificação, logística, equipamentos e reabilitação.",
"gaps": "Conhecimento geológico, processamento local, energia, financiamento, tecnologia, competências, origem responsável e mercado.",
"priority": "73 — MVP limitado; diligência avançada na Fase 2."
},
{
"code": "CLU-07",
"name": "Tecnologia e serviços digitais",
"anchors": "Fintech, govtech, centros de dados, incubação, formação e serviços empresariais.",
"gaps": "Capital de risco, competências, conectividade, investigação, clientes, propriedade intelectual e internacionalização.",
"priority": "72 — transversal no MVP; expansão na Fase 2."
},
{
"code": "CLU-08",
"name": "Financiamento do investimento",
"anchors": "Bancos, DFI, fundos climáticos, garantias, venture capital, crédito sectorial e assistência técnica.",
"gaps": "Colateral, preparação de projectos, planos de negócio, instrumentos por fase, garantias e blended finance.",
"priority": "Habilitador transversal do MVP."
}
],
"corridors": [
{
"code": "COR-01",
"name": "Corredor de Nacala e Norte",
"anchors": "A03 Corredor de Nacala; A04 Crusse Jamali; A05 Namialo–Metoro; componentes de A01.",
"clusters": "Logística, energia, agro-indústria, mineração, turismo e indústria.",
"focus": "Terminais, armazenagem, processamento, parques, água, energia, formação, fornecedores e conectividade.",
"priority": "MVP — muito alta."
},
{
"code": "COR-02",
"name": "Corredor da Beira e Centro",
"anchors": "A06 Cadeia do Arroz; A07 Parque Têxtil; componentes ferroviários, portuários e industriais.",
"clusters": "Agro-indústria, têxtil, logística, energia e serviços.",
"focus": "Regadio, silos, frio, processamento, fiação, logística, certificação, formação e financiamento.",
"priority": "MVP — muito alta."
},
{
"code": "COR-03",
"name": "Corredor Zambeze–Macuse",
"anchors": "A08 ZEE de Mocuba; A09 Cidadela de Mocuba; A10 Mphanda Nkuwa; A11 Macuse–Moatize; A12 Resiliência Costeira.",
"clusters": "Energia, logística, mineração, agro-indústria, serviços urbanos, clima e indústria.",
"focus": "Transmissão, porto, terminais, parques, água, serviços urbanos, mitigação social e ambiental e fornecedores.",
"priority": "MVP — muito alta."
},
{
"code": "COR-04",
"name": "Corredor Maputo–Limpopo",
"anchors": "A14 ZEE de Agronegócio do Limpopo; A15 Regadio da Bacia do Rio Maputo; componentes de A01.",
"clusters": "Agro-indústria, água, logística, indústria, comércio e serviços.",
"focus": "Irrigação, processamento, armazenagem, energia, embalagem, transporte, mercados e serviços financeiros.",
"priority": "MVP — alta."
},
{
"code": "COR-05",
"name": "Corredor Turístico Inhambane–Bazaruto",
"anchors": "A13 Região Integrada de Turismo de Vilanculos.",
"clusters": "Turismo, economia azul, aviação, serviços, conservação e tecnologia.",
"focus": "Alojamento, marinas, mobilidade, formação, água, energia, experiências e serviços digitais.",
"priority": "Fase 2 — alta."
},
{
"code": "COR-06",
"name": "Corredor Industrial Nacional Norte–Sul",
"anchors": "A01 MozParks; A02 Linha Ferroviária Norte–Sul.",
"clusters": "Indústria, logística, energia, tecnologia e cadeias provinciais.",
"focus": "Parques, ramais, utilities, centros logísticos, fornecedores, competências e digitalização.",
"priority": "Fase 2 — estruturante."
}
]
}
@@ -0,0 +1,16 @@
{
"need_category": {"labour_required":"Mão de obra necessária","labour_available":"Mão de obra disponível","infrastructure_existing":"Infraestruturas existentes","infrastructure_required":"Infraestruturas necessárias","education":"Educação e formação","support":"Apoios"},
"infrastructure": {"energy":"Energia","water":"Água","sanitation":"Saneamento","telecom":"Telecomunicações","internet":"Internet","road":"Estrada","rail":"Ferrovia","port":"Porto","airport":"Aeroporto","storage":"Armazenagem","cold_chain":"Cadeia de frio","housing":"Habitação","health":"Saúde","education":"Educação","security":"Segurança","industrial":"Instalações industriais","office":"Escritórios","land":"Terrenos","logistics":"Serviços logísticos"},
"education": {"preschool":"Educação pré-escolar","primary":"Ensino primário","secondary":"Ensino secundário","vocational":"Formação técnico-profissional","higher":"Ensino superior","research":"Investigação","innovation":"Centros de inovação","incubation":"Incubadoras","laboratory":"Laboratórios","edtech":"Tecnologia educativa","digital":"Plataformas digitais","connectivity":"Conectividade","buildings":"Infraestruturas escolares","equipment":"Equipamentos","library":"Bibliotecas","residence":"Alojamento","meals":"Alimentação escolar","transport":"Transporte","content":"Produção de conteúdos","teachers":"Formação de professores","skills":"Desenvolvimento de competências","continuing":"Formação contínua"},
"labour": {"technical":"Pessoal técnico","professional":"Profissionais especializados","operational":"Pessoal operacional","management":"Gestão","training":"Formadores"},
"qualification": {"primary":"Ensino primário","secondary":"Ensino secundário","technical":"Qualificação técnica","higher":"Ensino superior","postgraduate":"Pós-graduação"},
"support": {"licence":"Licenças","incentives":"Incentivos","finance":"Financiamento","land":"Terra","logistics":"Logística","partners":"Parceiros","suppliers":"Fornecedores","recruitment":"Contratação","imports":"Importação","exports":"Exportação","installation":"Instalação","utilities":"Ligação a serviços públicos"},
"priority": {"low":"Baixa","normal":"Normal","high":"Alta"},
"unit": {"people":"Pessoas","units":"Unidades","mw":"MW","m3_day":"m³/dia","km":"km","hectares":"Hectares"},
"participation": {"invest":"Investir","finance":"Financiar","supply":"Fornecer","operate":"Operar","partner":"Estabelecer parceria"},
"partnership": {"direct":"Investimento directo","joint_venture":"Joint venture","ppp":"Parceria público-privada","supply":"Fornecimento","technical":"Cooperação técnica"},
"investor_profile": {"individual":"Individual","company":"Empresa","fund":"Fundo","public":"Entidade pública"},
"impact": {"employment":"Emprego","training":"Competências","local_supply":"Fornecimento local","environment":"Ambiente","exports":"Exportações"},
"subsector": {},
"need_status": {"declared":"Declarada","available":"Disponível segundo declaração","required":"Necessária"}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace Database\Factories;
use App\Models\Investor;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/** @extends Factory<Investor> */
class InvestorFactory extends Factory
{
protected $model = Investor::class;
public function definition(): array
{
return [
'source_system' => 'example',
'external_id' => (string) Str::uuid(),
'data_classification' => 'internal',
'legal_name' => 'Investidor fictício de teste',
'investor_type' => 'institutional',
'status' => 'prospect',
];
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Database\Factories;
use App\Models\Project;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/** @extends Factory<Project> */
class ProjectFactory extends Factory
{
protected $model = Project::class;
public function definition(): array
{
return [
'source_system' => 'example',
'external_id' => (string) Str::uuid(),
'data_classification' => 'internal',
'code' => 'EXAMPLE-'.Str::uuid(),
'name' => 'Projecto fictício de teste',
'status' => 'draft',
'budget_amount' => '1000.00',
'budget_currency' => 'MZN',
];
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
/* @chisel-2fa */
'two_factor_secret' => null,
'two_factor_recovery_codes' => null,
'two_factor_confirmed_at' => null,
/* @end-chisel-2fa */
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
/**
* Indicate that the model has two-factor authentication configured.
*/
public function withTwoFactor(): static
{
/* @chisel-2fa */
return $this->state(fn (array $attributes) => [
'two_factor_secret' => encrypt('secret'),
'two_factor_recovery_codes' => encrypt(json_encode(['recovery-code-1'])),
'two_factor_confirmed_at' => now(),
]);
/* @end-chisel-2fa */
}
}
@@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->bigInteger('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->bigInteger('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};
@@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedSmallInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->string('connection');
$table->string('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
$table->index(['connection', 'queue', 'failed_at']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('passkeys', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->string('credential_id')->unique();
$table->json('credential');
$table->timestamp('last_used_at')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('passkeys');
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->text('two_factor_secret')->after('password')->nullable();
$table->text('two_factor_recovery_codes')->after('two_factor_secret')->nullable();
$table->timestamp('two_factor_confirmed_at')->after('two_factor_recovery_codes')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn([
'two_factor_secret',
'two_factor_recovery_codes',
'two_factor_confirmed_at',
]);
});
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('sectors', function (Blueprint $table) {
$table->id();
$table->string('name', 150);
$table->string('slug', 180)->unique();
$table->string('short_description', 255)->nullable();
$table->text('description')->nullable();
$table->string('icon', 100)->nullable();
$table->unsignedInteger('sort_order')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamp('published_at')->nullable();
$table->timestamps();
$table->softDeletes();
$table->index('slug');
$table->index('is_active');
});
}
public function down(): void
{
Schema::dropIfExists('sectors');
}
};
@@ -0,0 +1,62 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('opportunities', function (Blueprint $table) {
$table->id();
$table->foreignId('sector_id')
->constrained('sectors')
->cascadeOnUpdate()
->restrictOnDelete();
$table->string('reference', 80)->unique();
$table->string('title', 200);
$table->string('slug', 220)->unique();
$table->string('summary', 500)->nullable();
$table->longText('description')->nullable();
$table->string('province', 100)->nullable();
$table->string('district', 100)->nullable();
$table->string('promoter_name', 200)->nullable();
$table->string('promoter_type', 100)->nullable();
$table->unsignedTinyInteger('maturity_level')->nullable();
$table->string('maturity_label', 120)->nullable();
$table->decimal('estimated_investment_amount', 18, 2)->nullable();
$table->string('estimated_investment_currency', 10)->default('USD');
$table->string('financing_modality', 120)->nullable();
$table->text('expected_impact')->nullable();
$table->string('status', 50)->default('draft');
$table->boolean('is_featured')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamp('last_validated_at')->nullable();
$table->timestamps();
$table->softDeletes();
$table->index('sector_id');
$table->index('reference');
$table->index('slug');
$table->index('status');
$table->index('is_featured');
$table->index('province');
$table->index('maturity_level');
});
}
public function down(): void
{
Schema::dropIfExists('opportunities');
}
};
@@ -0,0 +1,61 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('interest_requests', function (Blueprint $table) {
$table->id();
$table->foreignId('opportunity_id')
->nullable()
->constrained('opportunities')
->cascadeOnUpdate()
->nullOnDelete();
$table->string('reference', 80)->unique();
$table->string('full_name', 150);
$table->string('email', 150);
$table->string('phone', 30)->nullable();
$table->string('investor_type', 80);
$table->string('country', 100);
$table->string('sector_interest', 150);
$table->string('opportunity_reference', 80)->nullable();
$table->string('investment_range', 80)->nullable();
$table->text('message');
$table->boolean('privacy_consent')->default(false);
$table->timestamp('consented_at')->nullable();
$table->string('status', 50)->default('received');
$table->string('source_page', 255)->nullable();
$table->ipAddress('ip_address')->nullable();
$table->text('user_agent')->nullable();
$table->json('metadata')->nullable();
$table->timestamp('reviewed_at')->nullable();
$table->foreignId('reviewed_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
$table->softDeletes();
$table->index('reference');
$table->index('email');
$table->index('status');
$table->index('created_at');
});
}
public function down(): void
{
Schema::dropIfExists('interest_requests');
}
};
@@ -0,0 +1,78 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE EXTENSION IF NOT EXISTS postgis;
SQL);
DB::statement(<<<'SQL'
CREATE EXTENSION IF NOT EXISTS pgcrypto;
SQL);
DB::statement(<<<'SQL'
CREATE OR REPLACE FUNCTION public.investmoz_set_updated_at() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$;
SQL);
DB::statement(<<<'SQL'
CREATE OR REPLACE FUNCTION public.investmoz_reject_audit_change() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
BEGIN
RAISE EXCEPTION 'InvestMoz audit_events is append-only' USING ERRCODE = '42501';
END;
$$;
SQL);
DB::statement(<<<'SQL'
CREATE OR REPLACE FUNCTION public.investmoz_protect_event_envelope() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
RAISE EXCEPTION 'InvestMoz event deletion requires a reviewed retention migration' USING ERRCODE = '42501';
END IF;
IF (to_jsonb(NEW) - ARRAY['status','updated_at','published_at','processed_at','available_at'])
IS DISTINCT FROM
(to_jsonb(OLD) - ARRAY['status','updated_at','published_at','processed_at','available_at']) THEN
RAISE EXCEPTION 'InvestMoz event envelope is immutable' USING ERRCODE = '42501';
END IF;
RETURN NEW;
END;
$$;
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
DROP FUNCTION IF EXISTS public.investmoz_protect_event_envelope() RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP FUNCTION IF EXISTS public.investmoz_reject_audit_change() RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP FUNCTION IF EXISTS public.investmoz_set_updated_at() RESTRICT;
SQL);
}
};
@@ -0,0 +1,159 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.organizations (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
name text NOT NULL,
organization_type text NOT NULL,
CONSTRAINT imz_organizations_pk PRIMARY KEY (id),
CONSTRAINT imz_organizations_check_01 CHECK (version_no > 0),
CONSTRAINT imz_organizations_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_organizations_check_03 CHECK (organization_type IN ('public','private','ngo','education'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.memberships (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
user_id bigint NOT NULL CONSTRAINT imz_memberships_user_id_fk REFERENCES public.users(id) ON DELETE CASCADE ON UPDATE CASCADE,
organization_id uuid NOT NULL CONSTRAINT imz_memberships_organization_id_fk REFERENCES public.organizations(id) ON DELETE CASCADE ON UPDATE CASCADE,
role text NOT NULL,
CONSTRAINT imz_memberships_pk PRIMARY KEY (id),
CONSTRAINT imz_memberships_check_01 CHECK (version_no > 0),
CONSTRAINT imz_memberships_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_memberships_check_03 CHECK (role IN ('admin','manager','officer','viewer'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.consents (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
user_id bigint CONSTRAINT imz_consents_user_id_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
subject_ref text NOT NULL,
purpose text NOT NULL,
status text NOT NULL,
granted_at timestamptz,
withdrawn_at timestamptz,
CONSTRAINT imz_consents_pk PRIMARY KEY (id),
CONSTRAINT imz_consents_check_01 CHECK (version_no > 0),
CONSTRAINT imz_consents_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_consents_check_03 CHECK (status IN ('granted','withdrawn','expired'))
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.consents DROP CONSTRAINT IF EXISTS imz_consents_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.consents DROP CONSTRAINT IF EXISTS imz_consents_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.consents DROP CONSTRAINT IF EXISTS imz_consents_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.consents DROP CONSTRAINT IF EXISTS imz_consents_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.consents DROP CONSTRAINT IF EXISTS imz_consents_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.consents RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.memberships DROP CONSTRAINT IF EXISTS imz_memberships_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.memberships DROP CONSTRAINT IF EXISTS imz_memberships_organization_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.memberships DROP CONSTRAINT IF EXISTS imz_memberships_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.memberships DROP CONSTRAINT IF EXISTS imz_memberships_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.memberships DROP CONSTRAINT IF EXISTS imz_memberships_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.memberships DROP CONSTRAINT IF EXISTS imz_memberships_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.memberships RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.organizations DROP CONSTRAINT IF EXISTS imz_organizations_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.organizations DROP CONSTRAINT IF EXISTS imz_organizations_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.organizations DROP CONSTRAINT IF EXISTS imz_organizations_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.organizations DROP CONSTRAINT IF EXISTS imz_organizations_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.organizations RESTRICT;
SQL);
}
};
@@ -0,0 +1,70 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.documents (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
file_name text NOT NULL,
media_type text NOT NULL,
storage_key text NOT NULL,
sha256 char(64) NOT NULL,
status text NOT NULL,
CONSTRAINT imz_documents_pk PRIMARY KEY (id),
CONSTRAINT imz_documents_check_01 CHECK (version_no > 0),
CONSTRAINT imz_documents_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_documents_check_03 CHECK (status IN ('active','quarantined','deleted')),
CONSTRAINT imz_documents_check_04 CHECK (sha256 ~ '^[0-9a-f]{64}$')
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.documents DROP CONSTRAINT IF EXISTS imz_documents_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.documents DROP CONSTRAINT IF EXISTS imz_documents_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.documents DROP CONSTRAINT IF EXISTS imz_documents_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.documents DROP CONSTRAINT IF EXISTS imz_documents_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.documents DROP CONSTRAINT IF EXISTS imz_documents_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.documents RESTRICT;
SQL);
}
};
@@ -0,0 +1,144 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.geo_locations (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
name text NOT NULL,
location_type text NOT NULL,
parent_id uuid CONSTRAINT imz_geo_locations_parent_id_fk REFERENCES public.geo_locations(id) ON DELETE RESTRICT ON UPDATE CASCADE,
code text NOT NULL,
CONSTRAINT imz_geo_locations_pk PRIMARY KEY (id),
CONSTRAINT imz_geo_locations_check_01 CHECK (version_no > 0),
CONSTRAINT imz_geo_locations_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_geo_locations_check_03 CHECK (location_type IN ('country','province','district','municipality','site'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.geo_geometries (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
geo_location_id uuid NOT NULL CONSTRAINT imz_geo_geometries_geo_location_id_fk REFERENCES public.geo_locations(id) ON DELETE CASCADE ON UPDATE CASCADE,
geometry_type text NOT NULL,
geom geometry(Geometry,4326) NOT NULL,
properties jsonb NOT NULL DEFAULT '{}'::jsonb,
CONSTRAINT imz_geo_geometries_pk PRIMARY KEY (id),
CONSTRAINT imz_geo_geometries_check_01 CHECK (version_no > 0),
CONSTRAINT imz_geo_geometries_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_geo_geometries_check_03 CHECK (geometry_type IN ('point','line','polygon','multipolygon')),
CONSTRAINT imz_geo_geometries_check_04 CHECK (ST_SRID(geom) = 4326),
CONSTRAINT imz_geo_geometries_check_05 CHECK (ST_NDims(geom) = 2),
CONSTRAINT imz_geo_geometries_check_06 CHECK (NOT ST_IsEmpty(geom)),
CONSTRAINT imz_geo_geometries_check_07 CHECK (ST_IsValid(geom)),
CONSTRAINT imz_geo_geometries_check_08 CHECK ((geometry_type = 'point' AND GeometryType(geom) = 'POINT') OR (geometry_type = 'line' AND GeometryType(geom) = 'LINESTRING') OR (geometry_type = 'polygon' AND GeometryType(geom) = 'POLYGON') OR (geometry_type = 'multipolygon' AND GeometryType(geom) = 'MULTIPOLYGON')),
CONSTRAINT imz_geo_geometries_check_09 CHECK (ST_XMin(Box3D(geom)) >= -180 AND ST_XMax(Box3D(geom)) <= 180 AND ST_YMin(Box3D(geom)) >= -90 AND ST_YMax(Box3D(geom)) <= 90)
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_geo_location_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_05 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_06 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_07 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_08 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_geometries DROP CONSTRAINT IF EXISTS imz_geo_geometries_check_09 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.geo_geometries RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_locations DROP CONSTRAINT IF EXISTS imz_geo_locations_parent_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_locations DROP CONSTRAINT IF EXISTS imz_geo_locations_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_locations DROP CONSTRAINT IF EXISTS imz_geo_locations_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_locations DROP CONSTRAINT IF EXISTS imz_geo_locations_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.geo_locations DROP CONSTRAINT IF EXISTS imz_geo_locations_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.geo_locations RESTRICT;
SQL);
}
};
@@ -0,0 +1,138 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.projects (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
code text NOT NULL,
name text NOT NULL,
status text NOT NULL,
description text,
budget_amount numeric(20,2),
budget_currency char(3),
start_date date,
end_date date,
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
CONSTRAINT imz_projects_pk PRIMARY KEY (id),
CONSTRAINT imz_projects_check_01 CHECK (version_no > 0),
CONSTRAINT imz_projects_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_projects_check_03 CHECK (status IN ('draft','planned','active','suspended','completed','cancelled')),
CONSTRAINT imz_projects_check_04 CHECK (budget_amount IS NULL OR budget_amount >= 0),
CONSTRAINT imz_projects_check_05 CHECK (end_date IS NULL OR start_date IS NULL OR end_date >= start_date),
CONSTRAINT imz_projects_check_06 CHECK ((budget_amount IS NULL) = (budget_currency IS NULL)),
CONSTRAINT imz_projects_check_07 CHECK (budget_currency IS NULL OR budget_currency ~ '^[A-Z]{3}$')
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.project_locations (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
project_id uuid NOT NULL CONSTRAINT imz_project_locations_project_id_fk REFERENCES public.projects(id) ON DELETE CASCADE ON UPDATE CASCADE,
geo_location_id uuid NOT NULL CONSTRAINT imz_project_locations_geo_location_id_fk REFERENCES public.geo_locations(id) ON DELETE RESTRICT ON UPDATE CASCADE,
role text NOT NULL,
CONSTRAINT imz_project_locations_pk PRIMARY KEY (id),
CONSTRAINT imz_project_locations_check_01 CHECK (version_no > 0),
CONSTRAINT imz_project_locations_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_project_locations_check_03 CHECK (role IN ('primary','secondary','impact'))
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_locations DROP CONSTRAINT IF EXISTS imz_project_locations_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_locations DROP CONSTRAINT IF EXISTS imz_project_locations_geo_location_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_locations DROP CONSTRAINT IF EXISTS imz_project_locations_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_locations DROP CONSTRAINT IF EXISTS imz_project_locations_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_locations DROP CONSTRAINT IF EXISTS imz_project_locations_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_locations DROP CONSTRAINT IF EXISTS imz_project_locations_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.project_locations RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_check_05 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_check_06 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.projects DROP CONSTRAINT IF EXISTS imz_projects_check_07 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.projects RESTRICT;
SQL);
}
};
@@ -0,0 +1,312 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.economic_clusters (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
code text NOT NULL,
name text NOT NULL,
sector text NOT NULL,
status text NOT NULL,
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
CONSTRAINT imz_economic_clusters_pk PRIMARY KEY (id),
CONSTRAINT imz_economic_clusters_check_01 CHECK (version_no > 0),
CONSTRAINT imz_economic_clusters_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_economic_clusters_check_03 CHECK (status IN ('planned','active','inactive'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.value_chains (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
cluster_id uuid NOT NULL CONSTRAINT imz_value_chains_cluster_id_fk REFERENCES public.economic_clusters(id) ON DELETE CASCADE ON UPDATE CASCADE,
code text NOT NULL,
name text NOT NULL,
stage text NOT NULL,
CONSTRAINT imz_value_chains_pk PRIMARY KEY (id),
CONSTRAINT imz_value_chains_check_01 CHECK (version_no > 0),
CONSTRAINT imz_value_chains_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_value_chains_check_03 CHECK (stage IN ('input','production','processing','logistics','market'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.value_chain_links (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
from_value_chain_id uuid NOT NULL CONSTRAINT imz_value_chain_links_from_value_chain_id_fk REFERENCES public.value_chains(id) ON DELETE CASCADE ON UPDATE CASCADE,
to_value_chain_id uuid NOT NULL CONSTRAINT imz_value_chain_links_to_value_chain_id_fk REFERENCES public.value_chains(id) ON DELETE CASCADE ON UPDATE CASCADE,
link_type text NOT NULL,
CONSTRAINT imz_value_chain_links_pk PRIMARY KEY (id),
CONSTRAINT imz_value_chain_links_check_01 CHECK (version_no > 0),
CONSTRAINT imz_value_chain_links_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_value_chain_links_check_03 CHECK (link_type IN ('supplies','processes','distributes','supports')),
CONSTRAINT imz_value_chain_links_check_04 CHECK (from_value_chain_id <> to_value_chain_id)
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.cluster_projects (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
cluster_id uuid NOT NULL CONSTRAINT imz_cluster_projects_cluster_id_fk REFERENCES public.economic_clusters(id) ON DELETE CASCADE ON UPDATE CASCADE,
project_id uuid NOT NULL CONSTRAINT imz_cluster_projects_project_id_fk REFERENCES public.projects(id) ON DELETE CASCADE ON UPDATE CASCADE,
role text NOT NULL,
CONSTRAINT imz_cluster_projects_pk PRIMARY KEY (id),
CONSTRAINT imz_cluster_projects_check_01 CHECK (version_no > 0),
CONSTRAINT imz_cluster_projects_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_cluster_projects_check_03 CHECK (role IN ('anchor','complementary','supporting'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.anchor_project_links (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
anchor_project_id uuid NOT NULL CONSTRAINT imz_anchor_project_links_anchor_project_id_fk REFERENCES public.projects(id) ON DELETE CASCADE ON UPDATE CASCADE,
cluster_id uuid NOT NULL CONSTRAINT imz_anchor_project_links_cluster_id_fk REFERENCES public.economic_clusters(id) ON DELETE CASCADE ON UPDATE CASCADE,
rationale text NOT NULL,
CONSTRAINT imz_anchor_project_links_pk PRIMARY KEY (id),
CONSTRAINT imz_anchor_project_links_check_01 CHECK (version_no > 0),
CONSTRAINT imz_anchor_project_links_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.complementary_project_links (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
anchor_project_id uuid NOT NULL CONSTRAINT imz_complementary_project_links_anchor_project_id_fk REFERENCES public.projects(id) ON DELETE CASCADE ON UPDATE CASCADE,
complementary_project_id uuid NOT NULL CONSTRAINT imz_complementary_project_links_complementary_project_id_fk REFERENCES public.projects(id) ON DELETE CASCADE ON UPDATE CASCADE,
relation_type text NOT NULL,
CONSTRAINT imz_complementary_project_links_pk PRIMARY KEY (id),
CONSTRAINT imz_complementary_project_links_check_01 CHECK (version_no > 0),
CONSTRAINT imz_complementary_project_links_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_complementary_project_links_check_03 CHECK (relation_type IN ('dependency','enabler','supplier','market')),
CONSTRAINT imz_complementary_project_links_check_04 CHECK (anchor_project_id<>complementary_project_id)
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.complementary_project_links DROP CONSTRAINT IF EXISTS imz_complementary_project_links_anchor_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.complementary_project_links DROP CONSTRAINT IF EXISTS imz_complementary_project_links_complementary_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.complementary_project_links DROP CONSTRAINT IF EXISTS imz_complementary_project_links_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.complementary_project_links DROP CONSTRAINT IF EXISTS imz_complementary_project_links_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.complementary_project_links DROP CONSTRAINT IF EXISTS imz_complementary_project_links_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.complementary_project_links DROP CONSTRAINT IF EXISTS imz_complementary_project_links_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.complementary_project_links DROP CONSTRAINT IF EXISTS imz_complementary_project_links_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.complementary_project_links RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.anchor_project_links DROP CONSTRAINT IF EXISTS imz_anchor_project_links_anchor_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.anchor_project_links DROP CONSTRAINT IF EXISTS imz_anchor_project_links_cluster_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.anchor_project_links DROP CONSTRAINT IF EXISTS imz_anchor_project_links_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.anchor_project_links DROP CONSTRAINT IF EXISTS imz_anchor_project_links_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.anchor_project_links DROP CONSTRAINT IF EXISTS imz_anchor_project_links_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.anchor_project_links RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.cluster_projects DROP CONSTRAINT IF EXISTS imz_cluster_projects_cluster_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.cluster_projects DROP CONSTRAINT IF EXISTS imz_cluster_projects_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.cluster_projects DROP CONSTRAINT IF EXISTS imz_cluster_projects_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.cluster_projects DROP CONSTRAINT IF EXISTS imz_cluster_projects_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.cluster_projects DROP CONSTRAINT IF EXISTS imz_cluster_projects_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.cluster_projects DROP CONSTRAINT IF EXISTS imz_cluster_projects_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.cluster_projects RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chain_links DROP CONSTRAINT IF EXISTS imz_value_chain_links_from_value_chain_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chain_links DROP CONSTRAINT IF EXISTS imz_value_chain_links_to_value_chain_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chain_links DROP CONSTRAINT IF EXISTS imz_value_chain_links_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chain_links DROP CONSTRAINT IF EXISTS imz_value_chain_links_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chain_links DROP CONSTRAINT IF EXISTS imz_value_chain_links_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chain_links DROP CONSTRAINT IF EXISTS imz_value_chain_links_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chain_links DROP CONSTRAINT IF EXISTS imz_value_chain_links_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.value_chain_links RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chains DROP CONSTRAINT IF EXISTS imz_value_chains_cluster_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chains DROP CONSTRAINT IF EXISTS imz_value_chains_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chains DROP CONSTRAINT IF EXISTS imz_value_chains_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chains DROP CONSTRAINT IF EXISTS imz_value_chains_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.value_chains DROP CONSTRAINT IF EXISTS imz_value_chains_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.value_chains RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.economic_clusters DROP CONSTRAINT IF EXISTS imz_economic_clusters_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.economic_clusters DROP CONSTRAINT IF EXISTS imz_economic_clusters_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.economic_clusters DROP CONSTRAINT IF EXISTS imz_economic_clusters_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.economic_clusters DROP CONSTRAINT IF EXISTS imz_economic_clusters_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.economic_clusters RESTRICT;
SQL);
}
};
@@ -0,0 +1,199 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.development_corridors (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
code text NOT NULL,
name text NOT NULL,
status text NOT NULL,
description text,
CONSTRAINT imz_development_corridors_pk PRIMARY KEY (id),
CONSTRAINT imz_development_corridors_check_01 CHECK (version_no > 0),
CONSTRAINT imz_development_corridors_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_development_corridors_check_03 CHECK (status IN ('proposed','active','closed'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.corridor_locations (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
corridor_id uuid NOT NULL CONSTRAINT imz_corridor_locations_corridor_id_fk REFERENCES public.development_corridors(id) ON DELETE CASCADE ON UPDATE CASCADE,
geo_location_id uuid NOT NULL CONSTRAINT imz_corridor_locations_geo_location_id_fk REFERENCES public.geo_locations(id) ON DELETE RESTRICT ON UPDATE CASCADE,
sequence_no integer NOT NULL,
CONSTRAINT imz_corridor_locations_pk PRIMARY KEY (id),
CONSTRAINT imz_corridor_locations_check_01 CHECK (version_no > 0),
CONSTRAINT imz_corridor_locations_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_corridor_locations_check_03 CHECK (sequence_no>0)
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.corridor_projects (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
corridor_id uuid NOT NULL CONSTRAINT imz_corridor_projects_corridor_id_fk REFERENCES public.development_corridors(id) ON DELETE CASCADE ON UPDATE CASCADE,
project_id uuid NOT NULL CONSTRAINT imz_corridor_projects_project_id_fk REFERENCES public.projects(id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT imz_corridor_projects_pk PRIMARY KEY (id),
CONSTRAINT imz_corridor_projects_check_01 CHECK (version_no > 0),
CONSTRAINT imz_corridor_projects_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.corridor_clusters (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
corridor_id uuid NOT NULL CONSTRAINT imz_corridor_clusters_corridor_id_fk REFERENCES public.development_corridors(id) ON DELETE CASCADE ON UPDATE CASCADE,
cluster_id uuid NOT NULL CONSTRAINT imz_corridor_clusters_cluster_id_fk REFERENCES public.economic_clusters(id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT imz_corridor_clusters_pk PRIMARY KEY (id),
CONSTRAINT imz_corridor_clusters_check_01 CHECK (version_no > 0),
CONSTRAINT imz_corridor_clusters_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted'))
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_clusters DROP CONSTRAINT IF EXISTS imz_corridor_clusters_corridor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_clusters DROP CONSTRAINT IF EXISTS imz_corridor_clusters_cluster_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_clusters DROP CONSTRAINT IF EXISTS imz_corridor_clusters_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_clusters DROP CONSTRAINT IF EXISTS imz_corridor_clusters_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_clusters DROP CONSTRAINT IF EXISTS imz_corridor_clusters_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.corridor_clusters RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_projects DROP CONSTRAINT IF EXISTS imz_corridor_projects_corridor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_projects DROP CONSTRAINT IF EXISTS imz_corridor_projects_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_projects DROP CONSTRAINT IF EXISTS imz_corridor_projects_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_projects DROP CONSTRAINT IF EXISTS imz_corridor_projects_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_projects DROP CONSTRAINT IF EXISTS imz_corridor_projects_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.corridor_projects RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_locations DROP CONSTRAINT IF EXISTS imz_corridor_locations_corridor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_locations DROP CONSTRAINT IF EXISTS imz_corridor_locations_geo_location_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_locations DROP CONSTRAINT IF EXISTS imz_corridor_locations_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_locations DROP CONSTRAINT IF EXISTS imz_corridor_locations_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_locations DROP CONSTRAINT IF EXISTS imz_corridor_locations_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.corridor_locations DROP CONSTRAINT IF EXISTS imz_corridor_locations_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.corridor_locations RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.development_corridors DROP CONSTRAINT IF EXISTS imz_development_corridors_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.development_corridors DROP CONSTRAINT IF EXISTS imz_development_corridors_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.development_corridors DROP CONSTRAINT IF EXISTS imz_development_corridors_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.development_corridors DROP CONSTRAINT IF EXISTS imz_development_corridors_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.development_corridors RESTRICT;
SQL);
}
};
@@ -0,0 +1,387 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.investors (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
organization_id uuid CONSTRAINT imz_investors_organization_id_fk REFERENCES public.organizations(id) ON DELETE SET NULL ON UPDATE CASCADE,
legal_name text NOT NULL,
investor_type text NOT NULL,
status text NOT NULL,
CONSTRAINT imz_investors_pk PRIMARY KEY (id),
CONSTRAINT imz_investors_check_01 CHECK (version_no > 0),
CONSTRAINT imz_investors_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_investors_check_03 CHECK (investor_type IN ('domestic','foreign','institutional','individual')),
CONSTRAINT imz_investors_check_04 CHECK (status IN ('prospect','active','inactive'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.contacts (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
full_name text NOT NULL,
email text,
phone text,
CONSTRAINT imz_contacts_pk PRIMARY KEY (id),
CONSTRAINT imz_contacts_check_01 CHECK (version_no > 0),
CONSTRAINT imz_contacts_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.investor_contacts (
investor_id uuid NOT NULL CONSTRAINT imz_investor_contacts_investor_id_fk REFERENCES public.investors(id) ON DELETE CASCADE ON UPDATE CASCADE,
contact_id uuid NOT NULL CONSTRAINT imz_investor_contacts_contact_id_fk REFERENCES public.contacts(id) ON DELETE CASCADE ON UPDATE CASCADE,
is_primary boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_investor_contacts_pk PRIMARY KEY (investor_id, contact_id)
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.leads (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
investor_id uuid CONSTRAINT imz_leads_investor_id_fk REFERENCES public.investors(id) ON DELETE SET NULL ON UPDATE CASCADE,
owner_user_id bigint CONSTRAINT imz_leads_owner_user_id_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
title text NOT NULL,
status text NOT NULL,
estimated_amount numeric(20,2),
currency char(3),
CONSTRAINT imz_leads_pk PRIMARY KEY (id),
CONSTRAINT imz_leads_check_01 CHECK (version_no > 0),
CONSTRAINT imz_leads_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_leads_check_03 CHECK (status IN ('new','qualified','disqualified','converted')),
CONSTRAINT imz_leads_check_04 CHECK ((estimated_amount IS NULL)=(currency IS NULL)),
CONSTRAINT imz_leads_check_05 CHECK (estimated_amount IS NULL OR estimated_amount >= 0),
CONSTRAINT imz_leads_check_06 CHECK (currency IS NULL OR currency ~ '^[A-Z]{3}$')
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.crm_opportunities (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
lead_id uuid CONSTRAINT imz_crm_opportunities_lead_id_fk REFERENCES public.leads(id) ON DELETE SET NULL ON UPDATE CASCADE,
project_id uuid CONSTRAINT imz_crm_opportunities_project_id_fk REFERENCES public.projects(id) ON DELETE SET NULL ON UPDATE CASCADE,
owner_user_id bigint CONSTRAINT imz_crm_opportunities_owner_user_id_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
stage text NOT NULL,
amount numeric(20,2),
currency char(3),
probability numeric(5,2),
CONSTRAINT imz_crm_opportunities_pk PRIMARY KEY (id),
CONSTRAINT imz_crm_opportunities_check_01 CHECK (version_no > 0),
CONSTRAINT imz_crm_opportunities_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_crm_opportunities_check_03 CHECK (stage IN ('discovery','assessment','negotiation','approved','lost')),
CONSTRAINT imz_crm_opportunities_check_04 CHECK (probability BETWEEN 0 AND 100),
CONSTRAINT imz_crm_opportunities_check_05 CHECK ((amount IS NULL)=(currency IS NULL)),
CONSTRAINT imz_crm_opportunities_check_06 CHECK (amount IS NULL OR amount >= 0),
CONSTRAINT imz_crm_opportunities_check_07 CHECK (currency IS NULL OR currency ~ '^[A-Z]{3}$')
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.activities (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
investor_id uuid CONSTRAINT imz_activities_investor_id_fk REFERENCES public.investors(id) ON DELETE CASCADE ON UPDATE CASCADE,
opportunity_id uuid CONSTRAINT imz_activities_opportunity_id_fk REFERENCES public.crm_opportunities(id) ON DELETE SET NULL ON UPDATE CASCADE,
actor_user_id bigint CONSTRAINT imz_activities_actor_user_id_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
activity_type text NOT NULL,
occurred_at timestamptz NOT NULL,
summary text NOT NULL,
CONSTRAINT imz_activities_pk PRIMARY KEY (id),
CONSTRAINT imz_activities_check_01 CHECK (version_no > 0),
CONSTRAINT imz_activities_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_activities_check_03 CHECK (activity_type IN ('call','meeting','email','note'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.tasks (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
assignee_user_id bigint CONSTRAINT imz_tasks_assignee_user_id_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
opportunity_id uuid CONSTRAINT imz_tasks_opportunity_id_fk REFERENCES public.crm_opportunities(id) ON DELETE CASCADE ON UPDATE CASCADE,
title text NOT NULL,
status text NOT NULL,
due_at timestamptz,
CONSTRAINT imz_tasks_pk PRIMARY KEY (id),
CONSTRAINT imz_tasks_check_01 CHECK (version_no > 0),
CONSTRAINT imz_tasks_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_tasks_check_03 CHECK (status IN ('open','in_progress','done','cancelled'))
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.tasks DROP CONSTRAINT IF EXISTS imz_tasks_assignee_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.tasks DROP CONSTRAINT IF EXISTS imz_tasks_opportunity_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.tasks DROP CONSTRAINT IF EXISTS imz_tasks_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.tasks DROP CONSTRAINT IF EXISTS imz_tasks_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.tasks DROP CONSTRAINT IF EXISTS imz_tasks_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.tasks DROP CONSTRAINT IF EXISTS imz_tasks_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.tasks RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.activities DROP CONSTRAINT IF EXISTS imz_activities_investor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.activities DROP CONSTRAINT IF EXISTS imz_activities_opportunity_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.activities DROP CONSTRAINT IF EXISTS imz_activities_actor_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.activities DROP CONSTRAINT IF EXISTS imz_activities_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.activities DROP CONSTRAINT IF EXISTS imz_activities_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.activities DROP CONSTRAINT IF EXISTS imz_activities_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.activities DROP CONSTRAINT IF EXISTS imz_activities_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.activities RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_lead_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_owner_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_check_05 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_check_06 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.crm_opportunities DROP CONSTRAINT IF EXISTS imz_crm_opportunities_check_07 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.crm_opportunities RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_investor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_owner_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_check_05 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.leads DROP CONSTRAINT IF EXISTS imz_leads_check_06 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.leads RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_contacts DROP CONSTRAINT IF EXISTS imz_investor_contacts_investor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_contacts DROP CONSTRAINT IF EXISTS imz_investor_contacts_contact_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_contacts DROP CONSTRAINT IF EXISTS imz_investor_contacts_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.investor_contacts RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.contacts DROP CONSTRAINT IF EXISTS imz_contacts_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.contacts DROP CONSTRAINT IF EXISTS imz_contacts_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.contacts DROP CONSTRAINT IF EXISTS imz_contacts_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.contacts RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investors DROP CONSTRAINT IF EXISTS imz_investors_organization_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investors DROP CONSTRAINT IF EXISTS imz_investors_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investors DROP CONSTRAINT IF EXISTS imz_investors_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investors DROP CONSTRAINT IF EXISTS imz_investors_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investors DROP CONSTRAINT IF EXISTS imz_investors_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investors DROP CONSTRAINT IF EXISTS imz_investors_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.investors RESTRICT;
SQL);
}
};
@@ -0,0 +1,337 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.investor_journeys (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
investor_id uuid NOT NULL CONSTRAINT imz_investor_journeys_investor_id_fk REFERENCES public.investors(id) ON DELETE CASCADE ON UPDATE CASCADE,
opportunity_id uuid CONSTRAINT imz_investor_journeys_opportunity_id_fk REFERENCES public.crm_opportunities(id) ON DELETE SET NULL ON UPDATE CASCADE,
status text NOT NULL,
started_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_investor_journeys_pk PRIMARY KEY (id),
CONSTRAINT imz_investor_journeys_check_01 CHECK (version_no > 0),
CONSTRAINT imz_investor_journeys_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_investor_journeys_check_03 CHECK (status IN ('started','active','completed','cancelled'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.journey_steps (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
journey_id uuid NOT NULL CONSTRAINT imz_journey_steps_journey_id_fk REFERENCES public.investor_journeys(id) ON DELETE CASCADE ON UPDATE CASCADE,
step_code text NOT NULL,
sequence_no integer NOT NULL,
status text NOT NULL,
CONSTRAINT imz_journey_steps_pk PRIMARY KEY (id),
CONSTRAINT imz_journey_steps_check_01 CHECK (version_no > 0),
CONSTRAINT imz_journey_steps_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_journey_steps_check_03 CHECK (sequence_no>0),
CONSTRAINT imz_journey_steps_check_04 CHECK (status IN ('pending','active','completed','blocked'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.submissions (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
journey_step_id uuid NOT NULL CONSTRAINT imz_submissions_journey_step_id_fk REFERENCES public.journey_steps(id) ON DELETE CASCADE ON UPDATE CASCADE,
submitted_by bigint CONSTRAINT imz_submissions_submitted_by_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
status text NOT NULL,
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
submitted_at timestamptz,
CONSTRAINT imz_submissions_pk PRIMARY KEY (id),
CONSTRAINT imz_submissions_check_01 CHECK (version_no > 0),
CONSTRAINT imz_submissions_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_submissions_check_03 CHECK (status IN ('draft','submitted','accepted','rejected'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.aftercare_plans (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
investor_id uuid NOT NULL CONSTRAINT imz_aftercare_plans_investor_id_fk REFERENCES public.investors(id) ON DELETE CASCADE ON UPDATE CASCADE,
project_id uuid CONSTRAINT imz_aftercare_plans_project_id_fk REFERENCES public.projects(id) ON DELETE SET NULL ON UPDATE CASCADE,
owner_user_id bigint CONSTRAINT imz_aftercare_plans_owner_user_id_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
status text NOT NULL,
review_date date,
CONSTRAINT imz_aftercare_plans_pk PRIMARY KEY (id),
CONSTRAINT imz_aftercare_plans_check_01 CHECK (version_no > 0),
CONSTRAINT imz_aftercare_plans_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_aftercare_plans_check_03 CHECK (status IN ('draft','active','closed'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.constraints (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
aftercare_plan_id uuid NOT NULL CONSTRAINT imz_constraints_aftercare_plan_id_fk REFERENCES public.aftercare_plans(id) ON DELETE CASCADE ON UPDATE CASCADE,
category text NOT NULL,
description text NOT NULL,
severity text NOT NULL,
status text NOT NULL,
CONSTRAINT imz_constraints_pk PRIMARY KEY (id),
CONSTRAINT imz_constraints_check_01 CHECK (version_no > 0),
CONSTRAINT imz_constraints_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_constraints_check_03 CHECK (severity IN ('low','medium','high','critical')),
CONSTRAINT imz_constraints_check_04 CHECK (status IN ('open','mitigating','resolved'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.escalations (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
constraint_id uuid NOT NULL CONSTRAINT imz_escalations_constraint_id_fk REFERENCES public.constraints(id) ON DELETE CASCADE ON UPDATE CASCADE,
escalated_by bigint CONSTRAINT imz_escalations_escalated_by_fk REFERENCES public.users(id) ON DELETE SET NULL ON UPDATE CASCADE,
level text NOT NULL,
status text NOT NULL,
escalated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_escalations_pk PRIMARY KEY (id),
CONSTRAINT imz_escalations_check_01 CHECK (version_no > 0),
CONSTRAINT imz_escalations_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_escalations_check_03 CHECK (level IN ('operational','management','executive')),
CONSTRAINT imz_escalations_check_04 CHECK (status IN ('open','acknowledged','closed'))
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.escalations DROP CONSTRAINT IF EXISTS imz_escalations_constraint_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.escalations DROP CONSTRAINT IF EXISTS imz_escalations_escalated_by_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.escalations DROP CONSTRAINT IF EXISTS imz_escalations_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.escalations DROP CONSTRAINT IF EXISTS imz_escalations_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.escalations DROP CONSTRAINT IF EXISTS imz_escalations_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.escalations DROP CONSTRAINT IF EXISTS imz_escalations_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.escalations DROP CONSTRAINT IF EXISTS imz_escalations_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.escalations RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.constraints DROP CONSTRAINT IF EXISTS imz_constraints_aftercare_plan_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.constraints DROP CONSTRAINT IF EXISTS imz_constraints_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.constraints DROP CONSTRAINT IF EXISTS imz_constraints_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.constraints DROP CONSTRAINT IF EXISTS imz_constraints_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.constraints DROP CONSTRAINT IF EXISTS imz_constraints_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.constraints DROP CONSTRAINT IF EXISTS imz_constraints_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.constraints RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_plans DROP CONSTRAINT IF EXISTS imz_aftercare_plans_investor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_plans DROP CONSTRAINT IF EXISTS imz_aftercare_plans_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_plans DROP CONSTRAINT IF EXISTS imz_aftercare_plans_owner_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_plans DROP CONSTRAINT IF EXISTS imz_aftercare_plans_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_plans DROP CONSTRAINT IF EXISTS imz_aftercare_plans_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_plans DROP CONSTRAINT IF EXISTS imz_aftercare_plans_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_plans DROP CONSTRAINT IF EXISTS imz_aftercare_plans_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.aftercare_plans RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.submissions DROP CONSTRAINT IF EXISTS imz_submissions_journey_step_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.submissions DROP CONSTRAINT IF EXISTS imz_submissions_submitted_by_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.submissions DROP CONSTRAINT IF EXISTS imz_submissions_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.submissions DROP CONSTRAINT IF EXISTS imz_submissions_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.submissions DROP CONSTRAINT IF EXISTS imz_submissions_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.submissions DROP CONSTRAINT IF EXISTS imz_submissions_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.submissions RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_steps DROP CONSTRAINT IF EXISTS imz_journey_steps_journey_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_steps DROP CONSTRAINT IF EXISTS imz_journey_steps_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_steps DROP CONSTRAINT IF EXISTS imz_journey_steps_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_steps DROP CONSTRAINT IF EXISTS imz_journey_steps_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_steps DROP CONSTRAINT IF EXISTS imz_journey_steps_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_steps DROP CONSTRAINT IF EXISTS imz_journey_steps_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.journey_steps RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_journeys DROP CONSTRAINT IF EXISTS imz_investor_journeys_investor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_journeys DROP CONSTRAINT IF EXISTS imz_investor_journeys_opportunity_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_journeys DROP CONSTRAINT IF EXISTS imz_investor_journeys_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_journeys DROP CONSTRAINT IF EXISTS imz_investor_journeys_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_journeys DROP CONSTRAINT IF EXISTS imz_investor_journeys_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_journeys DROP CONSTRAINT IF EXISTS imz_investor_journeys_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.investor_journeys RESTRICT;
SQL);
}
};
@@ -0,0 +1,305 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.skills (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
code text NOT NULL,
name text NOT NULL,
CONSTRAINT imz_skills_pk PRIMARY KEY (id),
CONSTRAINT imz_skills_check_01 CHECK (version_no > 0),
CONSTRAINT imz_skills_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.occupations (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
code text NOT NULL,
name text NOT NULL,
CONSTRAINT imz_occupations_pk PRIMARY KEY (id),
CONSTRAINT imz_occupations_check_01 CHECK (version_no > 0),
CONSTRAINT imz_occupations_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.training_needs (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
project_id uuid CONSTRAINT imz_training_needs_project_id_fk REFERENCES public.projects(id) ON DELETE SET NULL ON UPDATE CASCADE,
occupation_id uuid CONSTRAINT imz_training_needs_occupation_id_fk REFERENCES public.occupations(id) ON DELETE RESTRICT ON UPDATE CASCADE,
skill_id uuid CONSTRAINT imz_training_needs_skill_id_fk REFERENCES public.skills(id) ON DELETE RESTRICT ON UPDATE CASCADE,
quantity integer NOT NULL,
priority text NOT NULL,
CONSTRAINT imz_training_needs_pk PRIMARY KEY (id),
CONSTRAINT imz_training_needs_check_01 CHECK (version_no > 0),
CONSTRAINT imz_training_needs_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_training_needs_check_03 CHECK (quantity>0),
CONSTRAINT imz_training_needs_check_04 CHECK (priority IN ('Must','Should','Could'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.training_providers (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
organization_id uuid CONSTRAINT imz_training_providers_organization_id_fk REFERENCES public.organizations(id) ON DELETE SET NULL ON UPDATE CASCADE,
name text NOT NULL,
status text NOT NULL,
CONSTRAINT imz_training_providers_pk PRIMARY KEY (id),
CONSTRAINT imz_training_providers_check_01 CHECK (version_no > 0),
CONSTRAINT imz_training_providers_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_training_providers_check_03 CHECK (status IN ('candidate','approved','inactive'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.courses (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
provider_id uuid NOT NULL CONSTRAINT imz_courses_provider_id_fk REFERENCES public.training_providers(id) ON DELETE CASCADE ON UPDATE CASCADE,
code text NOT NULL,
title text NOT NULL,
status text NOT NULL,
CONSTRAINT imz_courses_pk PRIMARY KEY (id),
CONSTRAINT imz_courses_check_01 CHECK (version_no > 0),
CONSTRAINT imz_courses_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_courses_check_03 CHECK (status IN ('draft','published','retired'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.education_opportunities (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
course_id uuid NOT NULL CONSTRAINT imz_education_opportunities_course_id_fk REFERENCES public.courses(id) ON DELETE CASCADE ON UPDATE CASCADE,
geo_location_id uuid CONSTRAINT imz_education_opportunities_geo_location_id_fk REFERENCES public.geo_locations(id) ON DELETE SET NULL ON UPDATE CASCADE,
start_date date NOT NULL,
end_date date,
capacity integer,
status text NOT NULL,
CONSTRAINT imz_education_opportunities_pk PRIMARY KEY (id),
CONSTRAINT imz_education_opportunities_check_01 CHECK (version_no > 0),
CONSTRAINT imz_education_opportunities_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_education_opportunities_check_03 CHECK (capacity>=0),
CONSTRAINT imz_education_opportunities_check_04 CHECK (status IN ('planned','open','closed','cancelled')),
CONSTRAINT imz_education_opportunities_check_05 CHECK (end_date IS NULL OR end_date>=start_date)
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_course_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_geo_location_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_opportunities DROP CONSTRAINT IF EXISTS imz_education_opportunities_check_05 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.education_opportunities RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.courses DROP CONSTRAINT IF EXISTS imz_courses_provider_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.courses DROP CONSTRAINT IF EXISTS imz_courses_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.courses DROP CONSTRAINT IF EXISTS imz_courses_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.courses DROP CONSTRAINT IF EXISTS imz_courses_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.courses DROP CONSTRAINT IF EXISTS imz_courses_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.courses RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_providers DROP CONSTRAINT IF EXISTS imz_training_providers_organization_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_providers DROP CONSTRAINT IF EXISTS imz_training_providers_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_providers DROP CONSTRAINT IF EXISTS imz_training_providers_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_providers DROP CONSTRAINT IF EXISTS imz_training_providers_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_providers DROP CONSTRAINT IF EXISTS imz_training_providers_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.training_providers RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_occupation_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_skill_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.training_needs DROP CONSTRAINT IF EXISTS imz_training_needs_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.training_needs RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.occupations DROP CONSTRAINT IF EXISTS imz_occupations_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.occupations DROP CONSTRAINT IF EXISTS imz_occupations_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.occupations DROP CONSTRAINT IF EXISTS imz_occupations_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.occupations RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.skills DROP CONSTRAINT IF EXISTS imz_skills_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.skills DROP CONSTRAINT IF EXISTS imz_skills_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.skills DROP CONSTRAINT IF EXISTS imz_skills_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.skills RESTRICT;
SQL);
}
};
@@ -0,0 +1,147 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.project_documents (
project_id uuid NOT NULL CONSTRAINT imz_project_documents_project_id_fk REFERENCES public.projects(id) ON DELETE CASCADE ON UPDATE CASCADE,
document_id uuid NOT NULL CONSTRAINT imz_project_documents_document_id_fk REFERENCES public.documents(id) ON DELETE RESTRICT ON UPDATE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_project_documents_pk PRIMARY KEY (project_id, document_id)
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.investor_documents (
investor_id uuid NOT NULL CONSTRAINT imz_investor_documents_investor_id_fk REFERENCES public.investors(id) ON DELETE CASCADE ON UPDATE CASCADE,
document_id uuid NOT NULL CONSTRAINT imz_investor_documents_document_id_fk REFERENCES public.documents(id) ON DELETE RESTRICT ON UPDATE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_investor_documents_pk PRIMARY KEY (investor_id, document_id)
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.journey_documents (
journey_id uuid NOT NULL CONSTRAINT imz_journey_documents_journey_id_fk REFERENCES public.investor_journeys(id) ON DELETE CASCADE ON UPDATE CASCADE,
document_id uuid NOT NULL CONSTRAINT imz_journey_documents_document_id_fk REFERENCES public.documents(id) ON DELETE RESTRICT ON UPDATE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_journey_documents_pk PRIMARY KEY (journey_id, document_id)
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.aftercare_documents (
aftercare_plan_id uuid NOT NULL CONSTRAINT imz_aftercare_documents_aftercare_plan_id_fk REFERENCES public.aftercare_plans(id) ON DELETE CASCADE ON UPDATE CASCADE,
document_id uuid NOT NULL CONSTRAINT imz_aftercare_documents_document_id_fk REFERENCES public.documents(id) ON DELETE RESTRICT ON UPDATE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_aftercare_documents_pk PRIMARY KEY (aftercare_plan_id, document_id)
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.education_documents (
education_opportunity_id uuid NOT NULL CONSTRAINT imz_education_documents_education_opportunity_id_fk REFERENCES public.education_opportunities(id) ON DELETE CASCADE ON UPDATE CASCADE,
document_id uuid NOT NULL CONSTRAINT imz_education_documents_document_id_fk REFERENCES public.documents(id) ON DELETE RESTRICT ON UPDATE CASCADE,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT imz_education_documents_pk PRIMARY KEY (education_opportunity_id, document_id)
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_documents DROP CONSTRAINT IF EXISTS imz_education_documents_education_opportunity_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_documents DROP CONSTRAINT IF EXISTS imz_education_documents_document_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.education_documents DROP CONSTRAINT IF EXISTS imz_education_documents_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.education_documents RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_documents DROP CONSTRAINT IF EXISTS imz_aftercare_documents_aftercare_plan_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_documents DROP CONSTRAINT IF EXISTS imz_aftercare_documents_document_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.aftercare_documents DROP CONSTRAINT IF EXISTS imz_aftercare_documents_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.aftercare_documents RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_documents DROP CONSTRAINT IF EXISTS imz_journey_documents_journey_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_documents DROP CONSTRAINT IF EXISTS imz_journey_documents_document_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.journey_documents DROP CONSTRAINT IF EXISTS imz_journey_documents_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.journey_documents RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_documents DROP CONSTRAINT IF EXISTS imz_investor_documents_investor_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_documents DROP CONSTRAINT IF EXISTS imz_investor_documents_document_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.investor_documents DROP CONSTRAINT IF EXISTS imz_investor_documents_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.investor_documents RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_documents DROP CONSTRAINT IF EXISTS imz_project_documents_project_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_documents DROP CONSTRAINT IF EXISTS imz_project_documents_document_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.project_documents DROP CONSTRAINT IF EXISTS imz_project_documents_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.project_documents RESTRICT;
SQL);
}
};
@@ -0,0 +1,58 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.audit_events (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
actor_user_id bigint CONSTRAINT imz_audit_events_actor_user_id_fk REFERENCES public.users(id) ON DELETE RESTRICT ON UPDATE RESTRICT,
entity_type text NOT NULL,
entity_id uuid,
action text NOT NULL,
occurred_at timestamptz NOT NULL DEFAULT now(),
before_data jsonb,
after_data jsonb,
CONSTRAINT imz_audit_events_pk PRIMARY KEY (id),
CONSTRAINT imz_audit_events_check_01 CHECK (data_classification IN ('public','internal','confidential','restricted'))
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.audit_events DROP CONSTRAINT IF EXISTS imz_audit_events_actor_user_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.audit_events DROP CONSTRAINT IF EXISTS imz_audit_events_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.audit_events DROP CONSTRAINT IF EXISTS imz_audit_events_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.audit_events RESTRICT;
SQL);
}
};
@@ -0,0 +1,217 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TABLE public.outbox_events (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
aggregate_type text NOT NULL,
aggregate_id uuid NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL,
available_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz,
CONSTRAINT imz_outbox_events_pk PRIMARY KEY (id),
CONSTRAINT imz_outbox_events_check_01 CHECK (version_no > 0),
CONSTRAINT imz_outbox_events_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_outbox_events_check_03 CHECK (status IN ('pending','published','failed'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.inbox_events (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
message_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz,
CONSTRAINT imz_inbox_events_pk PRIMARY KEY (id),
CONSTRAINT imz_inbox_events_check_01 CHECK (version_no > 0),
CONSTRAINT imz_inbox_events_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_inbox_events_check_03 CHECK (status IN ('received','processed','failed'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.sync_runs (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
integration_name text NOT NULL,
direction text NOT NULL,
status text NOT NULL,
started_at timestamptz NOT NULL DEFAULT now(),
ended_at timestamptz,
totals jsonb NOT NULL DEFAULT '{}'::jsonb,
CONSTRAINT imz_sync_runs_pk PRIMARY KEY (id),
CONSTRAINT imz_sync_runs_check_01 CHECK (version_no > 0),
CONSTRAINT imz_sync_runs_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_sync_runs_check_03 CHECK (direction IN ('inbound','outbound')),
CONSTRAINT imz_sync_runs_check_04 CHECK (status IN ('running','succeeded','failed','cancelled'))
);
SQL);
DB::statement(<<<'SQL'
CREATE TABLE public.reconciliation_issues (
id uuid DEFAULT gen_random_uuid() NOT NULL,
source_system text NOT NULL DEFAULT 'investmoz',
external_id text,
version_no integer NOT NULL DEFAULT 1,
data_classification text NOT NULL DEFAULT 'internal',
correlation_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
sync_run_id uuid NOT NULL CONSTRAINT imz_reconciliation_issues_sync_run_id_fk REFERENCES public.sync_runs(id) ON DELETE CASCADE ON UPDATE CASCADE,
entity_type text NOT NULL,
external_id_ref text,
issue_type text NOT NULL,
severity text NOT NULL,
status text NOT NULL,
details jsonb NOT NULL DEFAULT '{}'::jsonb,
CONSTRAINT imz_reconciliation_issues_pk PRIMARY KEY (id),
CONSTRAINT imz_reconciliation_issues_check_01 CHECK (version_no > 0),
CONSTRAINT imz_reconciliation_issues_check_02 CHECK (data_classification IN ('public','internal','confidential','restricted')),
CONSTRAINT imz_reconciliation_issues_check_03 CHECK (issue_type IN ('missing','duplicate','orphan','checksum','geometry','value')),
CONSTRAINT imz_reconciliation_issues_check_04 CHECK (severity IN ('warning','error')),
CONSTRAINT imz_reconciliation_issues_check_05 CHECK (status IN ('open','accepted','resolved'))
);
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.reconciliation_issues DROP CONSTRAINT IF EXISTS imz_reconciliation_issues_sync_run_id_fk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.reconciliation_issues DROP CONSTRAINT IF EXISTS imz_reconciliation_issues_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.reconciliation_issues DROP CONSTRAINT IF EXISTS imz_reconciliation_issues_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.reconciliation_issues DROP CONSTRAINT IF EXISTS imz_reconciliation_issues_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.reconciliation_issues DROP CONSTRAINT IF EXISTS imz_reconciliation_issues_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.reconciliation_issues DROP CONSTRAINT IF EXISTS imz_reconciliation_issues_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.reconciliation_issues DROP CONSTRAINT IF EXISTS imz_reconciliation_issues_check_05 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.reconciliation_issues RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.sync_runs DROP CONSTRAINT IF EXISTS imz_sync_runs_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.sync_runs DROP CONSTRAINT IF EXISTS imz_sync_runs_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.sync_runs DROP CONSTRAINT IF EXISTS imz_sync_runs_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.sync_runs DROP CONSTRAINT IF EXISTS imz_sync_runs_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.sync_runs DROP CONSTRAINT IF EXISTS imz_sync_runs_check_04 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.sync_runs RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.inbox_events DROP CONSTRAINT IF EXISTS imz_inbox_events_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.inbox_events DROP CONSTRAINT IF EXISTS imz_inbox_events_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.inbox_events DROP CONSTRAINT IF EXISTS imz_inbox_events_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.inbox_events DROP CONSTRAINT IF EXISTS imz_inbox_events_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.inbox_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.outbox_events DROP CONSTRAINT IF EXISTS imz_outbox_events_pk RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.outbox_events DROP CONSTRAINT IF EXISTS imz_outbox_events_check_01 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.outbox_events DROP CONSTRAINT IF EXISTS imz_outbox_events_check_02 RESTRICT;
SQL);
DB::statement(<<<'SQL'
ALTER TABLE IF EXISTS public.outbox_events DROP CONSTRAINT IF EXISTS imz_outbox_events_check_03 RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TABLE IF EXISTS public.outbox_events RESTRICT;
SQL);
}
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,390 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
// Laravel's migration ledger provides idempotency; object drift fails explicitly.
public function up(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz requires PostgreSQL with PostGIS. Use the isolated pgsql test environment.');
}
DB::statement(<<<'SQL'
CREATE TRIGGER imz_organizations_updated BEFORE UPDATE ON public.organizations FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_memberships_updated BEFORE UPDATE ON public.memberships FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_consents_updated BEFORE UPDATE ON public.consents FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_documents_updated BEFORE UPDATE ON public.documents FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_geo_locations_updated BEFORE UPDATE ON public.geo_locations FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_geo_geometries_updated BEFORE UPDATE ON public.geo_geometries FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_projects_updated BEFORE UPDATE ON public.projects FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_project_locations_updated BEFORE UPDATE ON public.project_locations FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_economic_clusters_updated BEFORE UPDATE ON public.economic_clusters FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_value_chains_updated BEFORE UPDATE ON public.value_chains FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_value_chain_links_updated BEFORE UPDATE ON public.value_chain_links FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_cluster_projects_updated BEFORE UPDATE ON public.cluster_projects FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_anchor_project_links_updated BEFORE UPDATE ON public.anchor_project_links FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_complementary_project_links_updated BEFORE UPDATE ON public.complementary_project_links FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_development_corridors_updated BEFORE UPDATE ON public.development_corridors FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_corridor_locations_updated BEFORE UPDATE ON public.corridor_locations FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_corridor_projects_updated BEFORE UPDATE ON public.corridor_projects FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_corridor_clusters_updated BEFORE UPDATE ON public.corridor_clusters FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_investors_updated BEFORE UPDATE ON public.investors FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_contacts_updated BEFORE UPDATE ON public.contacts FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_investor_contacts_updated BEFORE UPDATE ON public.investor_contacts FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_leads_updated BEFORE UPDATE ON public.leads FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_crm_opportunities_updated BEFORE UPDATE ON public.crm_opportunities FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_activities_updated BEFORE UPDATE ON public.activities FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_tasks_updated BEFORE UPDATE ON public.tasks FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_investor_journeys_updated BEFORE UPDATE ON public.investor_journeys FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_journey_steps_updated BEFORE UPDATE ON public.journey_steps FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_submissions_updated BEFORE UPDATE ON public.submissions FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_aftercare_plans_updated BEFORE UPDATE ON public.aftercare_plans FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_constraints_updated BEFORE UPDATE ON public.constraints FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_escalations_updated BEFORE UPDATE ON public.escalations FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_skills_updated BEFORE UPDATE ON public.skills FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_occupations_updated BEFORE UPDATE ON public.occupations FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_training_needs_updated BEFORE UPDATE ON public.training_needs FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_training_providers_updated BEFORE UPDATE ON public.training_providers FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_courses_updated BEFORE UPDATE ON public.courses FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_education_opportunities_updated BEFORE UPDATE ON public.education_opportunities FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_outbox_events_updated BEFORE UPDATE ON public.outbox_events FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_inbox_events_updated BEFORE UPDATE ON public.inbox_events FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_sync_runs_updated BEFORE UPDATE ON public.sync_runs FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_reconciliation_issues_updated BEFORE UPDATE ON public.reconciliation_issues FOR EACH ROW EXECUTE FUNCTION public.investmoz_set_updated_at();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_audit_events_immutable BEFORE UPDATE OR DELETE OR TRUNCATE ON public.audit_events FOR EACH STATEMENT EXECUTE FUNCTION public.investmoz_reject_audit_change();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_outbox_events_envelope BEFORE UPDATE OR DELETE ON public.outbox_events FOR EACH ROW EXECUTE FUNCTION public.investmoz_protect_event_envelope();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_outbox_events_no_truncate BEFORE TRUNCATE ON public.outbox_events FOR EACH STATEMENT EXECUTE FUNCTION public.investmoz_reject_audit_change();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_inbox_events_envelope BEFORE UPDATE OR DELETE ON public.inbox_events FOR EACH ROW EXECUTE FUNCTION public.investmoz_protect_event_envelope();
SQL);
DB::statement(<<<'SQL'
CREATE TRIGGER imz_inbox_events_no_truncate BEFORE TRUNCATE ON public.inbox_events FOR EACH STATEMENT EXECUTE FUNCTION public.investmoz_reject_audit_change();
SQL);
}
public function down(): void
{
if (DB::connection()->getDriverName() !== 'pgsql') {
throw new RuntimeException('InvestMoz rollback requires PostgreSQL.');
}
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_inbox_events_no_truncate ON public.inbox_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_inbox_events_envelope ON public.inbox_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_outbox_events_no_truncate ON public.outbox_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_outbox_events_envelope ON public.outbox_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_audit_events_immutable ON public.audit_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_reconciliation_issues_updated ON public.reconciliation_issues RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_sync_runs_updated ON public.sync_runs RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_inbox_events_updated ON public.inbox_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_outbox_events_updated ON public.outbox_events RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_education_opportunities_updated ON public.education_opportunities RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_courses_updated ON public.courses RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_training_providers_updated ON public.training_providers RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_training_needs_updated ON public.training_needs RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_occupations_updated ON public.occupations RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_skills_updated ON public.skills RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_escalations_updated ON public.escalations RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_constraints_updated ON public.constraints RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_aftercare_plans_updated ON public.aftercare_plans RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_submissions_updated ON public.submissions RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_journey_steps_updated ON public.journey_steps RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_investor_journeys_updated ON public.investor_journeys RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_tasks_updated ON public.tasks RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_activities_updated ON public.activities RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_crm_opportunities_updated ON public.crm_opportunities RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_leads_updated ON public.leads RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_investor_contacts_updated ON public.investor_contacts RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_contacts_updated ON public.contacts RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_investors_updated ON public.investors RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_corridor_clusters_updated ON public.corridor_clusters RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_corridor_projects_updated ON public.corridor_projects RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_corridor_locations_updated ON public.corridor_locations RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_development_corridors_updated ON public.development_corridors RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_complementary_project_links_updated ON public.complementary_project_links RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_anchor_project_links_updated ON public.anchor_project_links RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_cluster_projects_updated ON public.cluster_projects RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_value_chain_links_updated ON public.value_chain_links RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_value_chains_updated ON public.value_chains RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_economic_clusters_updated ON public.economic_clusters RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_project_locations_updated ON public.project_locations RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_projects_updated ON public.projects RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_geo_geometries_updated ON public.geo_geometries RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_geo_locations_updated ON public.geo_locations RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_documents_updated ON public.documents RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_consents_updated ON public.consents RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_memberships_updated ON public.memberships RESTRICT;
SQL);
DB::statement(<<<'SQL'
DROP TRIGGER IF EXISTS imz_organizations_updated ON public.organizations RESTRICT;
SQL);
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('leads', function (Blueprint $table) {
$table->foreignId('interest_request_id')->nullable()->unique()->constrained('interest_requests')->restrictOnDelete();
$table->text('first_source')->nullable();
$table->text('last_source')->nullable();
$table->text('qualification_reason')->nullable();
});
Schema::table('tasks', function (Blueprint $table) {
$table->foreignUuid('lead_id')->nullable()->constrained('leads')->restrictOnDelete();
$table->index(['lead_id', 'status', 'due_at']);
});
}
public function down(): void
{
Schema::table('tasks', function (Blueprint $table) {
$table->dropIndex(['lead_id', 'status', 'due_at']);
$table->dropConstrainedForeignId('lead_id');
});
Schema::table('leads', function (Blueprint $table) {
$table->dropConstrainedForeignId('interest_request_id');
$table->dropColumn(['first_source', 'last_source', 'qualification_reason']);
});
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('investment_gaps', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('cluster_id')->constrained('economic_clusters')->restrictOnDelete();
$table->foreignUuid('value_chain_id')->constrained('value_chains')->restrictOnDelete();
$table->string('title', 200);
$table->text('location');
$table->text('required_capacity');
$table->text('rationale');
$table->string('status', 30)->default('identified');
$table->text('call_to_action');
$table->timestampsTz();
$table->softDeletesTz();
$table->index(['cluster_id', 'status']);
});
DB::statement("ALTER TABLE investment_gaps ADD CONSTRAINT investment_gaps_status_check CHECK (status IN ('identified','in_review','resolved','withdrawn'))");
}
public function down(): void
{
Schema::dropIfExists('investment_gaps');
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('interest_requests', function (Blueprint $table) {
$table->uuid('integration_id')->nullable()->unique();
});
Schema::create('interest_submission_receipts', function (Blueprint $table) {
$table->char('key_hash', 64)->primary();
$table->char('payload_hash', 64);
$table->foreignId('interest_request_id')->constrained('interest_requests')->restrictOnDelete();
$table->timestampTz('created_at');
});
}
public function down(): void
{
if (DB::table('interest_requests')->whereNotNull('integration_id')->exists()
|| DB::table('interest_submission_receipts')->exists()) {
throw new RuntimeException('Preserve submission identities and outbox links: reconcile captured events before schema rollback.');
}
Schema::dropIfExists('interest_submission_receipts');
Schema::table('interest_requests', fn (Blueprint $table) => $table->dropColumn('integration_id'));
}
};
@@ -0,0 +1,58 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('investment_dossiers', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('project_id')->nullable()->unique()->constrained('projects')->restrictOnDelete();
$table->foreignUuid('cluster_id')->nullable()->unique()->constrained('economic_clusters')->restrictOnDelete();
$table->foreignUuid('corridor_id')->nullable()->unique()->constrained('development_corridors')->restrictOnDelete();
$table->string('title');
$table->jsonb('content');
$table->text('source');
$table->string('publication_status')->default('draft');
$table->foreignId('editor_id')->nullable()->constrained('users')->restrictOnDelete();
$table->foreignId('reviewer_id')->nullable()->constrained('users')->restrictOnDelete();
$table->text('approval_evidence')->nullable();
$table->timestampTz('published_at')->nullable();
$table->timestampsTz();
$table->softDeletesTz();
});
DB::statement("ALTER TABLE investment_dossiers ADD CONSTRAINT dossier_one_entity CHECK (num_nonnulls(project_id, cluster_id, corridor_id) = 1), ADD CONSTRAINT dossier_publication CHECK (publication_status IN ('draft','published')), ADD CONSTRAINT dossier_review CHECK (publication_status <> 'published' OR (editor_id IS NOT NULL AND reviewer_id IS NOT NULL AND editor_id <> reviewer_id AND approval_evidence IS NOT NULL AND published_at IS NOT NULL))");
Schema::create('investor_accounts', function (Blueprint $table) {
$table->foreignId('user_id')->primary()->constrained('users')->restrictOnDelete();
$table->foreignUuid('investor_id')->unique()->constrained('investors')->restrictOnDelete();
$table->timestampsTz();
});
Schema::table('investor_journeys', function (Blueprint $table) {
$table->foreignId('user_id')->nullable()->constrained('users')->restrictOnDelete();
$table->foreignUuid('dossier_id')->nullable()->constrained('investment_dossiers')->restrictOnDelete();
$table->foreignUuid('origin_dossier_id')->nullable()->constrained('investment_dossiers')->restrictOnDelete();
$table->foreignId('interest_request_id')->nullable()->constrained('interest_requests')->restrictOnDelete();
$table->unique(['user_id', 'dossier_id']);
});
}
public function down(): void
{
if (DB::table('investment_dossiers')->exists() || DB::table('investor_accounts')->exists()) {
throw new RuntimeException('Preserve portfolio and investor data: reconcile before schema rollback.');
}
Schema::table('investor_journeys', function (Blueprint $table) {
$table->dropUnique(['user_id', 'dossier_id']);
$table->dropConstrainedForeignId('interest_request_id');
$table->dropConstrainedForeignId('dossier_id');
$table->dropConstrainedForeignId('origin_dossier_id');
$table->dropConstrainedForeignId('user_id');
});
Schema::dropIfExists('investor_accounts');
Schema::dropIfExists('investment_dossiers');
}
};
@@ -0,0 +1,54 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
foreach (['labour_demands', 'training_capacities'] as $name) {
Schema::create($name, function (Blueprint $table) use ($name) {
$table->uuid('id')->primary();
$table->foreignUuid('occupation_id')->constrained('occupations')->restrictOnDelete();
$table->foreignUuid('skill_id')->constrained('skills')->restrictOnDelete();
$table->foreignUuid('geo_location_id')->constrained('geo_locations')->restrictOnDelete();
if ($name === 'labour_demands') {
$table->foreignUuid('project_id')->constrained('projects')->restrictOnDelete();
$table->string('employer');
} else {
$table->foreignUuid('course_id')->constrained('courses')->restrictOnDelete();
}
$table->string('qualification');
$table->unsignedInteger('quantity');
$table->date('period_start');
$table->date('period_end');
$table->text('source');
$table->date('reference_date');
$table->date('valid_until');
$table->string('status')->default('submitted');
$table->unsignedInteger('version_no')->default(1);
$table->foreignId('submitted_by')->constrained('users')->restrictOnDelete();
$table->foreignId('reviewed_by')->nullable()->constrained('users')->restrictOnDelete();
$table->text('review_reason')->nullable();
$table->timestampsTz();
$table->softDeletesTz();
$table->index(['status', 'valid_until']);
});
DB::statement("ALTER TABLE {$name} ADD CONSTRAINT {$name}_valid CHECK (quantity > 0 AND version_no > 0 AND period_end >= period_start AND valid_until >= reference_date AND status IN ('submitted','reviewed','rejected') AND (status = 'submitted' OR (reviewed_by IS NOT NULL AND reviewed_by <> submitted_by AND review_reason IS NOT NULL)))");
}
}
public function down(): void
{
foreach (['training_capacities', 'labour_demands'] as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Preserve education submissions and reconcile before rollback.');
}
}
Schema::dropIfExists('training_capacities');
Schema::dropIfExists('labour_demands');
}
};
@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('education_investment_proposals', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('labour_demand_id')->unique()->constrained('labour_demands')->restrictOnDelete();
$table->unsignedInteger('demand_version');
$table->foreignId('opportunity_id')->unique()->constrained('opportunities')->restrictOnDelete();
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
$table->text('intervention');
$table->text('equipment_needs')->nullable();
$table->text('trainer_needs')->nullable();
$table->text('funding_plan')->nullable();
$table->text('risks');
$table->text('source');
$table->timestampsTz();
$table->softDeletesTz();
});
}
public function down(): void
{
if (DB::table('education_investment_proposals')->exists()) {
throw new RuntimeException('Preserve educational proposal links and reconcile before rollback.');
}
Schema::dropIfExists('education_investment_proposals');
}
};
@@ -0,0 +1,96 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('ai_controls', function (Blueprint $table) {
$table->string('capability', 30)->primary();
$table->boolean('suspended')->default(false);
$table->timestampsTz();
});
foreach (['assistant', 'search', 'recommend', 'classify', 'quality', 'sla', 'summary'] as $capability) {
DB::table('ai_controls')->insert(['capability' => $capability, 'suspended' => false, 'created_at' => now(), 'updated_at' => now()]);
}
Schema::create('ai_sources', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('document_id')->constrained('documents')->restrictOnDelete();
$table->unsignedInteger('document_version');
$table->char('document_checksum', 64);
$table->string('title', 200);
$table->string('language', 2);
$table->string('nature', 20);
$table->text('source_url');
$table->string('source_owner', 200);
$table->text('evidence_reference');
$table->date('source_date');
$table->date('valid_until');
$table->string('purpose', 50)->default('investment_information');
$table->string('status', 20)->default('pending');
$table->foreignId('submitted_by')->constrained('users')->restrictOnDelete();
$table->foreignId('reviewed_by')->nullable()->constrained('users')->restrictOnDelete();
$table->timestampTz('reviewed_at')->nullable();
$table->timestampsTz();
$table->unique(['document_id', 'document_version']);
$table->index(['status', 'valid_until']);
});
DB::statement("ALTER TABLE ai_sources ADD CONSTRAINT ai_sources_valid CHECK (document_version > 0 AND language IN ('pt','en') AND nature IN ('official','historical','illustrative','pending') AND status IN ('pending','approved','revoked') AND valid_until >= source_date AND (status <> 'approved' OR (reviewed_by IS NOT NULL AND reviewed_by <> submitted_by AND reviewed_at IS NOT NULL)))");
Schema::create('ai_chunks', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('source_id')->constrained('ai_sources')->restrictOnDelete();
$table->unsignedInteger('position');
$table->string('language', 2);
$table->text('content');
$table->char('checksum', 64);
$table->unique(['source_id', 'position']);
});
DB::statement("ALTER TABLE ai_chunks ADD COLUMN lexical tsvector GENERATED ALWAYS AS (CASE WHEN language = 'pt' THEN to_tsvector('portuguese', content) ELSE to_tsvector('english', content) END) STORED");
DB::statement('CREATE INDEX ai_chunks_lexical_idx ON ai_chunks USING gin (lexical)');
Schema::create('ai_runs', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$table->string('capability', 30);
$table->string('purpose', 50);
$table->string('mode', 40);
$table->string('rules_version', 80);
$table->string('prompt_version', 80);
$table->char('input_hash', 64);
$table->text('result');
$table->jsonb('source_ids')->default('[]');
$table->unsignedInteger('latency_ms');
$table->boolean('review_requested')->default(false);
$table->string('review_status', 20)->default('pending');
$table->foreignId('reviewed_by')->nullable()->constrained('users')->restrictOnDelete();
$table->timestampTz('reviewed_at')->nullable();
$table->unsignedInteger('version_no')->default(1);
$table->timestampsTz();
$table->index(['actor_id', 'created_at']);
});
DB::statement("ALTER TABLE ai_runs ADD CONSTRAINT ai_runs_review_valid CHECK (review_status IN ('pending','accepted','rejected') AND version_no > 0 AND (review_status = 'pending' OR (reviewed_by IS NOT NULL AND reviewed_by <> actor_id AND reviewed_at IS NOT NULL)))");
Schema::create('ai_feedback', function (Blueprint $table) {
$table->id();
$table->foreignUuid('run_id')->constrained('ai_runs')->restrictOnDelete();
$table->foreignId('user_id')->constrained('users')->restrictOnDelete();
$table->string('rating', 30);
$table->timestampsTz();
$table->unique(['run_id', 'user_id']);
});
}
public function down(): void
{
foreach (['ai_sources', 'ai_runs', 'ai_feedback'] as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Preserve AI evidence and reviews; disable the feature instead of deleting data.');
}
}
foreach (['ai_feedback', 'ai_runs', 'ai_chunks', 'ai_sources', 'ai_controls'] as $table) {
Schema::dropIfExists($table);
}
}
};
@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
DB::statement("ALTER TABLE investment_dossiers ADD COLUMN approval_basis varchar(40) NOT NULL DEFAULT 'manager', DROP CONSTRAINT dossier_review, ADD CONSTRAINT dossier_approval_basis CHECK (approval_basis IN ('manager','document_owner')), ADD CONSTRAINT dossier_review CHECK (publication_status <> 'published' OR (approval_evidence IS NOT NULL AND length(trim(approval_evidence)) >= 15 AND published_at IS NOT NULL AND (reviewer_id IS NOT NULL OR approval_basis = 'document_owner')))");
}
public function down(): void
{
if (DB::table('investment_dossiers')->where('publication_status', 'published')->where(function ($query) {
$query->whereNull('editor_id')->orWhereNull('reviewer_id')->orWhereColumn('editor_id', 'reviewer_id');
})->exists()) {
throw new RuntimeException('Preserve owner approvals before restoring the two-reviewer policy.');
}
DB::statement("ALTER TABLE investment_dossiers DROP CONSTRAINT dossier_review, DROP CONSTRAINT dossier_approval_basis, DROP COLUMN approval_basis, ADD CONSTRAINT dossier_review CHECK (publication_status <> 'published' OR (editor_id IS NOT NULL AND reviewer_id IS NOT NULL AND editor_id <> reviewer_id AND approval_evidence IS NOT NULL AND published_at IS NOT NULL))");
}
};
@@ -0,0 +1,47 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('portal_resources', function (Blueprint $table) {
$table->id();
$table->foreignUuid('document_id')->constrained('documents')->restrictOnDelete();
$table->string('title');
$table->string('category');
$table->string('topic');
$table->boolean('legislation')->default(false);
$table->boolean('essential')->default(false);
$table->boolean('published')->default(false);
$table->text('source_reference');
$table->foreignId('approved_by')->constrained('users')->restrictOnDelete();
$table->timestampsTz();
});
Schema::create('portal_partnerships', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->restrictOnDelete();
$table->string('title');
$table->string('sector');
$table->string('province');
$table->text('offer');
$table->text('seeking');
$table->string('status')->default('pending');
$table->foreignId('reviewed_by')->nullable()->constrained('users')->restrictOnDelete();
$table->timestampsTz();
});
}
public function down(): void
{
if (DB::table('portal_resources')->exists() || DB::table('portal_partnerships')->exists()) {
throw new RuntimeException('Preserve portal resources and partnership submissions before rollback.');
}
Schema::dropIfExists('portal_partnerships');
Schema::dropIfExists('portal_resources');
}
};
@@ -0,0 +1,111 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('investment_reference_options', function (Blueprint $t) {
$t->id();
$t->string('group');
$t->string('code');
$t->string('label');
$t->boolean('active')->default(true);
$t->boolean('requires_description')->default(false);
$t->unsignedInteger('sort_order')->default(0);
$t->timestampsTz();
$t->unique(['group', 'code']);
});
Schema::create('opportunity_profiles', function (Blueprint $t) {
$t->foreignId('opportunity_id')->primary()->constrained('opportunities')->restrictOnDelete();
$t->boolean('is_education')->default(false)->index();
$t->unsignedInteger('version')->default(1);
$t->text('business_model')->nullable();
$t->text('requirements')->nullable();
$t->text('risks')->nullable();
$t->date('target_date')->nullable();
$t->text('source_reference')->nullable();
$t->timestampsTz();
});
foreach (['clusters' => ['cluster_id', 'economic_clusters'], 'corridors' => ['corridor_id', 'development_corridors'],
'projects' => ['project_id', 'projects'], 'locations' => ['geo_location_id', 'geo_locations']] as $name => [$foreign, $target]) {
Schema::create('opportunity_'.$name, function (Blueprint $t) use ($foreign, $target) {
$t->foreignId('opportunity_id')->constrained('opportunities')->restrictOnDelete();
$t->foreignUuid($foreign)->constrained($target)->restrictOnDelete();
$t->primary(['opportunity_id', $foreign]);
$t->index($foreign);
});
}
Schema::create('opportunity_facets', function (Blueprint $t) {
$t->foreignId('opportunity_id')->constrained('opportunities')->restrictOnDelete();
$t->foreignId('option_id')->constrained('investment_reference_options')->restrictOnDelete();
$t->primary(['opportunity_id', 'option_id']);
$t->index('option_id');
});
Schema::create('investment_submissions', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignId('user_id')->constrained('users')->restrictOnDelete();
$t->foreignId('opportunity_id')->nullable()->constrained('opportunities')->restrictOnDelete();
$t->foreignUuid('dossier_id')->nullable()->constrained('investment_dossiers')->restrictOnDelete();
$t->foreignId('interest_request_id')->nullable()->unique()->constrained('interest_requests')->restrictOnDelete();
$t->text('payload');
$t->string('status')->default('draft')->index();
$t->unsignedInteger('version')->default(1);
$t->timestampsTz();
$t->index(['user_id', 'status']);
});
DB::statement("ALTER TABLE investment_submissions ADD CONSTRAINT submission_status CHECK(status IN ('draft','submitted')), ADD CONSTRAINT submission_target CHECK(num_nonnulls(opportunity_id,dossier_id)<=1), ADD CONSTRAINT submission_receipt CHECK ((status='draft' AND interest_request_id IS NULL) OR (status='submitted' AND interest_request_id IS NOT NULL))");
Schema::create('investment_specific_needs', function (Blueprint $t) {
$t->id();
$t->foreignUuid('submission_id')->constrained('investment_submissions')->restrictOnDelete();
$t->foreignId('category_id')->constrained('investment_reference_options')->restrictOnDelete();
$t->foreignId('option_id')->constrained('investment_reference_options')->restrictOnDelete();
$t->foreignId('unit_id')->nullable()->constrained('investment_reference_options')->restrictOnDelete();
$t->foreignId('priority_id')->nullable()->constrained('investment_reference_options')->restrictOnDelete();
$t->decimal('quantity', 16, 2)->nullable();
$t->date('deadline')->nullable();
$t->text('details');
$t->timestampsTz();
});
DB::statement('ALTER TABLE investment_specific_needs ADD CONSTRAINT need_quantity CHECK(quantity IS NULL OR quantity>=0)');
Schema::create('investment_submission_attachments', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('submission_id')->constrained('investment_submissions')->restrictOnDelete();
$t->foreignUuid('document_id')->constrained('documents')->restrictOnDelete();
$t->timestampsTz();
});
Schema::create('investment_submission_events', function (Blueprint $t) {
$t->id();
$t->foreignUuid('submission_id')->constrained('investment_submissions')->restrictOnDelete();
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->string('action');
$t->unsignedInteger('version');
$t->timestampTz('created_at')->useCurrent();
});
Schema::create('opportunity_favourites', function (Blueprint $t) {
$t->foreignId('user_id')->constrained('users')->restrictOnDelete();
$t->foreignId('opportunity_id')->constrained('opportunities')->restrictOnDelete();
$t->timestampsTz();
$t->primary(['user_id', 'opportunity_id']);
});
}
public function down(): void
{
$tables = ['opportunity_favourites', 'investment_submission_events', 'investment_submission_attachments', 'investment_specific_needs',
'investment_submissions', 'opportunity_facets', 'opportunity_locations', 'opportunity_projects', 'opportunity_corridors', 'opportunity_clusters',
'opportunity_profiles', 'investment_reference_options'];
foreach ($tables as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Preserve investment unification data before rollback.');
}
}
foreach ($tables as $table) {
Schema::dropIfExists($table);
}
}
};
@@ -0,0 +1,71 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('investment_accounts', function (Blueprint $t) {
$t->foreignId('user_id')->primary()->constrained('users')->restrictOnDelete();
$t->text('payload');
$t->unsignedInteger('version')->default(1);
$t->timestampsTz();
});
Schema::create('investment_company_declarations', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignId('user_id')->constrained('users')->restrictOnDelete();
$t->text('payload');
$t->unsignedInteger('version')->default(1);
$t->timestampsTz();
$t->index('user_id');
});
Schema::create('investment_messages', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('submission_id')->constrained('investment_submissions')->restrictOnDelete();
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->uuid('client_key');
$t->string('sender_role');
$t->text('body');
$t->timestampTz('created_at')->useCurrent();
$t->unique(['submission_id', 'actor_id', 'client_key']);
});
DB::statement("ALTER TABLE investment_messages ADD CONSTRAINT investment_message_role CHECK(sender_role IN ('investor','support'))");
Schema::create('investment_notifications', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignId('user_id')->constrained('users')->restrictOnDelete();
$t->foreignUuid('submission_id')->constrained('investment_submissions')->restrictOnDelete();
$t->string('kind');
$t->text('payload');
$t->string('event_key');
$t->timestampTz('read_at')->nullable();
$t->timestampTz('created_at')->useCurrent();
$t->unique(['user_id', 'event_key']);
$t->index(['user_id', 'read_at']);
});
Schema::create('investment_submission_revisions', function (Blueprint $t) {
$t->id();
$t->foreignUuid('submission_id')->constrained('investment_submissions')->restrictOnDelete();
$t->unsignedInteger('version');
$t->text('snapshot');
$t->timestampTz('created_at')->useCurrent();
$t->unique(['submission_id', 'version']);
});
}
public function down(): void
{
$tables = ['investment_submission_revisions', 'investment_notifications', 'investment_messages', 'investment_company_declarations', 'investment_accounts'];
foreach ($tables as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Preserve investor workspace data before rollback.');
}
}
foreach ($tables as $table) {
Schema::dropIfExists($table);
}
}
};
@@ -0,0 +1,20 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('investment_dossiers', function (Blueprint $table) {
$table->unsignedInteger('version_no')->default(1);
});
}
public function down(): void
{
throw new RuntimeException('Preserve editorial versions; restore a verified backup instead.');
}
};
@@ -0,0 +1,159 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private const TABLES = ['investment_zone_revisions', 'investment_zone_geometries', 'investment_zone_links', 'investment_zone_relations', 'investment_item_projects', 'investment_item_opportunities', 'investment_items', 'investment_zones', 'investment_legal_sources'];
public function up(): void
{
Schema::create('investment_legal_sources', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->string('title');
$t->text('url');
$t->string('diploma');
$t->string('article');
$t->string('competent_entity');
$t->date('valid_from');
$t->date('valid_until')->nullable();
$t->string('validation_status')->default('pending');
$t->foreignId('owner_id')->constrained('users')->restrictOnDelete();
$t->foreignId('validator_id')->nullable()->constrained('users')->restrictOnDelete();
$t->timestampTz('validated_at')->nullable();
$t->unsignedInteger('version_no')->default(1);
$t->timestampsTz();
});
DB::statement("ALTER TABLE investment_legal_sources ADD CHECK(validation_status IN ('pending','validated','revoked')), ADD CHECK(valid_until IS NULL OR valid_until>=valid_from), ADD CHECK(version_no>0), ADD CHECK(validation_status<>'validated' OR (validator_id IS NOT NULL AND validator_id<>owner_id AND validated_at IS NOT NULL))");
Schema::create('investment_zones', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->string('code')->unique();
$t->string('category');
$t->string('name');
$t->string('name_en')->nullable();
$t->text('description')->nullable();
$t->text('description_en')->nullable();
$t->string('province')->nullable();
$t->string('district')->nullable();
$t->foreignUuid('operator_id')->nullable()->constrained('organizations')->restrictOnDelete();
$t->foreignUuid('legal_source_id')->nullable()->constrained('investment_legal_sources')->restrictOnDelete();
$t->string('publication_status')->default('draft');
$t->string('validation_status')->default('pending');
$t->foreignId('editor_id')->constrained('users')->restrictOnDelete();
$t->foreignId('reviewer_id')->nullable()->constrained('users')->restrictOnDelete();
$t->timestampTz('published_at')->nullable();
$t->unsignedInteger('version_no')->default(1);
$t->timestampsTz();
$t->softDeletesTz();
});
DB::statement("ALTER TABLE investment_zones ADD CHECK(category IN ('zee','zfi','industrial_park','pending')), ADD CHECK(publication_status IN ('draft','published','suspended')), ADD CHECK(validation_status IN ('pending','validated','historical')), ADD CHECK(version_no>0), ADD CHECK(publication_status<>'published' OR (validation_status='validated' AND category<>'pending' AND legal_source_id IS NOT NULL AND operator_id IS NOT NULL AND reviewer_id IS NOT NULL AND reviewer_id<>editor_id AND published_at IS NOT NULL AND name_en IS NOT NULL AND description_en IS NOT NULL))");
Schema::create('investment_items', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->string('code')->unique();
$t->string('title');
$t->string('kind');
$t->string('validation_status')->default('pending');
$t->unsignedInteger('version_no')->default(1);
$t->timestampsTz();
});
foreach (['opportunities' => ['opportunity_id', false], 'projects' => ['project_id', true]] as $table => [$foreign, $uuid]) {
Schema::create('investment_item_'.$table, function (Blueprint $t) use ($table, $foreign, $uuid) {
$t->foreignUuid('item_id')->constrained('investment_items')->restrictOnDelete();
if ($uuid) {
$t->foreignUuid($foreign)->constrained($table)->restrictOnDelete();
} else {
$t->foreignId($foreign)->constrained($table)->restrictOnDelete();
}
$t->primary(['item_id', $foreign]);
$t->unique($foreign);
$t->text('mapping_evidence');
$t->timestampsTz();
});
}
// Explicit nullable FKs: exactly one target, no polymorphic unverified identifiers.
Schema::create('investment_zone_relations', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('zone_id')->constrained('investment_zones')->restrictOnDelete();
$t->foreignUuid('cluster_id')->nullable()->constrained('economic_clusters')->restrictOnDelete();
$t->foreignUuid('corridor_id')->nullable()->constrained('development_corridors')->restrictOnDelete();
$t->foreignUuid('project_id')->nullable()->constrained('projects')->restrictOnDelete();
$this->relationFields($t);
});
DB::statement('ALTER TABLE investment_zone_relations ADD CHECK(num_nonnulls(cluster_id,corridor_id,project_id)=1)');
foreach (['cluster_id', 'corridor_id', 'project_id'] as $key) {
DB::statement("CREATE UNIQUE INDEX zone_relation_{$key}_unique ON investment_zone_relations(zone_id,{$key}) WHERE {$key} IS NOT NULL");
}
Schema::create('investment_zone_links', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('item_id')->constrained('investment_items')->restrictOnDelete();
$t->foreignUuid('zone_id')->constrained('investment_zones')->restrictOnDelete();
$this->relationFields($t);
$t->unique(['item_id', 'zone_id']);
});
foreach (['investment_zone_links', 'investment_zone_relations'] as $table) {
DB::statement("ALTER TABLE {$table} ADD CHECK(association_type IN ('official','influence','proximity','potential','historical')), ADD CHECK(validation_status IN ('pending','validated','revoked')), ADD CHECK(valid_until IS NULL OR valid_until>=valid_from), ADD CHECK(length(trim(source_reference))>=10), ADD CHECK(version_no>0), ADD CHECK(association_type<>'official' OR legal_source_id IS NOT NULL), ADD CHECK(validation_status<>'validated' OR (validator_id IS NOT NULL AND validator_id<>editor_id))");
}
Schema::create('investment_zone_geometries', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('zone_id')->constrained('investment_zones')->restrictOnDelete();
$t->foreignUuid('geometry_id')->constrained('geo_geometries')->restrictOnDelete();
$t->foreignUuid('legal_source_id')->nullable()->constrained('investment_legal_sources')->restrictOnDelete();
$t->string('purpose');
$t->text('source_reference');
$t->string('validating_entity');
$t->date('observed_at');
$t->boolean('publication_authorized')->default(false);
$t->string('validation_status')->default('pending');
$t->unsignedInteger('version_no')->default(1);
$t->timestampsTz();
$t->unique(['zone_id', 'geometry_id']);
});
DB::statement("ALTER TABLE investment_zone_geometries ADD CHECK(purpose IN ('official_perimeter','influence','site','alternative')), ADD CHECK(validation_status IN ('pending','validated','revoked')), ADD CHECK(purpose<>'official_perimeter' OR legal_source_id IS NOT NULL), ADD CHECK(NOT publication_authorized OR validation_status='validated')");
Schema::create('investment_zone_revisions', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('zone_id')->constrained('investment_zones')->restrictOnDelete();
$t->unsignedInteger('version_no');
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->string('action');
$t->text('snapshot');
$t->char('sha256', 64);
$t->timestampTz('created_at')->useCurrent();
$t->unique(['zone_id', 'version_no']);
});
DB::unprepared("CREATE OR REPLACE FUNCTION reject_zone_revision_change() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Zone revisions are immutable'; END $$; CREATE TRIGGER immutable_zone_revision BEFORE UPDATE OR DELETE ON investment_zone_revisions FOR EACH ROW EXECUTE FUNCTION reject_zone_revision_change()");
}
private function relationFields(Blueprint $t): void
{
$t->string('role')->default('related');
$t->string('association_type')->default('potential');
$t->boolean('is_primary')->default(false);
$t->integer('priority')->default(0);
$t->text('justification');
$t->text('source_reference');
$t->foreignUuid('legal_source_id')->nullable()->constrained('investment_legal_sources')->restrictOnDelete();
$t->date('valid_from');
$t->date('valid_until')->nullable();
$t->string('validation_status')->default('pending');
$t->foreignId('editor_id')->constrained('users')->restrictOnDelete();
$t->foreignId('validator_id')->nullable()->constrained('users')->restrictOnDelete();
$t->unsignedInteger('version_no')->default(1);
$t->timestampsTz();
}
public function down(): void
{
foreach (self::TABLES as $table) {
if (DB::table($table)->exists()) {
throw new RuntimeException('Zone data exists. Restore a verified backup; do not discard records.');
}
}
foreach (self::TABLES as $table) {
Schema::drop($table);
}
DB::statement('DROP FUNCTION reject_zone_revision_change()');
}
};
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('investment_zone_geometries', function (Blueprint $t) {
$t->foreignId('editor_id')->nullable()->constrained('users')->restrictOnDelete();
$t->foreignId('reviewer_id')->nullable()->constrained('users')->restrictOnDelete();
});
DB::statement('ALTER TABLE investment_zone_geometries ADD CONSTRAINT zone_geometry_independent_review CHECK(NOT publication_authorized OR (editor_id IS NOT NULL AND reviewer_id IS NOT NULL AND editor_id<>reviewer_id))');
}
public function down(): void
{
if (DB::table('investment_zone_geometries')->exists()) {
throw new RuntimeException('Preserve GIS reviews; restore a verified backup.');
}
DB::statement('ALTER TABLE investment_zone_geometries DROP CONSTRAINT zone_geometry_independent_review');
Schema::table('investment_zone_geometries', function (Blueprint $t) {
$t->dropConstrainedForeignId('editor_id');
$t->dropConstrainedForeignId('reviewer_id');
});
}
};
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('investment_submission_zones', function (Blueprint $t) {
$t->foreignUuid('submission_id')->primary()->constrained('investment_submissions')->restrictOnDelete();
$t->foreignUuid('zone_id')->constrained('investment_zones')->restrictOnDelete();
$t->unsignedInteger('zone_version');
$t->string('intent');
$t->timestampTz('created_at')->useCurrent();
$t->index(['zone_id', 'intent']);
});
DB::statement("ALTER TABLE investment_submission_zones ADD CHECK(zone_version>0), ADD CHECK(intent IN ('interest','dossier','meeting'))");
}
public function down(): void
{
if (DB::table('investment_submission_zones')->exists()) {
throw new RuntimeException('Preserve submission origins; restore a verified backup.');
}
Schema::drop('investment_submission_zones');
}
};
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
if (! app()->environment(['local', 'testing'])) {
return;
}
$this->call(InvestMozReferenceSeeder::class);
$this->call(InvestmentReferenceSeeder::class);
// User::factory(10)->create();
User::firstOrCreate(
['email' => 'test@example.com'],
[
'name' => 'Test User',
'password' => Hash::make(Str::random(48)),
],
);
}
}
@@ -0,0 +1,40 @@
<?php
namespace Database\Seeders;
use App\Models\Investor;
use App\Models\Project;
use Illuminate\Database\Seeder;
class InvestMozReferenceSeeder extends Seeder
{
public function run(): void
{
if (! app()->environment(['local', 'testing'])) {
throw new \RuntimeException('Reference fixtures are restricted to local/testing.');
}
Project::withTrashed()->updateOrCreate(
['source_system' => 'example', 'external_id' => 'PROJECT-001'],
[
'code' => 'EXAMPLE-PROJECT-001',
'name' => 'Projecto fictício para validação técnica',
'status' => 'draft',
'budget_amount' => '1000.00',
'budget_currency' => 'MZN',
'data_classification' => 'internal',
'deleted_at' => null,
],
);
Investor::withTrashed()->updateOrCreate(
['source_system' => 'example', 'external_id' => 'INVESTOR-001'],
[
'legal_name' => 'Entidade fictícia para validação técnica',
'investor_type' => 'institutional',
'status' => 'prospect',
'data_classification' => 'internal',
'deleted_at' => null,
],
);
}
}
@@ -0,0 +1,66 @@
<?php
namespace Database\Seeders;
use App\Models\DevelopmentCorridor;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\Project;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class InvestmentPortfolioSeeder extends Seeder
{
public function run(): void
{
$data = json_decode(File::get(database_path('data/investment-portfolio.json')), true, 512, JSON_THROW_ON_ERROR);
DB::transaction(function () use ($data) {
DB::select('select pg_advisory_xact_lock(250925, 130000)');
$ids = [];
foreach (['projects' => [Project::class, 'project_id', 'draft', '6.1 / 6.6'],
'clusters' => [EconomicCluster::class, 'cluster_id', 'planned', '4.5.2'],
'corridors' => [DevelopmentCorridor::class, 'corridor_id', 'proposed', '4.3.4']] as $kind => [$model, $foreign, $status, $section]) {
foreach ($data[$kind] as $item) {
// Never overwrite a manually edited record or silently take over its code.
$record = $model::withTrashed()->where('code', $item['code'])->first();
if ($record && ($record->getAttribute('source_system') !== 'upgrade-v4' || $record->trashed())) {
throw new \RuntimeException('Portfolio code collision: '.$item['code']);
}
$record ??= $model::create(['code' => $item['code'], 'name' => $item['name'], 'status' => $status,
'source_system' => 'upgrade-v4', 'external_id' => $item['code'],
...($kind === 'clusters' ? ['sector' => $item['name']] : ['description' => $item['description'] ?? $item['focus']])]);
$ids[$item['code']] = $record->id;
InvestmentDossier::withTrashed()->firstOrCreate([$foreign => $record->id], [
'title' => $item['name'], 'source' => $data['source'].' — '.$section,
'content' => [...$item, 'notice' => $data['notice']], 'publication_status' => 'draft',
]);
}
}
foreach (['clusters' => ['cluster_projects', 'cluster_id'], 'corridors' => ['corridor_projects', 'corridor_id']] as $kind => [$table, $foreign]) {
foreach ($data[$kind] as $item) {
preg_match_all('/\bA\d{2}\b/', $item['anchors'], $matches);
foreach (array_unique($matches[0]) as $code) {
$key = [$foreign => $ids[$item['code']], 'project_id' => $ids[$code]];
if (! DB::table($table)->where($key)->exists()) {
DB::table($table)->insert([...$key, 'id' => (string) Str::uuid(), 'source_system' => 'upgrade-v4',
...($kind === 'clusters' ? ['role' => 'anchor'] : [])]);
}
}
}
}
// Only unambiguous correspondences in section 4.3.4; no inferred mining anchors.
$matrix = ['COR-01' => [1, 2, 3, 4, 6], 'COR-02' => [1, 2, 3, 5], 'COR-03' => [1, 2, 3, 6],
'COR-04' => [1, 3], 'COR-05' => [4, 7], 'COR-06' => [2, 3, 7]];
foreach ($matrix as $corridor => $clusters) {
foreach ($clusters as $cluster) {
$key = ['corridor_id' => $ids[$corridor], 'cluster_id' => $ids[sprintf('CLU-%02d', $cluster)]];
if (! DB::table('corridor_clusters')->where($key)->exists()) {
DB::table('corridor_clusters')->insert([...$key, 'id' => (string) Str::uuid(), 'source_system' => 'upgrade-v4']);
}
}
}
});
}
}
@@ -0,0 +1,23 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class InvestmentReferenceSeeder extends Seeder
{
public function run(): void
{
$groups = json_decode(File::get(database_path('data/investment-reference-options.json')), true, 512, JSON_THROW_ON_ERROR);
DB::transaction(function () use ($groups) {
foreach ($groups as $group => $options) {
foreach ([...$options, 'other' => 'Outro — especificar'] as $code => $label) {
DB::table('investment_reference_options')->insertOrIgnore(['group' => $group, 'code' => $code, 'label' => $label,
'active' => true, 'requires_description' => $code === 'other', 'created_at' => now(), 'updated_at' => now()]);
}
}
});
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Database\Seeders;
use App\Models\Opportunity;
use App\Models\Sector;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class OpportunitySeeder extends Seeder
{
/** @var array<int, string> */
private array $maturityLabels = [
1 => 'Ideia identificada',
2 => 'Pré-estudo disponível',
3 => 'Estudo de viabilidade em curso',
4 => 'Projecto estruturado',
5 => 'Pronto para investimento',
6 => 'Em negociação ou implementação',
];
public function run(): void
{
$items = [
['sector' => 'agronegocio', 'reference' => 'INV-MZ-AGR-001', 'title' => 'Unidade de processamento agrícola em Nampula', 'province' => 'Nampula', 'maturity' => 4, 'amount' => 2500000, 'financing' => 'Capital e parceria técnica', 'impact' => '120 empregos directos e substituição de importações.', 'featured' => true],
['sector' => 'energia', 'reference' => 'INV-MZ-ENE-002', 'title' => 'Mini-rede solar para polo produtivo', 'province' => 'Zambézia', 'maturity' => 3, 'amount' => 1200000, 'financing' => 'PPP ou financiamento misto', 'impact' => 'Acesso a energia para 40 unidades produtivas.', 'featured' => true],
['sector' => 'turismo', 'reference' => 'INV-MZ-TUR-003', 'title' => 'Eco-lodge costeiro com integração comunitária', 'province' => 'Inhambane', 'maturity' => 2, 'amount' => 1800000, 'financing' => 'Capital privado ou joint venture', 'impact' => 'Emprego local e conservação da faixa costeira.', 'featured' => true],
['sector' => 'infraestruturas', 'reference' => 'INV-MZ-INF-004', 'title' => 'Centro logístico provincial', 'province' => 'Sofala', 'maturity' => 4, 'amount' => 8500000, 'financing' => 'Concessão ou PPP', 'impact' => 'Redução de custos logísticos regionais.', 'featured' => false],
['sector' => 'economia-azul', 'reference' => 'INV-MZ-BLUE-005', 'title' => 'Processamento de pescado e cadeia fria', 'province' => 'Zambézia', 'maturity' => 2, 'amount' => 900000, 'financing' => 'Capital, crédito ou parceria operacional', 'impact' => 'Redução de perdas pós-captura na pesca artesanal.', 'featured' => false],
['sector' => 'mercado-financeiro', 'reference' => 'INV-MZ-FIN-006', 'title' => 'Plataforma de crédito para PME agrícolas', 'province' => 'Maputo Cidade', 'maturity' => 3, 'amount' => 3000000, 'financing' => 'Fundo de investimento ou parceiro financeiro', 'impact' => 'Acesso a financiamento para 300+ pequenas empresas.', 'featured' => false],
];
foreach ($items as $item) {
$sector = Sector::where('slug', $item['sector'])->first();
if (! $sector) {
continue;
}
Opportunity::updateOrCreate(
['reference' => $item['reference']],
[
'sector_id' => $sector->id,
'title' => $item['title'],
'slug' => Str::slug($item['reference'].'-'.$item['title']),
'summary' => $item['impact'],
'description' => $item['impact'],
'province' => $item['province'],
'promoter_name' => 'Promotor em validação',
'promoter_type' => 'privado',
'maturity_level' => $item['maturity'],
'maturity_label' => $this->maturityLabels[$item['maturity']],
'estimated_investment_amount' => $item['amount'],
'estimated_investment_currency' => 'USD',
'financing_modality' => $item['financing'],
'expected_impact' => $item['impact'],
'status' => 'published',
'is_featured' => $item['featured'],
'published_at' => now(),
]
);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace Database\Seeders;
use App\Models\Sector;
use Illuminate\Database\Seeder;
class SectorSeeder extends Seeder
{
public function run(): void
{
$sectors = [
['name' => 'Agronegócio', 'slug' => 'agronegocio', 'short_description' => 'Produção, agroprocessamento, irrigação e cadeias de valor agrícolas.'],
['name' => 'Energia e Mineração', 'slug' => 'energia', 'short_description' => 'Energias renováveis, transição energética e mineração responsável.'],
['name' => 'Turismo', 'slug' => 'turismo', 'short_description' => 'Hotelaria, turismo costeiro, cultural e ecológico.'],
['name' => 'Infraestruturas', 'slug' => 'infraestruturas', 'short_description' => 'Logística, transportes, parques industriais e energia.'],
['name' => 'Economia Azul', 'slug' => 'economia-azul', 'short_description' => 'Pesca, aquacultura, portos e logística marítima.'],
['name' => 'Mercado Financeiro', 'slug' => 'mercado-financeiro', 'short_description' => 'Fintech, capital de risco e instrumentos financeiros.'],
];
foreach ($sectors as $index => $sector) {
Sector::updateOrCreate(
['slug' => $sector['slug']],
[...$sector, 'is_active' => true, 'sort_order' => $index + 1, 'published_at' => now()]
);
}
}
}