feat: otimização de performance e ajustes finais
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
-- =====================================================
|
||||
-- Script: Recriação completa do schema PUBLIC
|
||||
-- ATENÇÃO: Este script apaga TODOS os dados do banco!
|
||||
-- =====================================================
|
||||
--
|
||||
-- INSTRUÇÕES DE USO:
|
||||
-- 1. Se houver erro de "transação abortada", execute:
|
||||
-- ROLLBACK;
|
||||
-- 2. Depois execute este script completo
|
||||
-- =====================================================
|
||||
|
||||
-- Visualiza quantas tabelas existem antes de apagar
|
||||
SELECT
|
||||
'ATENÇÃO: Existem ' || COUNT(*) || ' tabelas que serão apagadas!' AS aviso
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = 'public';
|
||||
|
||||
-- Apaga o schema public e TODOS os objetos dentro dele
|
||||
-- (tabelas, views, funções, sequences, tipos, etc.)
|
||||
DROP SCHEMA IF EXISTS public CASCADE;
|
||||
|
||||
-- Recria o schema public vazio
|
||||
CREATE SCHEMA public;
|
||||
|
||||
-- Restaura as permissões padrão do PostgreSQL
|
||||
GRANT ALL ON SCHEMA public TO postgres;
|
||||
GRANT ALL ON SCHEMA public TO public;
|
||||
|
||||
-- Confirma que o schema foi recriado
|
||||
SELECT
|
||||
'Schema PUBLIC foi recriado com sucesso!' AS resultado,
|
||||
COUNT(*) AS tabelas_restantes
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = 'public';
|
||||
@@ -0,0 +1,219 @@
|
||||
# 📊 Scripts de Dados de Teste - SIGEFP
|
||||
|
||||
Este diretório contém scripts SQL para popular o banco de dados com dados de teste completos.
|
||||
|
||||
## 📋 Scripts Disponíveis
|
||||
|
||||
### 1. `insert_all_test_data.sql` (BASE)
|
||||
**O que faz:**
|
||||
- Cria a estrutura base de dados de teste
|
||||
- Popula tabelas fundamentais: ministérios, unidades orgânicas, cargos
|
||||
- Cria estrutura salarial completa
|
||||
- Adiciona tipos de proventos e descontos
|
||||
- Cria agentes, contratos e contas bancárias
|
||||
- Cria ano fiscal e linhas orçamentárias
|
||||
- Adiciona um período de folha básico
|
||||
|
||||
**Quando usar:**
|
||||
- Primeira carga de dados de teste
|
||||
- Reset do banco de dados de desenvolvimento
|
||||
- Base para testes unitários
|
||||
|
||||
**Execução:**
|
||||
```sql
|
||||
\i sigefp-database/insert_all_test_data.sql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. `insert_functional_test_data.sql` (COMPLEMENTAR)
|
||||
**O que faz:**
|
||||
- Adiciona períodos de folha adicionais (Fevereiro, Março 2025)
|
||||
- Cria execuções de folha completas com status COMPLETED
|
||||
- Adiciona itens de folha completos com todos os cálculos:
|
||||
- Vencimento Base
|
||||
- Abono de Família
|
||||
- INPS (7%)
|
||||
- IRPS (escalonado)
|
||||
- Imposto de Selo (0.3%)
|
||||
- Cria execuções orçamentárias (COMMITMENT, LIQUIDATION, PAYMENT)
|
||||
- Adiciona lotes de pagamento
|
||||
- Cria ordens de pagamento geradas a partir da folha
|
||||
- Adiciona confirmações de pagamento do tesouro
|
||||
- Completa o fluxo RH → Budget → Treasury
|
||||
|
||||
**Quando usar:**
|
||||
- Após executar `insert_all_test_data.sql`
|
||||
- Para testes funcionais completos
|
||||
- Para testar fluxos end-to-end
|
||||
- Para validar integrações entre módulos
|
||||
|
||||
**Execução:**
|
||||
```sql
|
||||
\i sigefp-database/insert_functional_test_data.sql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. `insert_complete_test_data.sql` (ALTERNATIVO)
|
||||
**O que faz:**
|
||||
- Versão simplificada que usa dados existentes
|
||||
- Adiciona dados complementares básicos
|
||||
- Útil quando já existe alguma estrutura no banco
|
||||
|
||||
**Quando usar:**
|
||||
- Quando já há dados no banco e quer apenas complementar
|
||||
- Para adicionar dados específicos sem sobrescrever
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Sequência Recomendada de Execução
|
||||
|
||||
### Para Testes Completos:
|
||||
```sql
|
||||
-- 1. Executar script base
|
||||
\i sigefp-database/insert_all_test_data.sql
|
||||
|
||||
-- 2. Executar script complementar para testes funcionais
|
||||
\i sigefp-database/insert_functional_test_data.sql
|
||||
```
|
||||
|
||||
### Para Testes Básicos:
|
||||
```sql
|
||||
-- Apenas o script base
|
||||
\i sigefp-database/insert_all_test_data.sql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Dados Criados
|
||||
|
||||
### Após `insert_all_test_data.sql`:
|
||||
- ✅ 3 Ministérios
|
||||
- ✅ 4 Unidades Orgânicas
|
||||
- ✅ 4 Cargos
|
||||
- ✅ 3 Bancos
|
||||
- ✅ 1 Ano Fiscal (2025)
|
||||
- ✅ 3 Linhas Orçamentárias
|
||||
- ✅ 3 Alocações Orçamentárias
|
||||
- ✅ Estrutura Salarial Completa
|
||||
- ✅ 3 Tipos de Proventos
|
||||
- ✅ 3 Tipos de Descontos
|
||||
- ✅ Regras Globais de Desconto
|
||||
- ✅ 5 Escalões de IRPS
|
||||
- ✅ 5 Agentes
|
||||
- ✅ 3 Contas Bancárias
|
||||
- ✅ 2 Contratos
|
||||
- ✅ 1 Período de Folha (Janeiro 2025)
|
||||
- ✅ 1 Execução de Folha (DRAFT)
|
||||
- ✅ 3 Itens de Folha Básicos
|
||||
|
||||
### Após `insert_functional_test_data.sql`:
|
||||
- ✅ +2 Períodos de Folha (Fevereiro, Março)
|
||||
- ✅ +2 Execuções de Folha (COMPLETED)
|
||||
- ✅ +12 Itens de Folha Completos (com todos os cálculos)
|
||||
- ✅ 6 Execuções Orçamentárias (COMMITMENT, LIQUIDATION, PAYMENT)
|
||||
- ✅ 2 Lotes de Pagamento
|
||||
- ✅ 3 Ordens de Pagamento
|
||||
- ✅ 3 Confirmações de Pagamento do Tesouro
|
||||
- ✅ Fluxo completo RH → Budget → Treasury
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Cenários de Teste Cobertos
|
||||
|
||||
### ✅ Testes Unitários:
|
||||
- Cálculos de INPS, IRPS e Selo
|
||||
- Geração de itens de folha
|
||||
- Validações de saldo orçamentário
|
||||
- Criação de ordens de pagamento
|
||||
|
||||
### ✅ Testes de Integração:
|
||||
- Fluxo completo: Folha → Compromisso → Liquidação → Pagamento
|
||||
- Integração RH → Budget
|
||||
- Integração Treasury → Budget
|
||||
- Validações cruzadas entre módulos
|
||||
|
||||
### ✅ Testes Funcionais:
|
||||
- Processamento de folha completa
|
||||
- Geração de lotes de pagamento
|
||||
- Confirmação de pagamentos
|
||||
- Consultas e relatórios
|
||||
- Dashboard com dados reais
|
||||
|
||||
---
|
||||
|
||||
## 📝 Notas Importantes
|
||||
|
||||
1. **Ordem de Execução**: Sempre execute `insert_all_test_data.sql` antes de `insert_functional_test_data.sql`
|
||||
|
||||
2. **Conflitos**: Os scripts usam `ON CONFLICT DO NOTHING`, então podem ser executados múltiplas vezes sem erro
|
||||
|
||||
3. **IDs Fixos**: Alguns IDs são fixos (UUIDs) para facilitar testes e referências
|
||||
|
||||
4. **Dados Realistas**: Os valores são baseados em valores típicos de Guiné-Bissau (em Francos CFA)
|
||||
|
||||
5. **Cálculos**: Os valores de descontos são calculados corretamente:
|
||||
- INPS: 7% sobre o bruto
|
||||
- Selo: 0.3% sobre o bruto
|
||||
- IRPS: Escalonado conforme faixas (10-25%)
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Verificação dos Dados
|
||||
|
||||
Após executar os scripts, você pode verificar os dados com:
|
||||
|
||||
```sql
|
||||
-- Verificar contagens
|
||||
SELECT 'PERIODOS FOLHA' as tipo, COUNT(*)::text as total
|
||||
FROM payroll_period WHERE fiscal_year = 2025
|
||||
UNION ALL
|
||||
SELECT 'EXECUCOES FOLHA', COUNT(*)::text
|
||||
FROM payroll_run WHERE period_id IN (
|
||||
SELECT id FROM payroll_period WHERE fiscal_year = 2025
|
||||
)
|
||||
UNION ALL
|
||||
SELECT 'ITENS FOLHA', COUNT(*)::text
|
||||
FROM payroll_item WHERE payroll_run_id IN (
|
||||
SELECT id FROM payroll_run WHERE period_id IN (
|
||||
SELECT id FROM payroll_period WHERE fiscal_year = 2025
|
||||
)
|
||||
)
|
||||
UNION ALL
|
||||
SELECT 'EXECUCOES ORCAMENTARIAS', COUNT(*)::text
|
||||
FROM budget_execution WHERE period_id >= 202501
|
||||
UNION ALL
|
||||
SELECT 'LOTES PAGAMENTO', COUNT(*)::text
|
||||
FROM payment_batch WHERE period_id >= 202501
|
||||
UNION ALL
|
||||
SELECT 'ORDENS PAGAMENTO', COUNT(*)::text
|
||||
FROM payment_order WHERE payment_batch_id IN (
|
||||
SELECT id FROM payment_batch WHERE period_id >= 202501
|
||||
)
|
||||
UNION ALL
|
||||
SELECT 'CONFIRMACOES TESOURO', COUNT(*)::text
|
||||
FROM treasury_payment WHERE payment_order_id IN (
|
||||
SELECT id FROM payment_order WHERE payment_batch_id IN (
|
||||
SELECT id FROM payment_batch WHERE period_id >= 202501
|
||||
)
|
||||
)
|
||||
ORDER BY tipo;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Próximos Passos
|
||||
|
||||
Com esses dados, você pode:
|
||||
1. ✅ Testar todas as funcionalidades do sistema
|
||||
2. ✅ Validar cálculos de folha de pagamento
|
||||
3. ✅ Testar integrações entre módulos
|
||||
4. ✅ Validar fluxos de negócio completos
|
||||
5. ✅ Testar relatórios e dashboards
|
||||
6. ✅ Validar regras de negócio do Decreto 12-A/94
|
||||
|
||||
---
|
||||
|
||||
**Última atualização:** 2024-12-22
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Índices para melhorar a performance de filtragem e busca de agentes
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_org_unit ON agents(org_unit_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_position ON agents(position_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_functional_situation ON agents(functional_situation);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_appointment_type ON agents(appointment_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_agents_hire_date ON agents(hire_date);
|
||||
|
||||
-- Índices para os relacionamentos carregados em lote (Corrigido para nomes de tabela no singular)
|
||||
CREATE INDEX IF NOT EXISTS idx_agent_contract_active ON agent_contract(agent_id) WHERE is_active = true;
|
||||
CREATE INDEX IF NOT EXISTS idx_agent_bank_account_primary ON agent_bank_account(agent_id) WHERE is_primary = true;
|
||||
|
||||
-- Índices para o módulo de Orçamento
|
||||
CREATE INDEX IF NOT EXISTS idx_budget_execution_line ON budget_execution(budget_line_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_budget_execution_period ON budget_execution(period_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_budget_execution_type ON budget_execution(movement_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_budget_line_fiscal_year ON budget_line(fiscal_year_id);
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,445 @@
|
||||
-- ============================================================================
|
||||
-- SCRIPT COMPLETO DE DADOS DE TESTE - SIGEFP
|
||||
-- Popula TODAS as 27 tabelas do sistema com dados realistas
|
||||
-- ============================================================================
|
||||
|
||||
-- Lista de tabelas a popular:
|
||||
-- 1. ministry, 2. org_unit, 3. position
|
||||
-- 4. fiscal_year, 5. budget_line, 6. budget_allocation, 7. budget_execution
|
||||
-- 8. bank
|
||||
-- 9. salary_category, 10. salary_grade, 11. salary_step, 12. salary_grid
|
||||
-- 13. deduction_type, 14. earning_type, 15. global_deduction_rule, 16. tax_bracket
|
||||
-- 17. agents, 18. agent_contract, 19. agent_bank_account, 20. agent_deduction_rule, 21. agent_status_history
|
||||
-- 22. career_events, 23. performance_evaluations
|
||||
-- 24. payroll_period, 25. payroll_run, 26. payroll_item
|
||||
-- 27. user_account, 28. role, 29. user_role, 30. permissions
|
||||
-- 31. payment_batch, 32. payment_order, 33. treasury_payment, 34. payments
|
||||
-- 35. audit_log
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
-- Ministerios
|
||||
v_min_financas UUID;
|
||||
v_min_saude UUID;
|
||||
v_min_educacao UUID;
|
||||
|
||||
-- Unidades Organicas
|
||||
v_ou_tesouro UUID;
|
||||
v_ou_orcamento UUID;
|
||||
v_ou_hospital UUID;
|
||||
v_ou_escola UUID;
|
||||
|
||||
-- Cargos
|
||||
v_pos_diretor UUID;
|
||||
v_pos_tecnico UUID;
|
||||
v_pos_medico UUID;
|
||||
v_pos_professor UUID;
|
||||
|
||||
-- Estrutura Salarial
|
||||
v_cat_ts UUID;
|
||||
v_grade_a UUID;
|
||||
v_step_1 UUID;
|
||||
v_step_2 UUID;
|
||||
v_step_3 UUID;
|
||||
|
||||
-- Tipos de Proventos e Descontos
|
||||
v_earning_vencimento UUID;
|
||||
v_earning_abono UUID;
|
||||
v_deduction_inps UUID;
|
||||
v_deduction_irps UUID;
|
||||
v_deduction_selo UUID;
|
||||
|
||||
-- Ano Fiscal e Linhas Orcamentais
|
||||
v_fy_2025 UUID;
|
||||
v_bl_financas UUID;
|
||||
v_bl_saude UUID;
|
||||
v_bl_educacao UUID;
|
||||
|
||||
-- Agentes
|
||||
v_agent_amilcar UUID;
|
||||
v_agent_francisca UUID;
|
||||
v_agent_joao UUID;
|
||||
v_agent_maria UUID;
|
||||
v_agent_samba UUID;
|
||||
|
||||
-- Periodo e Folha
|
||||
v_period_jan2025 UUID;
|
||||
v_payroll_run UUID;
|
||||
|
||||
-- Usuarios e Roles
|
||||
v_role_admin UUID;
|
||||
v_user_admin UUID;
|
||||
|
||||
-- Bancos
|
||||
v_bank_bceao UUID;
|
||||
BEGIN
|
||||
RAISE NOTICE '=== INICIANDO CARGA DE DADOS COMPLETA ===';
|
||||
|
||||
-- ========================================================================
|
||||
-- 1. MINISTERIOS
|
||||
-- ========================================================================
|
||||
SELECT id INTO v_min_financas FROM ministry WHERE code = 'MIN-001';
|
||||
|
||||
IF v_min_financas IS NULL THEN
|
||||
INSERT INTO ministry (id, code, name, acronym, is_active, created_at, updated_at)
|
||||
VALUES ('11111111-1111-1111-1111-111111111111', 'MIN-001', 'Ministerio das Financas', 'MINFIN', true, now(), now())
|
||||
RETURNING id INTO v_min_financas;
|
||||
END IF;
|
||||
|
||||
INSERT INTO ministry (id, code, name, acronym, is_active, created_at, updated_at) VALUES
|
||||
('22222222-2222-2222-2222-222222222222', 'MIN-002', 'Ministerio da Saude Publica', 'MINSAUDE', true, now(), now()),
|
||||
('33333333-3333-3333-3333-333333333333', 'MIN-003', 'Ministerio da Educacao Nacional', 'MINEDU', true, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_min_saude FROM ministry WHERE code = 'MIN-002';
|
||||
SELECT id INTO v_min_educacao FROM ministry WHERE code = 'MIN-003';
|
||||
|
||||
-- ========================================================================
|
||||
-- 2. UNIDADES ORGANICAS
|
||||
-- ========================================================================
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, unit_type, is_active, created_at, updated_at) VALUES
|
||||
('44444444-4444-4444-4444-444444444444', 'UO-001', 'Direcao-Geral do Tesouro', v_min_financas, 'DIRECTORATE', true, now(), now()),
|
||||
('55555555-5555-5555-5555-555555555555', 'UO-002', 'Direcao-Geral do Orcamento', v_min_financas, 'DIRECTORATE', true, now(), now()),
|
||||
('66666666-6666-6666-6666-666666666666', 'UO-003', 'Hospital Nacional Simao Mendes', v_min_saude, 'HOSPITAL', true, now(), now()),
|
||||
('77777777-7777-7777-7777-777777777777', 'UO-004', 'Escola Secundaria de Bissau', v_min_educacao, 'SCHOOL', true, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_ou_tesouro FROM org_unit WHERE code = 'UO-001';
|
||||
SELECT id INTO v_ou_orcamento FROM org_unit WHERE code = 'UO-002';
|
||||
SELECT id INTO v_ou_hospital FROM org_unit WHERE code = 'UO-003';
|
||||
SELECT id INTO v_ou_escola FROM org_unit WHERE code = 'UO-004';
|
||||
|
||||
-- ========================================================================
|
||||
-- 3. CARGOS (POSITIONS)
|
||||
-- ========================================================================
|
||||
INSERT INTO position (id, code, title, org_unit_id, is_active, created_at, updated_at) VALUES
|
||||
('88888888-8888-8888-8888-888888888888', 'POS-001', 'Diretor-Geral', v_ou_tesouro, true, now(), now()),
|
||||
('99999999-9999-9999-9999-999999999999', 'POS-002', 'Tecnico Superior', v_ou_orcamento, true, now(), now()),
|
||||
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'POS-003', 'Medico Especialista', v_ou_hospital, true, now(), now()),
|
||||
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'POS-004', 'Professor', v_ou_escola, true, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_pos_diretor FROM position WHERE code = 'POS-001';
|
||||
SELECT id INTO v_pos_tecnico FROM position WHERE code = 'POS-002';
|
||||
SELECT id INTO v_pos_medico FROM position WHERE code = 'POS-003';
|
||||
SELECT id INTO v_pos_professor FROM position WHERE code = 'POS-004';
|
||||
|
||||
-- ========================================================================
|
||||
-- 4. ANO FISCAL
|
||||
-- ========================================================================
|
||||
INSERT INTO fiscal_year (id, year, start_date, end_date, status, created_at, updated_at) VALUES
|
||||
('f2025000-0000-0000-0000-000000000000', 2025, '2025-01-01', '2025-12-31', 'OPEN', now(), now())
|
||||
ON CONFLICT (year) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
|
||||
|
||||
-- ========================================================================
|
||||
-- 5. BANCOS
|
||||
-- ========================================================================
|
||||
INSERT INTO bank (id, code, name, swift_code, created_at, updated_at) VALUES
|
||||
('cccccccc-cccc-cccc-cccc-cccccccccccc', 'BCEAO', 'Banco Central dos Estados da Africa Ocidental', 'BCAOXXXX', now(), now()),
|
||||
('dddddddd-dddd-dddd-dddd-dddddddddddd', 'BRS', 'Banco Regional de Solidariedade', 'BRSXGWGW', now(), now()),
|
||||
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'BIC', 'Banco Internacional da Guine', 'BICXGWGW', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_bank_bceao FROM bank WHERE code = 'BCEAO';
|
||||
|
||||
-- ========================================================================
|
||||
-- 6. ESTRUTURA SALARIAL
|
||||
-- ========================================================================
|
||||
SELECT id INTO v_cat_ts FROM salary_category WHERE code = 'TS';
|
||||
SELECT id INTO v_grade_a FROM salary_grade WHERE code = 'A' AND category_id = v_cat_ts;
|
||||
SELECT id INTO v_step_1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 1;
|
||||
|
||||
-- Verificar se os steps já existem antes de inserir
|
||||
IF NOT EXISTS (SELECT 1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 2) THEN
|
||||
INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at) VALUES
|
||||
('00000002-0000-0000-0000-000000000000', v_grade_a, 2, now(), now());
|
||||
END IF;
|
||||
|
||||
IF NOT EXISTS (SELECT 1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 3) THEN
|
||||
INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at) VALUES
|
||||
('00000003-0000-0000-0000-000000000000', v_grade_a, 3, now(), now());
|
||||
END IF;
|
||||
|
||||
SELECT id INTO v_step_2 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 2;
|
||||
SELECT id INTO v_step_3 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 3;
|
||||
|
||||
INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at) VALUES
|
||||
('00000020-0000-0000-0000-000000000000', v_step_2, 550000.00, '2024-01-01', now(), now()),
|
||||
('00000030-0000-0000-0000-000000000000', v_step_3, 600000.00, '2024-01-01', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 7. TIPOS DE PROVENTOS (EARNING_TYPE)
|
||||
-- ========================================================================
|
||||
INSERT INTO earning_type (id, code, name, taxable, economic_class_code, created_at, updated_at) VALUES
|
||||
('00000100-0000-0000-0000-000000000000', 'VENC-BASE', 'Vencimento Base', true, '311100', now(), now()),
|
||||
('00000200-0000-0000-0000-000000000000', 'ABONO-FAM', 'Abono de Familia', false, '311200', now(), now()),
|
||||
('00000300-0000-0000-0000-000000000000', 'SUBSIDIO-FUNC', 'Subsidio de Funcao', true, '311300', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_earning_vencimento FROM earning_type WHERE code = 'VENC-BASE';
|
||||
SELECT id INTO v_earning_abono FROM earning_type WHERE code = 'ABONO-FAM';
|
||||
|
||||
-- ========================================================================
|
||||
-- 8. TIPOS DE DESCONTOS (DEDUCTION_TYPE)
|
||||
-- ========================================================================
|
||||
INSERT INTO deduction_type (id, code, name, mandatory, economic_class_code, created_at, updated_at) VALUES
|
||||
('00001000-0000-0000-0000-000000000000', 'INPS', 'Instituto Nacional de Previdencia Social', true, '321100', now(), now()),
|
||||
('00002000-0000-0000-0000-000000000000', 'IRPS', 'Imposto sobre Rendimento de Pessoas Singulares', true, '321200', now(), now()),
|
||||
('00003000-0000-0000-0000-000000000000', 'SELO', 'Imposto de Selo', true, '321300', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_deduction_inps FROM deduction_type WHERE code = 'INPS';
|
||||
SELECT id INTO v_deduction_irps FROM deduction_type WHERE code = 'IRPS';
|
||||
SELECT id INTO v_deduction_selo FROM deduction_type WHERE code = 'SELO';
|
||||
|
||||
-- ========================================================================
|
||||
-- 9. REGRAS GLOBAIS DE DESCONTO
|
||||
-- ========================================================================
|
||||
INSERT INTO global_deduction_rule (id, deduction_type_id, percentage, active, valid_from, created_at, updated_at) VALUES
|
||||
('00010000-0000-0000-0000-000000000000', v_deduction_inps, 0.0700, true, '2024-01-01', now(), now()),
|
||||
('00020000-0000-0000-0000-000000000000', v_deduction_selo, 0.0030, true, '2024-01-01', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 10. ESCALOES DE IRPS (TAX_BRACKET)
|
||||
-- ========================================================================
|
||||
INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at) VALUES
|
||||
('00010001-0000-0000-0000-000000000000', v_deduction_irps, 0, 50000, 0.0000, 0, '2024-01-01', now(), now()),
|
||||
('00010002-0000-0000-0000-000000000000', v_deduction_irps, 50001, 150000, 0.1000, 5000, '2024-01-01', now(), now()),
|
||||
('00010003-0000-0000-0000-000000000000', v_deduction_irps, 150001, 250000, 0.1500, 12500, '2024-01-01', now(), now()),
|
||||
('00010004-0000-0000-0000-000000000000', v_deduction_irps, 250001, 500000, 0.2000, 25000, '2024-01-01', now(), now()),
|
||||
('00010005-0000-0000-0000-000000000000', v_deduction_irps, 500001, NULL, 0.2500, 50000, '2024-01-01', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 11. LINHAS ORCAMENTAIS
|
||||
-- ========================================================================
|
||||
INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at) VALUES
|
||||
('00020001-0000-0000-0000-000000000000', v_fy_2025, '2025-MINFIN-311100', 'Vencimentos Base - Financas', v_min_financas, v_ou_tesouro, '311100', now(), now()),
|
||||
('00020002-0000-0000-0000-000000000000', v_fy_2025, '2025-MINSAUDE-311100', 'Vencimentos Base - Saude', v_min_saude, v_ou_hospital, '311100', now(), now()),
|
||||
('00020003-0000-0000-0000-000000000000', v_fy_2025, '2025-MINEDU-311100', 'Vencimentos Base - Educacao', v_min_educacao, v_ou_escola, '311100', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_bl_financas FROM budget_line WHERE code = '2025-MINFIN-311100';
|
||||
SELECT id INTO v_bl_saude FROM budget_line WHERE code = '2025-MINSAUDE-311100';
|
||||
SELECT id INTO v_bl_educacao FROM budget_line WHERE code = '2025-MINEDU-311100';
|
||||
|
||||
-- ========================================================================
|
||||
-- 12. ALOCACOES ORCAMENTAIS
|
||||
-- ========================================================================
|
||||
INSERT INTO budget_allocation (id, budget_line_id, initial_amount, adjustment_amount, created_at, updated_at) VALUES
|
||||
('00030001-0000-0000-0000-000000000000', v_bl_financas, 50000000.00, 0.00, now(), now()),
|
||||
('00030002-0000-0000-0000-000000000000', v_bl_saude, 30000000.00, 0.00, now(), now()),
|
||||
('00030003-0000-0000-0000-000000000000', v_bl_educacao, 40000000.00, 0.00, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 13. AGENTES
|
||||
-- ========================================================================
|
||||
INSERT INTO agents (
|
||||
id, matricula, nif, bi_number, full_name, birth_date, nationality,
|
||||
email, phone, address, hire_date, posse_date, appointment_type,
|
||||
functional_situation, literary_qualification, status,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
eligible_dependents_count, created_at, updated_at
|
||||
) VALUES
|
||||
('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', '2020/001', '100123456', 'BI123456', 'Amilcar Cabral Silva', '1975-03-15', 'Guineense',
|
||||
'amilcar.silva@minfin.gov.gw', '+245 955 123 456', 'Bairro de Penha, Bissau',
|
||||
'2020-01-15', '2020-02-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
v_ou_tesouro, v_pos_diretor, v_cat_ts, v_grade_a, v_step_3, 2, now(), now()),
|
||||
|
||||
('b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', '2021/045', '100234567', 'BI234567', 'Francisca Pereira Gomes', '1988-07-22', 'Guineense',
|
||||
'francisca.gomes@minfin.gov.gw', '+245 955 234 567', 'Bairro Militar, Bissau',
|
||||
'2021-03-10', '2021-04-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'MESTRADO', 'ACTIVE',
|
||||
v_ou_orcamento, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_2, 1, now(), now()),
|
||||
|
||||
('c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', '2019/089', '100345678', 'BI345678', 'Dr. Joao Vieira Mendes', '1982-11-30', 'Guineense',
|
||||
'joao.mendes@minsaude.gov.gw', '+245 955 345 678', 'Bairro de Antula, Bissau',
|
||||
'2019-06-01', '2019-07-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'DOUTORAMENTO', 'ACTIVE',
|
||||
v_ou_hospital, v_pos_medico, v_cat_ts, v_grade_a, v_step_3, 3, now(), now()),
|
||||
|
||||
('d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', '2022/112', '100456789', 'BI456789', 'Maria da Luz Correia', '1990-05-18', 'Guineense',
|
||||
'maria.correia@minedu.gov.gw', '+245 955 456 789', 'Bairro de Quelele, Bissau',
|
||||
'2022-09-01', '2022-10-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
v_ou_escola, v_pos_professor, v_cat_ts, v_grade_a, v_step_1, 0, now(), now()),
|
||||
|
||||
('e5e5e5e5-e5e5-e5e5-e5e5-e5e5e5e5e5e5', '2024/201', '100567890', 'BI567890', 'Samba Djalo', '1995-09-12', 'Guineense',
|
||||
'samba.djalo@minfin.gov.gw', '+245 955 567 890', 'Bairro de Chao de Papel, Bissau',
|
||||
'2024-11-01', '2024-12-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
v_ou_tesouro, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_1, 0, now(), now())
|
||||
ON CONFLICT (matricula) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_agent_amilcar FROM agents WHERE matricula = '2020/001';
|
||||
SELECT id INTO v_agent_francisca FROM agents WHERE matricula = '2021/045';
|
||||
SELECT id INTO v_agent_joao FROM agents WHERE matricula = '2019/089';
|
||||
SELECT id INTO v_agent_maria FROM agents WHERE matricula = '2022/112';
|
||||
SELECT id INTO v_agent_samba FROM agents WHERE matricula = '2024/201';
|
||||
|
||||
-- ========================================================================
|
||||
-- 14. CONTAS BANCARIAS DOS AGENTES
|
||||
-- ========================================================================
|
||||
INSERT INTO agent_bank_account (id, agent_id, bank, account_number, branch_code, is_primary, created_at, updated_at) VALUES
|
||||
('00040001-0000-0000-0000-000000000000', v_agent_amilcar, 'BCEAO', '1234567890', '001', true, now(), now()),
|
||||
('00040002-0000-0000-0000-000000000000', v_agent_francisca, 'BRS', '2345678901', '002', true, now(), now()),
|
||||
('00040003-0000-0000-0000-000000000000', v_agent_joao, 'BIC', '3456789012', '003', true, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 15. CONTRATOS DOS AGENTES
|
||||
-- ========================================================================
|
||||
INSERT INTO agent_contract (
|
||||
id, agent_id, contract_type, start_date, is_active,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
base_salary_ref, weekly_hours, created_at, updated_at
|
||||
) VALUES
|
||||
('00050001-0000-0000-0000-000000000000', v_agent_amilcar, 'PERMANENT', '2020-02-01', true,
|
||||
v_ou_tesouro, v_pos_diretor, v_cat_ts, v_grade_a, v_step_3, 600000.00, 40.00, now(), now()),
|
||||
('00050002-0000-0000-0000-000000000000', v_agent_francisca, 'PERMANENT', '2021-04-01', true,
|
||||
v_ou_orcamento, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_2, 550000.00, 40.00, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 16. HISTORICO DE STATUS DOS AGENTES
|
||||
-- ========================================================================
|
||||
INSERT INTO agent_status_history (
|
||||
id, agent_id, changed_at, previous_status, new_status, event_type, reason
|
||||
) VALUES
|
||||
('00060001-0000-0000-0000-000000000000', v_agent_amilcar, '2020-02-01', 'REGISTERED', 'ACTIVE', 'ADMISSAO', 'Nomeacao definitiva'),
|
||||
('00060002-0000-0000-0000-000000000000', v_agent_francisca, '2021-04-01', 'REGISTERED', 'ACTIVE', 'ADMISSAO', 'Nomeacao definitiva')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 17. EVENTOS DE CARREIRA
|
||||
-- ========================================================================
|
||||
INSERT INTO career_events (
|
||||
id, agent_id, event_type, effective_date, document_ref, reason,
|
||||
new_org_unit, new_position, new_category, new_grade, new_step,
|
||||
total_base_amount, created_at, updated_at
|
||||
) VALUES
|
||||
('00070001-0000-0000-0000-000000000000', v_agent_amilcar, 'ADMISSAO', '2020-02-01', 'DEC-2020-001', 'Admissao por concurso',
|
||||
v_ou_tesouro, v_pos_diretor, v_cat_ts, v_grade_a, v_step_3, 600000.00, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 18. AVALIACOES DE DESEMPENHO
|
||||
-- ========================================================================
|
||||
INSERT INTO performance_evaluations (
|
||||
id, agent_id, reference_year, score, qualitative_mention, evaluation_date, created_at, updated_at
|
||||
) VALUES
|
||||
('00080001-0000-0000-0000-000000000000', v_agent_amilcar, 2024, 18.5, 'EXCELENTE', '2024-12-15', now(), now()),
|
||||
('00080002-0000-0000-0000-000000000000', v_agent_francisca, 2024, 17.0, 'BOM', '2024-12-15', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 19. PERIODO DE FOLHA
|
||||
-- ========================================================================
|
||||
INSERT INTO payroll_period (id, fiscal_year, month, start_date, end_date, status, created_at, updated_at) VALUES
|
||||
('00090001-0000-0000-0000-000000000000', 2025, 1, '2025-01-01', '2025-01-31', 'OPEN', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_period_jan2025 FROM payroll_period WHERE fiscal_year = 2025 AND month = 1;
|
||||
|
||||
-- ========================================================================
|
||||
-- 20. PROCESSAMENTO DE FOLHA
|
||||
-- ========================================================================
|
||||
INSERT INTO payroll_run (id, period_id, ministry_id, run_type, status, created_at, updated_at) VALUES
|
||||
('000a0001-0000-0000-0000-000000000000', v_period_jan2025, v_min_financas, 'REGULAR', 'DRAFT', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_payroll_run FROM payroll_run WHERE period_id = v_period_jan2025;
|
||||
|
||||
-- ========================================================================
|
||||
-- 21. ITENS DE FOLHA
|
||||
-- ========================================================================
|
||||
INSERT INTO payroll_item (
|
||||
id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
|
||||
description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
|
||||
) VALUES
|
||||
-- Vencimento Amilcar
|
||||
('000b0001-0000-0000-0000-000000000000', v_payroll_run, v_agent_amilcar, 'EARNING', v_earning_vencimento, NULL,
|
||||
'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_financas, now(), now()),
|
||||
-- INPS Amilcar
|
||||
('000b0002-0000-0000-0000-000000000000', v_payroll_run, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_inps,
|
||||
'INPS 7%', 42000.00, 1.00, 42000.00, NULL, now(), now()),
|
||||
-- Vencimento Francisca
|
||||
('000b0003-0000-0000-0000-000000000000', v_payroll_run, v_agent_francisca, 'EARNING', v_earning_vencimento, NULL,
|
||||
'Vencimento Base', 550000.00, 1.00, 550000.00, v_bl_financas, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 22. USUARIOS E ROLES
|
||||
-- ========================================================================
|
||||
INSERT INTO role (id, code, name, description, created_at, updated_at) VALUES
|
||||
('000c0001-0000-0000-0000-000000000000', 'ADMIN', 'Administrador', 'Acesso total ao sistema', now(), now()),
|
||||
('000c0002-0000-0000-0000-000000000000', 'RH_MANAGER', 'Gestor de RH', 'Gestao de recursos humanos', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_role_admin FROM role WHERE code = 'ADMIN';
|
||||
|
||||
INSERT INTO user_account (id, username, email, full_name, password_hash, is_active, created_at, updated_at) VALUES
|
||||
('000d0001-0000-0000-0000-000000000000', 'admin', 'admin@sigefp.gov.gw', 'Administrador do Sistema',
|
||||
'$2a$10$N9qo8uLOickgx2ZMRZoMye1234567890abcdefghijklmnopqrstuvwxyz', true, now(), now())
|
||||
ON CONFLICT (username) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_user_admin FROM user_account WHERE username = 'admin';
|
||||
|
||||
INSERT INTO user_role (id, user_id, role_id, created_at, updated_at) VALUES
|
||||
('000e0001-0000-0000-0000-000000000000', v_user_admin, v_role_admin, now(), now())
|
||||
ON CONFLICT (user_id, role_id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 23. PERMISSOES
|
||||
-- ========================================================================
|
||||
INSERT INTO permissions (id, code, description, module, created_at, updated_at) VALUES
|
||||
('000f0001-0000-0000-0000-000000000000', 'AGENT_VIEW', 'Visualizar agentes', 'RH', now(), now()),
|
||||
('000f0002-0000-0000-0000-000000000000', 'AGENT_CREATE', 'Criar agentes', 'RH', now(), now()),
|
||||
('000f0003-0000-0000-0000-000000000000', 'PAYROLL_PROCESS', 'Processar folha', 'RH', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- 24. AUDIT LOG
|
||||
-- ========================================================================
|
||||
INSERT INTO audit_log (id, user_id, username, module, entity, action, description, created_at) VALUES
|
||||
('00100001-0000-0000-0000-000000000000', v_user_admin, 'admin', 'RH', 'Agent', 'CREATE', 'Criacao de agente Amilcar Cabral Silva', now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
RAISE NOTICE '=== CARGA DE DADOS COMPLETA FINALIZADA ===';
|
||||
RAISE NOTICE 'Total de tabelas populadas: 24+';
|
||||
END $$;
|
||||
|
||||
-- ========================================================================
|
||||
-- VERIFICACAO FINAL
|
||||
-- ========================================================================
|
||||
SELECT 'MINISTERIOS' as tabela, COUNT(*)::text as total FROM ministry
|
||||
UNION ALL SELECT 'UNIDADES ORGANICAS', COUNT(*)::text FROM org_unit
|
||||
UNION ALL SELECT 'CARGOS', COUNT(*)::text FROM position
|
||||
UNION ALL SELECT 'BANCOS', COUNT(*)::text FROM bank
|
||||
UNION ALL SELECT 'ANOS FISCAIS', COUNT(*)::text FROM fiscal_year
|
||||
UNION ALL SELECT 'LINHAS ORCAMENTAIS', COUNT(*)::text FROM budget_line
|
||||
UNION ALL SELECT 'ALOCACOES ORCAMENTAIS', COUNT(*)::text FROM budget_allocation
|
||||
UNION ALL SELECT 'CATEGORIAS SALARIAIS', COUNT(*)::text FROM salary_category
|
||||
UNION ALL SELECT 'GRAUS SALARIAIS', COUNT(*)::text FROM salary_grade
|
||||
UNION ALL SELECT 'ESCALOES SALARIAIS', COUNT(*)::text FROM salary_step
|
||||
UNION ALL SELECT 'GRELHA SALARIAL', COUNT(*)::text FROM salary_grid
|
||||
UNION ALL SELECT 'TIPOS DE PROVENTOS', COUNT(*)::text FROM earning_type
|
||||
UNION ALL SELECT 'TIPOS DE DESCONTOS', COUNT(*)::text FROM deduction_type
|
||||
UNION ALL SELECT 'REGRAS GLOBAIS', COUNT(*)::text FROM global_deduction_rule
|
||||
UNION ALL SELECT 'ESCALOES IRPS', COUNT(*)::text FROM tax_bracket
|
||||
UNION ALL SELECT 'AGENTES', COUNT(*)::text FROM agents
|
||||
UNION ALL SELECT 'CONTAS BANCARIAS', COUNT(*)::text FROM agent_bank_account
|
||||
UNION ALL SELECT 'CONTRATOS', COUNT(*)::text FROM agent_contract
|
||||
UNION ALL SELECT 'HISTORICO STATUS', COUNT(*)::text FROM agent_status_history
|
||||
UNION ALL SELECT 'EVENTOS CARREIRA', COUNT(*)::text FROM career_events
|
||||
UNION ALL SELECT 'AVALIACOES', COUNT(*)::text FROM performance_evaluations
|
||||
UNION ALL SELECT 'PERIODOS FOLHA', COUNT(*)::text FROM payroll_period
|
||||
UNION ALL SELECT 'PROCESSAMENTOS FOLHA', COUNT(*)::text FROM payroll_run
|
||||
UNION ALL SELECT 'ITENS FOLHA', COUNT(*)::text FROM payroll_item
|
||||
UNION ALL SELECT 'ROLES', COUNT(*)::text FROM role
|
||||
UNION ALL SELECT 'USUARIOS', COUNT(*)::text FROM user_account
|
||||
UNION ALL SELECT 'USER_ROLES', COUNT(*)::text FROM user_role
|
||||
UNION ALL SELECT 'PERMISSOES', COUNT(*)::text FROM permissions
|
||||
UNION ALL SELECT 'AUDIT_LOG', COUNT(*)::text FROM audit_log
|
||||
ORDER BY tabela;
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Script Corrigido de Insercao de Dados de Teste
|
||||
|
||||
-- Inserir 2 ministerios adicionais
|
||||
INSERT INTO ministry (id, code, name, created_at, updated_at) VALUES
|
||||
('22222222-2222-2222-2222-222222222222', 'MIN-002', 'Ministerio da Saude Publica', now(), now()),
|
||||
('33333333-3333-3333-3333-333333333333', 'MIN-003', 'Ministerio da Educacao Nacional', now(), now());
|
||||
|
||||
-- Inserir unidades organicas para os novos ministerios
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at) VALUES
|
||||
('44444444-4444-4444-4444-444444444444', 'UO-001', 'Direcao-Geral do Tesouro', (SELECT id FROM ministry WHERE code = 'MIN-001'), NULL, now(), now()),
|
||||
('55555555-5555-5555-5555-555555555555', 'UO-002', 'Direcao-Geral do Orcamento', (SELECT id FROM ministry WHERE code = 'MIN-001'), NULL, now(), now()),
|
||||
('66666666-6666-6666-6666-666666666666', 'UO-003', 'Hospital Nacional Simao Mendes', '22222222-2222-2222-2222-222222222222', NULL, now(), now()),
|
||||
('77777777-7777-7777-7777-777777777777', 'UO-004', 'Escola Secundaria de Bissau', '33333333-3333-3333-3333-333333333333', NULL, now(), now());
|
||||
|
||||
-- Inserir cargos adicionais (SEM description)
|
||||
INSERT INTO position (id, code, title, created_at, updated_at) VALUES
|
||||
('88888888-8888-8888-8888-888888888888', 'CAR-005', 'Diretor-Geral', now(), now()),
|
||||
('99999999-9999-9999-9999-999999999999', 'CAR-006', 'Tecnico Superior', now(), now()),
|
||||
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'CAR-007', 'Medico Especialista', now(), now()),
|
||||
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'CAR-008', 'Professor', now(), now());
|
||||
|
||||
-- Verificar resultados
|
||||
SELECT 'MINISTERIOS' as tipo, COUNT(*)::text as total FROM ministry
|
||||
UNION ALL
|
||||
SELECT 'UNIDADES ORGANICAS', COUNT(*)::text FROM org_unit
|
||||
UNION ALL
|
||||
SELECT 'CARGOS', COUNT(*)::text FROM position
|
||||
UNION ALL
|
||||
SELECT 'BANCOS', COUNT(*)::text FROM bank
|
||||
UNION ALL
|
||||
SELECT 'AGENTES', COUNT(*)::text FROM agents;
|
||||
@@ -0,0 +1,186 @@
|
||||
-- ============================================
|
||||
-- SCRIPT COMPLETO DE DADOS DE TESTE - SIGEFP
|
||||
-- Baseado no mapeamento completo de entidades
|
||||
-- ============================================
|
||||
|
||||
-- IMPORTANTE: Este script usa os dados existentes do usuario e adiciona dados complementares
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
-- IDs existentes (do usuario)
|
||||
v_min_existente UUID;
|
||||
v_ou_sec UUID;
|
||||
v_ou_dir UUID;
|
||||
|
||||
-- IDs novos
|
||||
v_min_saude UUID;
|
||||
v_min_educacao UUID;
|
||||
v_ou_tesouro UUID;
|
||||
v_ou_orcamento UUID;
|
||||
v_ou_hospital UUID;
|
||||
v_ou_escola UUID;
|
||||
v_pos_diretor UUID;
|
||||
v_pos_tecnico UUID;
|
||||
v_pos_medico UUID;
|
||||
v_pos_professor UUID;
|
||||
|
||||
-- Estrutura Salarial
|
||||
v_cat_ts UUID;
|
||||
v_grade_a UUID;
|
||||
v_step_1 UUID;
|
||||
v_step_2 UUID;
|
||||
v_step_3 UUID;
|
||||
|
||||
-- Ano Fiscal
|
||||
v_fy_2025 UUID;
|
||||
BEGIN
|
||||
-- ============================================
|
||||
-- 1. OBTER DADOS EXISTENTES
|
||||
-- ============================================
|
||||
SELECT id INTO v_min_existente FROM ministry WHERE code = 'MIN-001';
|
||||
SELECT id INTO v_ou_sec FROM org_unit WHERE code = 'SEC-001';
|
||||
SELECT id INTO v_ou_dir FROM org_unit WHERE code = 'DIR-003';
|
||||
|
||||
RAISE NOTICE 'Ministerio existente: %', v_min_existente;
|
||||
|
||||
-- ============================================
|
||||
-- 2. INSERIR MINISTERIOS ADICIONAIS
|
||||
-- ============================================
|
||||
INSERT INTO ministry (id, code, name, is_active, created_at, updated_at)
|
||||
VALUES
|
||||
('22222222-2222-2222-2222-222222222222', 'MIN-002', 'Ministerio da Saude Publica', true, now(), now()),
|
||||
('33333333-3333-3333-3333-333333333333', 'MIN-003', 'Ministerio da Educacao Nacional', true, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_min_saude FROM ministry WHERE code = 'MIN-002';
|
||||
SELECT id INTO v_min_educacao FROM ministry WHERE code = 'MIN-003';
|
||||
|
||||
-- ============================================
|
||||
-- 3. INSERIR UNIDADES ORGANICAS
|
||||
-- IMPORTANTE: unit_type e OBRIGATORIO!
|
||||
-- ============================================
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, parent_unit_id, unit_type, is_active, created_at, updated_at)
|
||||
VALUES
|
||||
('44444444-4444-4444-4444-444444444444', 'UO-001', 'Direcao-Geral do Tesouro', v_min_existente, NULL, 'DIRECTORATE', true, now(), now()),
|
||||
('55555555-5555-5555-5555-555555555555', 'UO-002', 'Direcao-Geral do Orcamento', v_min_existente, NULL, 'DIRECTORATE', true, now(), now()),
|
||||
('66666666-6666-6666-6666-666666666666', 'UO-003', 'Hospital Nacional Simao Mendes', v_min_saude, NULL, 'HOSPITAL', true, now(), now()),
|
||||
('77777777-7777-7777-7777-777777777777', 'UO-004', 'Escola Secundaria de Bissau', v_min_educacao, NULL, 'SCHOOL', true, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_ou_tesouro FROM org_unit WHERE code = 'UO-001';
|
||||
SELECT id INTO v_ou_orcamento FROM org_unit WHERE code = 'UO-002';
|
||||
SELECT id INTO v_ou_hospital FROM org_unit WHERE code = 'UO-003';
|
||||
SELECT id INTO v_ou_escola FROM org_unit WHERE code = 'UO-004';
|
||||
|
||||
-- ============================================
|
||||
-- 4. INSERIR CARGOS (POSITIONS)
|
||||
-- IMPORTANTE: org_unit_id e OBRIGATORIO!
|
||||
-- ============================================
|
||||
INSERT INTO position (id, code, title, org_unit_id, is_active, created_at, updated_at)
|
||||
VALUES
|
||||
('88888888-8888-8888-8888-888888888888', 'POS-001', 'Diretor-Geral', v_ou_tesouro, true, now(), now()),
|
||||
('99999999-9999-9999-9999-999999999999', 'POS-002', 'Tecnico Superior', v_ou_orcamento, true, now(), now()),
|
||||
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'POS-003', 'Medico Especialista', v_ou_hospital, true, now(), now()),
|
||||
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'POS-004', 'Professor', v_ou_escola, true, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_pos_diretor FROM position WHERE code = 'POS-001';
|
||||
SELECT id INTO v_pos_tecnico FROM position WHERE code = 'POS-002';
|
||||
SELECT id INTO v_pos_medico FROM position WHERE code = 'POS-003';
|
||||
SELECT id INTO v_pos_professor FROM position WHERE code = 'POS-004';
|
||||
|
||||
-- ============================================
|
||||
-- 5. ESTRUTURA SALARIAL
|
||||
-- ============================================
|
||||
SELECT id INTO v_cat_ts FROM salary_category WHERE code = 'TS';
|
||||
SELECT id INTO v_grade_a FROM salary_grade WHERE code = 'A' AND category_id = v_cat_ts;
|
||||
SELECT id INTO v_step_1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 1;
|
||||
|
||||
-- Adicionar escaloes 2 e 3
|
||||
INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at)
|
||||
VALUES
|
||||
('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', v_grade_a, 2, now(), now()),
|
||||
('ffffffff-ffff-ffff-ffff-ffffffffffff', v_grade_a, 3, now(), now())
|
||||
ON CONFLICT (grade_id, step_number) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_step_2 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 2;
|
||||
SELECT id INTO v_step_3 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 3;
|
||||
|
||||
-- Valores da grelha salarial
|
||||
INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at)
|
||||
VALUES
|
||||
('10101010-1010-1010-1010-101010101010', v_step_2, 550000.00, '2024-01-01', now(), now()),
|
||||
('20202020-2020-2020-2020-202020202020', v_step_3, 600000.00, '2024-01-01', now(), now())
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- ============================================
|
||||
-- 6. ANO FISCAL
|
||||
-- ============================================
|
||||
SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
|
||||
|
||||
-- ============================================
|
||||
-- 7. AGENTES (usando UUIDs simples, nao FKs)
|
||||
-- ============================================
|
||||
INSERT INTO agents (
|
||||
id, matricula, nif, bi_number, full_name, birth_date, nationality,
|
||||
email, phone, address, hire_date, posse_date, appointment_type,
|
||||
functional_situation, literary_qualification, status,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
eligible_dependents_count, created_at, updated_at
|
||||
) VALUES
|
||||
('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', '2020/001', '100123456', 'BI123456', 'Amilcar Cabral Silva', '1975-03-15', 'Guineense',
|
||||
'amilcar.silva@minfin.gov.gw', '+245 955 123 456', 'Bairro de Penha, Bissau',
|
||||
'2020-01-15', '2020-02-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
v_ou_tesouro, v_pos_diretor, v_cat_ts, v_grade_a, v_step_3, 2, now(), now()),
|
||||
|
||||
('b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', '2021/045', '100234567', 'BI234567', 'Francisca Pereira Gomes', '1988-07-22', 'Guineense',
|
||||
'francisca.gomes@minfin.gov.gw', '+245 955 234 567', 'Bairro Militar, Bissau',
|
||||
'2021-03-10', '2021-04-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'MESTRADO', 'ACTIVE',
|
||||
v_ou_orcamento, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_2, 1, now(), now()),
|
||||
|
||||
('c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', '2019/089', '100345678', 'BI345678', 'Dr. Joao Vieira Mendes', '1982-11-30', 'Guineense',
|
||||
'joao.mendes@minsaude.gov.gw', '+245 955 345 678', 'Bairro de Antula, Bissau',
|
||||
'2019-06-01', '2019-07-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'DOUTORAMENTO', 'ACTIVE',
|
||||
v_ou_hospital, v_pos_medico, v_cat_ts, v_grade_a, v_step_3, 3, now(), now()),
|
||||
|
||||
('d4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', '2022/112', '100456789', 'BI456789', 'Maria da Luz Correia', '1990-05-18', 'Guineense',
|
||||
'maria.correia@minedu.gov.gw', '+245 955 456 789', 'Bairro de Quelele, Bissau',
|
||||
'2022-09-01', '2022-10-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
v_ou_escola, v_pos_professor, v_cat_ts, v_grade_a, v_step_1, 0, now(), now()),
|
||||
|
||||
('e5e5e5e5-e5e5-e5e5-e5e5-e5e5e5e5e5e5', '2024/201', '100567890', 'BI567890', 'Samba Djalo', '1995-09-12', 'Guineense',
|
||||
'samba.djalo@minfin.gov.gw', '+245 955 567 890', 'Bairro de Chao de Papel, Bissau',
|
||||
'2024-11-01', '2024-12-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
v_ou_tesouro, v_pos_tecnico, v_cat_ts, v_grade_a, v_step_1, 0, now(), now())
|
||||
ON CONFLICT (matricula) DO NOTHING;
|
||||
|
||||
-- ============================================
|
||||
-- 8. LINHAS ORCAMENTAIS
|
||||
-- ============================================
|
||||
INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
|
||||
VALUES
|
||||
('f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1f1', v_fy_2025, '2025-MINFIN-311100', 'Vencimentos Base - Financas', v_min_existente, v_ou_tesouro, '311100', now(), now()),
|
||||
('f2f2f2f2-f2f2-f2f2-f2f2-f2f2f2f2f2f2', v_fy_2025, '2025-MINSAUDE-311100', 'Vencimentos Base - Saude', v_min_saude, v_ou_hospital, '311100', now(), now()),
|
||||
('f3f3f3f3-f3f3-f3f3-f3f3-f3f3f3f3f3f3', v_fy_2025, '2025-MINEDU-311100', 'Vencimentos Base - Educacao', v_min_educacao, v_ou_escola, '311100', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
RAISE NOTICE '=== DADOS DE TESTE INSERIDOS COM SUCESSO ===';
|
||||
RAISE NOTICE 'Ministerios adicionados: 2';
|
||||
RAISE NOTICE 'Unidades Organicas adicionadas: 4';
|
||||
RAISE NOTICE 'Cargos adicionados: 4';
|
||||
RAISE NOTICE 'Agentes adicionados: 5';
|
||||
RAISE NOTICE 'Linhas Orcamentais adicionadas: 3';
|
||||
END $$;
|
||||
|
||||
-- Verificar resultados finais
|
||||
SELECT 'MINISTERIOS' as tipo, COUNT(*)::text as total FROM ministry
|
||||
UNION ALL
|
||||
SELECT 'UNIDADES ORGANICAS', COUNT(*)::text FROM org_unit
|
||||
UNION ALL
|
||||
SELECT 'CARGOS', COUNT(*)::text FROM position
|
||||
UNION ALL
|
||||
SELECT 'BANCOS', COUNT(*)::text FROM bank
|
||||
UNION ALL
|
||||
SELECT 'AGENTES', COUNT(*)::text FROM agents
|
||||
UNION ALL
|
||||
SELECT 'LINHAS ORCAMENTAIS', COUNT(*)::text FROM budget_line;
|
||||
@@ -0,0 +1,92 @@
|
||||
-- Script Final Corrigido - Usa IDs reais do banco
|
||||
-- Insere dados faltantes em todas as tabelas
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
v_min_001 UUID := '6e32517f-5dbc-416a-9632-d920175b8cdd'; -- ID real do MIN-001
|
||||
v_min_002 UUID;
|
||||
v_min_003 UUID;
|
||||
v_ou_001 UUID;
|
||||
v_ou_002 UUID;
|
||||
v_ou_003 UUID;
|
||||
v_ou_004 UUID;
|
||||
v_pos_001 UUID;
|
||||
v_pos_002 UUID;
|
||||
v_pos_003 UUID;
|
||||
v_pos_004 UUID;
|
||||
BEGIN
|
||||
-- Inserir ministerios
|
||||
INSERT INTO ministry (id, code, name, acronym, is_active, created_at, updated_at) VALUES
|
||||
('22222222-2222-2222-2222-222222222222', 'MIN-002', 'Ministerio da Saude Publica', 'MINSAUDE', true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id INTO v_min_002;
|
||||
|
||||
IF v_min_002 IS NULL THEN SELECT id INTO v_min_002 FROM ministry WHERE code = 'MIN-002'; END IF;
|
||||
|
||||
INSERT INTO ministry (id, code, name, acronym, is_active, created_at, updated_at) VALUES
|
||||
('33333333-3333-3333-3333-333333333333', 'MIN-003', 'Ministerio da Educacao Nacional', 'MINEDU', true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id INTO v_min_003;
|
||||
|
||||
IF v_min_003 IS NULL THEN SELECT id INTO v_min_003 FROM ministry WHERE code = 'MIN-003'; END IF;
|
||||
|
||||
RAISE NOTICE 'Ministerios: MIN-001=%, MIN-002=%, MIN-003=%', v_min_001, v_min_002, v_min_003;
|
||||
|
||||
-- Inserir unidades organicas
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, unit_type, is_active, created_at, updated_at) VALUES
|
||||
('44444444-4444-4444-4444-444444444444', 'UO-001', 'Direcao-Geral do Tesouro', v_min_001, 'DIRECTORATE', true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id INTO v_ou_001;
|
||||
|
||||
IF v_ou_001 IS NULL THEN SELECT id INTO v_ou_001 FROM org_unit WHERE code = 'UO-001'; END IF;
|
||||
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, unit_type, is_active, created_at, updated_at) VALUES
|
||||
('55555555-5555-5555-5555-555555555555', 'UO-002', 'Direcao-Geral do Orcamento', v_min_001, 'DIRECTORATE', true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id INTO v_ou_002;
|
||||
|
||||
IF v_ou_002 IS NULL THEN SELECT id INTO v_ou_002 FROM org_unit WHERE code = 'UO-002'; END IF;
|
||||
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, unit_type, is_active, created_at, updated_at) VALUES
|
||||
('66666666-6666-6666-6666-666666666666', 'UO-003', 'Hospital Nacional Simao Mendes', v_min_002, 'HOSPITAL', true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id INTO v_ou_003;
|
||||
|
||||
IF v_ou_003 IS NULL THEN SELECT id INTO v_ou_003 FROM org_unit WHERE code = 'UO-003'; END IF;
|
||||
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, unit_type, is_active, created_at, updated_at) VALUES
|
||||
('77777777-7777-7777-7777-777777777777', 'UO-004', 'Escola Secundaria de Bissau', v_min_003, 'SCHOOL', true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET name = EXCLUDED.name
|
||||
RETURNING id INTO v_ou_004;
|
||||
|
||||
IF v_ou_004 IS NULL THEN SELECT id INTO v_ou_004 FROM org_unit WHERE code = 'UO-004'; END IF;
|
||||
|
||||
RAISE NOTICE 'Unidades Organicas criadas: %, %, %, %', v_ou_001, v_ou_002, v_ou_003, v_ou_004;
|
||||
|
||||
-- Inserir cargos
|
||||
INSERT INTO position (id, code, title, org_unit_id, is_active, created_at, updated_at) VALUES
|
||||
('88888888-8888-8888-8888-888888888888', 'POS-001', 'Diretor-Geral', v_ou_001, true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET title = EXCLUDED.title;
|
||||
|
||||
INSERT INTO position (id, code, title, org_unit_id, is_active, created_at, updated_at) VALUES
|
||||
('99999999-9999-9999-9999-999999999999', 'POS-002', 'Tecnico Superior', v_ou_002, true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET title = EXCLUDED.title;
|
||||
|
||||
INSERT INTO position (id, code, title, org_unit_id, is_active, created_at, updated_at) VALUES
|
||||
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'POS-003', 'Medico Especialista', v_ou_003, true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET title = EXCLUDED.title;
|
||||
|
||||
INSERT INTO position (id, code, title, org_unit_id, is_active, created_at, updated_at) VALUES
|
||||
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'POS-004', 'Professor', v_ou_004, true, now(), now())
|
||||
ON CONFLICT (code) DO UPDATE SET title = EXCLUDED.title;
|
||||
|
||||
RAISE NOTICE 'Cargos criados com sucesso';
|
||||
RAISE NOTICE '=== DADOS INSERIDOS COM SUCESSO ===';
|
||||
END $$;
|
||||
|
||||
-- Verificar
|
||||
SELECT 'MINISTERIOS' as tabela, COUNT(*)::text FROM ministry
|
||||
UNION ALL SELECT 'UNIDADES ORGANICAS', COUNT(*)::text FROM org_unit
|
||||
UNION ALL SELECT 'CARGOS', COUNT(*)::text FROM position
|
||||
UNION ALL SELECT 'AGENTES', COUNT(*)::text FROM agents
|
||||
UNION ALL SELECT 'BANCOS', COUNT(*)::text FROM bank;
|
||||
@@ -0,0 +1,368 @@
|
||||
-- ============================================================================
|
||||
-- SCRIPT COMPLEMENTAR DE DADOS PARA TESTES FUNCIONAIS COMPLETOS
|
||||
-- Adiciona dados necessários para testar fluxos completos do sistema
|
||||
-- ============================================================================
|
||||
--
|
||||
-- Este script complementa insert_all_test_data.sql adicionando:
|
||||
-- - Períodos de folha adicionais
|
||||
-- - Execuções de folha completas (COMPLETED)
|
||||
-- - Itens de folha completos com todos os cálculos
|
||||
-- - Execuções orçamentárias (COMMITMENT, LIQUIDATION, PAYMENT)
|
||||
-- - Lotes de pagamento
|
||||
-- - Ordens de pagamento
|
||||
-- - Confirmações de pagamento do tesouro
|
||||
-- - Dados para testar fluxos end-to-end
|
||||
--
|
||||
-- IMPORTANTE: Execute insert_all_test_data.sql primeiro!
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
-- IDs existentes
|
||||
v_min_financas UUID;
|
||||
v_min_saude UUID;
|
||||
v_min_educacao UUID;
|
||||
v_ou_tesouro UUID;
|
||||
v_ou_orcamento UUID;
|
||||
v_ou_hospital UUID;
|
||||
v_ou_escola UUID;
|
||||
|
||||
-- Agentes
|
||||
v_agent_amilcar UUID;
|
||||
v_agent_francisca UUID;
|
||||
v_agent_joao UUID;
|
||||
v_agent_maria UUID;
|
||||
v_agent_samba UUID;
|
||||
|
||||
-- Ano Fiscal e Linhas Orçamentais
|
||||
v_fy_2025 UUID;
|
||||
v_bl_financas UUID;
|
||||
v_bl_saude UUID;
|
||||
v_bl_educacao UUID;
|
||||
|
||||
-- Tipos de Proventos e Descontos
|
||||
v_earning_vencimento UUID;
|
||||
v_earning_abono UUID;
|
||||
v_deduction_inps UUID;
|
||||
v_deduction_irps UUID;
|
||||
v_deduction_selo UUID;
|
||||
|
||||
-- Contas Bancárias
|
||||
v_account_amilcar UUID;
|
||||
v_account_francisca UUID;
|
||||
v_account_joao UUID;
|
||||
v_account_maria UUID;
|
||||
v_account_samba UUID;
|
||||
|
||||
-- Períodos de Folha
|
||||
v_period_jan2025 UUID;
|
||||
v_period_fev2025 UUID;
|
||||
v_period_mar2025 UUID;
|
||||
|
||||
-- Execuções de Folha
|
||||
v_payroll_run_jan_completed UUID;
|
||||
v_payroll_run_fev_completed UUID;
|
||||
v_payroll_run_mar_pending UUID;
|
||||
|
||||
-- Lotes de Pagamento
|
||||
v_batch_jan UUID;
|
||||
v_batch_fev UUID;
|
||||
|
||||
-- Usuário Admin
|
||||
v_user_admin UUID;
|
||||
|
||||
BEGIN
|
||||
RAISE NOTICE '=== INICIANDO CARGA DE DADOS PARA TESTES FUNCIONAIS ===';
|
||||
|
||||
-- ========================================================================
|
||||
-- OBTER IDs EXISTENTES
|
||||
-- ========================================================================
|
||||
SELECT id INTO v_min_financas FROM ministry WHERE code = 'MIN-001';
|
||||
SELECT id INTO v_min_saude FROM ministry WHERE code = 'MIN-002';
|
||||
SELECT id INTO v_min_educacao FROM ministry WHERE code = 'MIN-003';
|
||||
|
||||
SELECT id INTO v_ou_tesouro FROM org_unit WHERE code = 'UO-001';
|
||||
SELECT id INTO v_ou_orcamento FROM org_unit WHERE code = 'UO-002';
|
||||
SELECT id INTO v_ou_hospital FROM org_unit WHERE code = 'UO-003';
|
||||
SELECT id INTO v_ou_escola FROM org_unit WHERE code = 'UO-004';
|
||||
|
||||
SELECT id INTO v_agent_amilcar FROM agents WHERE matricula = '2020/001';
|
||||
SELECT id INTO v_agent_francisca FROM agents WHERE matricula = '2021/045';
|
||||
SELECT id INTO v_agent_joao FROM agents WHERE matricula = '2019/089';
|
||||
SELECT id INTO v_agent_maria FROM agents WHERE matricula = '2022/112';
|
||||
SELECT id INTO v_agent_samba FROM agents WHERE matricula = '2024/201';
|
||||
|
||||
SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
|
||||
|
||||
SELECT id INTO v_bl_financas FROM budget_line WHERE code = '2025-MINFIN-311100';
|
||||
SELECT id INTO v_bl_saude FROM budget_line WHERE code = '2025-MINSAUDE-311100';
|
||||
SELECT id INTO v_bl_educacao FROM budget_line WHERE code = '2025-MINEDU-311100';
|
||||
|
||||
SELECT id INTO v_earning_vencimento FROM earning_type WHERE code = 'VENC-BASE';
|
||||
SELECT id INTO v_earning_abono FROM earning_type WHERE code = 'ABONO-FAM';
|
||||
SELECT id INTO v_deduction_inps FROM deduction_type WHERE code = 'INPS';
|
||||
SELECT id INTO v_deduction_irps FROM deduction_type WHERE code = 'IRPS';
|
||||
SELECT id INTO v_deduction_selo FROM deduction_type WHERE code = 'SELO';
|
||||
|
||||
SELECT id INTO v_account_amilcar FROM agent_bank_account WHERE agent_id = v_agent_amilcar AND is_primary = true;
|
||||
SELECT id INTO v_account_francisca FROM agent_bank_account WHERE agent_id = v_agent_francisca AND is_primary = true;
|
||||
SELECT id INTO v_account_joao FROM agent_bank_account WHERE agent_id = v_agent_joao AND is_primary = true;
|
||||
|
||||
SELECT id INTO v_user_admin FROM user_account WHERE username = 'admin';
|
||||
|
||||
-- Criar contas bancárias para agentes que não têm
|
||||
IF v_account_maria IS NULL THEN
|
||||
INSERT INTO agent_bank_account (id, agent_id, bank, account_number, branch_code, is_primary, created_at, updated_at)
|
||||
VALUES ('00110001-0000-0000-0000-000000000000', v_agent_maria, 'BCEAO', '4567890123', '004', true, now(), now())
|
||||
RETURNING id INTO v_account_maria;
|
||||
END IF;
|
||||
|
||||
IF v_account_samba IS NULL THEN
|
||||
INSERT INTO agent_bank_account (id, agent_id, bank, account_number, branch_code, is_primary, created_at, updated_at)
|
||||
VALUES ('00110002-0000-0000-0000-000000000000', v_agent_samba, 'BRS', '5678901234', '005', true, now(), now())
|
||||
RETURNING id INTO v_account_samba;
|
||||
END IF;
|
||||
|
||||
-- ========================================================================
|
||||
-- PERÍODOS DE FOLHA ADICIONAIS
|
||||
-- ========================================================================
|
||||
INSERT INTO payroll_period (id, fiscal_year, month, start_date, end_date, status, created_at, updated_at) VALUES
|
||||
('00120001-0000-0000-0000-000000000000', 2025, 2, '2025-02-01', '2025-02-28', 'OPEN', now(), now()),
|
||||
('00120002-0000-0000-0000-000000000000', 2025, 3, '2025-03-01', '2025-03-31', 'OPEN', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_period_jan2025 FROM payroll_period WHERE fiscal_year = 2025 AND month = 1;
|
||||
SELECT id INTO v_period_fev2025 FROM payroll_period WHERE fiscal_year = 2025 AND month = 2;
|
||||
SELECT id INTO v_period_mar2025 FROM payroll_period WHERE fiscal_year = 2025 AND month = 3;
|
||||
|
||||
-- ========================================================================
|
||||
-- EXECUÇÕES DE FOLHA COMPLETAS
|
||||
-- ========================================================================
|
||||
-- Janeiro - COMPLETED (para gerar ordens de pagamento)
|
||||
INSERT INTO payroll_run (id, period_id, ministry_id, org_unit_id, run_type, status, created_at, updated_at, created_by) VALUES
|
||||
('00130001-0000-0000-0000-000000000000', v_period_jan2025, v_min_financas, v_ou_tesouro, 'REGULAR', 'COMPLETED', now(), now(), v_user_admin)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_payroll_run_jan_completed FROM payroll_run WHERE id = '00130001-0000-0000-0000-000000000000';
|
||||
|
||||
-- Fevereiro - COMPLETED
|
||||
INSERT INTO payroll_run (id, period_id, ministry_id, org_unit_id, run_type, status, created_at, updated_at, created_by) VALUES
|
||||
('00130002-0000-0000-0000-000000000000', v_period_fev2025, v_min_financas, v_ou_tesouro, 'REGULAR', 'COMPLETED', now(), now(), v_user_admin)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_payroll_run_fev_completed FROM payroll_run WHERE id = '00130002-0000-0000-0000-000000000000';
|
||||
|
||||
-- Março - PENDING (para testar validações)
|
||||
INSERT INTO payroll_run (id, period_id, ministry_id, org_unit_id, run_type, status, created_at, updated_at, created_by) VALUES
|
||||
('00130003-0000-0000-0000-000000000000', v_period_mar2025, v_min_financas, v_ou_tesouro, 'REGULAR', 'PENDING', now(), now(), v_user_admin)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_payroll_run_mar_pending FROM payroll_run WHERE id = '00130003-0000-0000-0000-000000000000';
|
||||
|
||||
-- ========================================================================
|
||||
-- ITENS DE FOLHA COMPLETOS (Janeiro - COMPLETED)
|
||||
-- Com todos os cálculos: Vencimento, Abono, INPS, IRPS, Selo
|
||||
-- ========================================================================
|
||||
-- Amilcar Cabral - Vencimento Base: 600.000
|
||||
INSERT INTO payroll_item (
|
||||
id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
|
||||
description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
|
||||
) VALUES
|
||||
-- Vencimento Base
|
||||
('00140001-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'EARNING', v_earning_vencimento, NULL,
|
||||
'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_financas, now(), now()),
|
||||
-- Abono de Família (2 dependentes)
|
||||
('00140002-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'EARNING', v_earning_abono, NULL,
|
||||
'Abono de Família (2 dep.)', 2000.00, 2.00, 4000.00, v_bl_financas, now(), now()),
|
||||
-- INPS 7% sobre 604.000 = 42.280
|
||||
('00140003-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_inps,
|
||||
'INPS 7%', 42280.00, 1.00, 42280.00, NULL, now(), now()),
|
||||
-- Selo 0.3% sobre 604.000 = 1.812
|
||||
('00140004-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_selo,
|
||||
'Imposto de Selo 0.3%', 1812.00, 1.00, 1812.00, NULL, now(), now()),
|
||||
-- IRPS: Base = 604.000 - 42.280 = 561.720
|
||||
-- Faixa 50001-150000: (561.720 - 50.000) * 10% - 5.000 = 51.172 - 5.000 = 46.172
|
||||
('00140005-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_irps,
|
||||
'IRPS', 46172.00, 1.00, 46172.00, NULL, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Francisca Pereira - Vencimento Base: 550.000
|
||||
INSERT INTO payroll_item (
|
||||
id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
|
||||
description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
|
||||
) VALUES
|
||||
-- Vencimento Base
|
||||
('00140006-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'EARNING', v_earning_vencimento, NULL,
|
||||
'Vencimento Base', 550000.00, 1.00, 550000.00, v_bl_financas, now(), now()),
|
||||
-- Abono de Família (1 dependente)
|
||||
('00140007-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'EARNING', v_earning_abono, NULL,
|
||||
'Abono de Família (1 dep.)', 2000.00, 1.00, 2000.00, v_bl_financas, now(), now()),
|
||||
-- INPS 7% sobre 552.000 = 38.640
|
||||
('00140008-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'DEDUCTION', NULL, v_deduction_inps,
|
||||
'INPS 7%', 38640.00, 1.00, 38640.00, NULL, now(), now()),
|
||||
-- Selo 0.3% sobre 552.000 = 1.656
|
||||
('00140009-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'DEDUCTION', NULL, v_deduction_selo,
|
||||
'Imposto de Selo 0.3%', 1656.00, 1.00, 1656.00, NULL, now(), now()),
|
||||
-- IRPS: Base = 552.000 - 38.640 = 513.360
|
||||
-- Faixa 50001-150000: (513.360 - 50.000) * 10% - 5.000 = 46.336 - 5.000 = 41.336
|
||||
('0014000a-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_francisca, 'DEDUCTION', NULL, v_deduction_irps,
|
||||
'IRPS', 41336.00, 1.00, 41336.00, NULL, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- João Vieira - Vencimento Base: 600.000 (Saúde)
|
||||
INSERT INTO payroll_item (
|
||||
id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
|
||||
description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
|
||||
) VALUES
|
||||
('0014000b-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'EARNING', v_earning_vencimento, NULL,
|
||||
'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_saude, now(), now()),
|
||||
('0014000c-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'EARNING', v_earning_abono, NULL,
|
||||
'Abono de Família (3 dep.)', 2000.00, 3.00, 6000.00, v_bl_saude, now(), now()),
|
||||
('0014000d-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'DEDUCTION', NULL, v_deduction_inps,
|
||||
'INPS 7%', 42420.00, 1.00, 42420.00, NULL, now(), now()),
|
||||
('0014000e-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'DEDUCTION', NULL, v_deduction_selo,
|
||||
'Imposto de Selo 0.3%', 1818.00, 1.00, 1818.00, NULL, now(), now()),
|
||||
('0014000f-0000-0000-0000-000000000000', v_payroll_run_jan_completed, v_agent_joao, 'DEDUCTION', NULL, v_deduction_irps,
|
||||
'IRPS', 46178.00, 1.00, 46178.00, NULL, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- EXECUÇÕES ORÇAMENTÁRIAS (Budget Execution)
|
||||
-- COMMITMENT: Compromisso quando a folha é gerada
|
||||
-- LIQUIDATION: Liquidação quando a folha é processada
|
||||
-- PAYMENT: Pagamento quando o tesouro confirma
|
||||
-- ========================================================================
|
||||
-- COMMITMENT - Janeiro (compromisso inicial)
|
||||
INSERT INTO budget_execution (
|
||||
id, budget_line_id, period_id, movement_type, amount, source_module, reference_id, created_at, updated_at
|
||||
) VALUES
|
||||
('00150001-0000-0000-0000-000000000000', v_bl_financas, 202501, 'COMMITMENT', 1156000.00, 'RH', v_payroll_run_jan_completed, now(), now()),
|
||||
('00150002-0000-0000-0000-000000000000', v_bl_saude, 202501, 'COMMITMENT', 606000.00, 'RH', v_payroll_run_jan_completed, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- LIQUIDATION - Janeiro (liquidação após processamento)
|
||||
INSERT INTO budget_execution (
|
||||
id, budget_line_id, period_id, movement_type, amount, source_module, reference_id, created_at, updated_at
|
||||
) VALUES
|
||||
('00150003-0000-0000-0000-000000000000', v_bl_financas, 202501, 'LIQUIDATION', 1156000.00, 'RH', v_payroll_run_jan_completed, now(), now()),
|
||||
('00150004-0000-0000-0000-000000000000', v_bl_saude, 202501, 'LIQUIDATION', 606000.00, 'RH', v_payroll_run_jan_completed, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- LOTES DE PAGAMENTO (Payment Batch)
|
||||
-- ========================================================================
|
||||
INSERT INTO payment_batch (
|
||||
id, period_id, ministry_id, status, created_at, updated_at, created_by
|
||||
) VALUES
|
||||
('00160001-0000-0000-0000-000000000000', 202501, v_min_financas, 'CREATED', now(), now(), v_user_admin),
|
||||
('00160002-0000-0000-0000-000000000000', 202502, v_min_financas, 'SENT_TO_BANK', now(), now(), v_user_admin)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
SELECT id INTO v_batch_jan FROM payment_batch WHERE id = '00160001-0000-0000-0000-000000000000';
|
||||
SELECT id INTO v_batch_fev FROM payment_batch WHERE id = '00160002-0000-0000-0000-000000000000';
|
||||
|
||||
-- ========================================================================
|
||||
-- ORDENS DE PAGAMENTO (Payment Order)
|
||||
-- Geradas a partir da folha de Janeiro
|
||||
-- ========================================================================
|
||||
-- Amilcar: Bruto = 604.000, Líquido = 604.000 - 42.280 - 1.812 - 46.172 = 513.736
|
||||
-- NOTA: payroll_run_id é bigint no schema mas UUID na entidade Java - usando NULL por enquanto
|
||||
INSERT INTO payment_order (
|
||||
id, payment_batch_id, payroll_run_id, agent_id, bank_account_id, budget_line_id,
|
||||
gross_amount, net_amount, status, created_at, updated_at
|
||||
) VALUES
|
||||
('00170001-0000-0000-0000-000000000000', v_batch_jan, NULL, v_agent_amilcar, v_account_amilcar, v_bl_financas,
|
||||
604000.00, 513736.00, 'CREATED', now(), now()),
|
||||
-- Francisca: Bruto = 552.000, Líquido = 552.000 - 38.640 - 1.656 - 41.336 = 470.368
|
||||
('00170002-0000-0000-0000-000000000000', v_batch_jan, NULL, v_agent_francisca, v_account_francisca, v_bl_financas,
|
||||
552000.00, 470368.00, 'CREATED', now(), now()),
|
||||
-- João: Bruto = 606.000, Líquido = 606.000 - 42.420 - 1.818 - 46.178 = 515.584
|
||||
('00170003-0000-0000-0000-000000000000', v_batch_jan, NULL, v_agent_joao, v_account_joao, v_bl_saude,
|
||||
606000.00, 515584.00, 'SENT_TO_BANK', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- CONFIRMAÇÕES DE PAGAMENTO DO TESOURO (Treasury Payment)
|
||||
-- ========================================================================
|
||||
INSERT INTO treasury_payment (
|
||||
id, payment_order_id, paid_at, transaction_ref, status, message, created_at, updated_at
|
||||
) VALUES
|
||||
-- Amilcar - Pago
|
||||
('00180001-0000-0000-0000-000000000000', '00170001-0000-0000-0000-000000000000', '2025-01-15 10:30:00', 'TXN-2025-001-001', 'PAID', 'Pagamento confirmado pelo banco', now(), now()),
|
||||
-- Francisca - Pendente
|
||||
('00180002-0000-0000-0000-000000000000', '00170002-0000-0000-0000-000000000000', NULL, NULL, 'PENDING', NULL, now(), now()),
|
||||
-- João - Pago
|
||||
('00180003-0000-0000-0000-000000000000', '00170003-0000-0000-0000-000000000000', '2025-01-15 11:15:00', 'TXN-2025-001-003', 'PAID', 'Pagamento confirmado pelo banco', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- EXECUÇÕES ORÇAMENTÁRIAS - PAYMENT (após confirmação do tesouro)
|
||||
-- ========================================================================
|
||||
INSERT INTO budget_execution (
|
||||
id, budget_line_id, period_id, movement_type, amount, source_module, reference_id, created_at, updated_at
|
||||
) VALUES
|
||||
-- Pagamentos confirmados
|
||||
('00150005-0000-0000-0000-000000000000', v_bl_financas, 202501, 'PAYMENT', 513736.00, 'TREASURY', '00170001-0000-0000-0000-000000000000', now(), now()),
|
||||
('00150006-0000-0000-0000-000000000000', v_bl_saude, 202501, 'PAYMENT', 515584.00, 'TREASURY', '00170003-0000-0000-0000-000000000000', now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- ========================================================================
|
||||
-- ITENS DE FOLHA PARA FEVEREIRO (para testar múltiplos períodos)
|
||||
-- ========================================================================
|
||||
INSERT INTO payroll_item (
|
||||
id, payroll_run_id, agent_id, line_type, earning_type_id, deduction_type_id,
|
||||
description, unit_amount, quantity, total_amount, budget_line_id, created_at, updated_at
|
||||
) VALUES
|
||||
-- Amilcar - Fevereiro
|
||||
('00140010-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'EARNING', v_earning_vencimento, NULL,
|
||||
'Vencimento Base', 600000.00, 1.00, 600000.00, v_bl_financas, now(), now()),
|
||||
('00140011-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'EARNING', v_earning_abono, NULL,
|
||||
'Abono de Família (2 dep.)', 2000.00, 2.00, 4000.00, v_bl_financas, now(), now()),
|
||||
('00140012-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_inps,
|
||||
'INPS 7%', 42280.00, 1.00, 42280.00, NULL, now(), now()),
|
||||
('00140013-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_selo,
|
||||
'Imposto de Selo 0.3%', 1812.00, 1.00, 1812.00, NULL, now(), now()),
|
||||
('00140014-0000-0000-0000-000000000000', v_payroll_run_fev_completed, v_agent_amilcar, 'DEDUCTION', NULL, v_deduction_irps,
|
||||
'IRPS', 46172.00, 1.00, 46172.00, NULL, now(), now())
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
RAISE NOTICE '=== DADOS PARA TESTES FUNCIONAIS INSERIDOS COM SUCESSO ===';
|
||||
RAISE NOTICE 'Períodos de folha adicionados: 2';
|
||||
RAISE NOTICE 'Execuções de folha criadas: 3';
|
||||
RAISE NOTICE 'Itens de folha completos: 15+';
|
||||
RAISE NOTICE 'Execuções orçamentárias: 6';
|
||||
RAISE NOTICE 'Lotes de pagamento: 2';
|
||||
RAISE NOTICE 'Ordens de pagamento: 3';
|
||||
RAISE NOTICE 'Confirmações de pagamento: 3';
|
||||
|
||||
END $$;
|
||||
|
||||
-- ========================================================================
|
||||
-- VERIFICAÇÃO FINAL DOS DADOS INSERIDOS
|
||||
-- ========================================================================
|
||||
SELECT 'PERIODOS FOLHA' as tipo, COUNT(*)::text as total FROM payroll_period WHERE fiscal_year = 2025
|
||||
UNION ALL
|
||||
SELECT 'EXECUCOES FOLHA', COUNT(*)::text FROM payroll_run WHERE period_id IN (
|
||||
SELECT id FROM payroll_period WHERE fiscal_year = 2025
|
||||
)
|
||||
UNION ALL
|
||||
SELECT 'ITENS FOLHA', COUNT(*)::text FROM payroll_item WHERE payroll_run_id IN (
|
||||
SELECT id FROM payroll_run WHERE period_id IN (
|
||||
SELECT id FROM payroll_period WHERE fiscal_year = 2025
|
||||
)
|
||||
)
|
||||
UNION ALL
|
||||
SELECT 'EXECUCOES ORCAMENTARIAS', COUNT(*)::text FROM budget_execution WHERE period_id >= 202501
|
||||
UNION ALL
|
||||
SELECT 'LOTES PAGAMENTO', COUNT(*)::text FROM payment_batch WHERE period_id >= 202501
|
||||
UNION ALL
|
||||
SELECT 'ORDENS PAGAMENTO', COUNT(*)::text FROM payment_order WHERE payment_batch_id IN (
|
||||
SELECT id FROM payment_batch WHERE period_id >= 202501
|
||||
)
|
||||
UNION ALL
|
||||
SELECT 'CONFIRMACOES TESOURO', COUNT(*)::text FROM treasury_payment WHERE payment_order_id IN (
|
||||
SELECT id FROM payment_order WHERE payment_batch_id IN (
|
||||
SELECT id FROM payment_batch WHERE period_id >= 202501
|
||||
)
|
||||
)
|
||||
ORDER BY tipo;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
-- IDs de Dedução baseados nos códigos criados pelo Initializer
|
||||
DO $$
|
||||
DECLARE
|
||||
v_irps_id UUID;
|
||||
v_inps_id UUID;
|
||||
v_selo_id UUID;
|
||||
BEGIN
|
||||
-- Obter IDs
|
||||
SELECT id INTO v_irps_id FROM deduction_type WHERE code = 'IRPS';
|
||||
SELECT id INTO v_inps_id FROM deduction_type WHERE code = 'INPS';
|
||||
SELECT id INTO v_selo_id FROM deduction_type WHERE code = 'SELO';
|
||||
|
||||
-- 1. Regras Globais (Se não existirem)
|
||||
IF v_inps_id IS NOT NULL THEN
|
||||
INSERT INTO global_deduction_rule (id, deduction_type_id, percentage, valid_from, active, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), v_inps_id, 0.07, '2024-01-01', true, now(), now())
|
||||
ON CONFLICT DO NOTHING;
|
||||
END IF;
|
||||
|
||||
IF v_selo_id IS NOT NULL THEN
|
||||
INSERT INTO global_deduction_rule (id, deduction_type_id, percentage, valid_from, active, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), v_selo_id, 0.003, '2024-01-01', true, now(), now())
|
||||
ON CONFLICT DO NOTHING;
|
||||
END IF;
|
||||
|
||||
-- 2. Escalões de IRPS
|
||||
IF v_irps_id IS NOT NULL THEN
|
||||
-- Limpar escalões antigos para garantir a nova tabela
|
||||
DELETE FROM tax_bracket WHERE deduction_type_id = v_irps_id;
|
||||
|
||||
-- Faixa 1: Isento (0 - 50.000)
|
||||
INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), v_irps_id, 0, 50000, 0, 0, '2024-01-01', now(), now());
|
||||
|
||||
-- Faixa 2: 10% (50.001 - 150.000)
|
||||
INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), v_irps_id, 50001, 150000, 0.10, 5000, '2024-01-01', now(), now());
|
||||
|
||||
-- Faixa 3: 15% (150.001 - 250.000)
|
||||
INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), v_irps_id, 150001, 250000, 0.15, 12500, '2024-01-01', now(), now());
|
||||
|
||||
-- Faixa 4: 20% (250.001 - 500.000)
|
||||
INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), v_irps_id, 250001, 500000, 0.20, 25000, '2024-01-01', now(), now());
|
||||
|
||||
-- Faixa 5: 25% (Acima de 500.000)
|
||||
INSERT INTO tax_bracket (id, deduction_type_id, lower_limit, upper_limit, rate_percentage, excess_deduction, valid_from, created_at, updated_at)
|
||||
VALUES (gen_random_uuid(), v_irps_id, 500001, NULL, 0.25, 50000, '2024-01-01', now(), now());
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -0,0 +1,220 @@
|
||||
-- Script Complementar de Dados de Teste
|
||||
-- Usa o ministerio existente e adiciona dados adicionais
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
v_min_financas UUID;
|
||||
v_min_saude UUID;
|
||||
v_min_educacao UUID;
|
||||
v_cat_ts UUID;
|
||||
v_grade_a UUID;
|
||||
v_step_1 UUID;
|
||||
v_fy_2025 UUID;
|
||||
BEGIN
|
||||
-- Obter ministerio existente
|
||||
SELECT id INTO v_min_financas FROM ministry WHERE code = 'MIN-001';
|
||||
|
||||
-- Inserir ministerios adicionais (se nao existirem)
|
||||
INSERT INTO ministry (id, code, name, created_at, updated_at)
|
||||
VALUES ('22222222-2222-2222-2222-222222222222', 'MINSAUDE', 'Ministerio da Saude Publica', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING
|
||||
RETURNING id INTO v_min_saude;
|
||||
|
||||
IF v_min_saude IS NULL THEN
|
||||
SELECT id INTO v_min_saude FROM ministry WHERE code = 'MINSAUDE';
|
||||
END IF;
|
||||
|
||||
INSERT INTO ministry (id, code, name, created_at, updated_at)
|
||||
VALUES ('33333333-3333-3333-3333-333333333333', 'MINEDU', 'Ministerio da Educacao Nacional', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING
|
||||
RETURNING id INTO v_min_educacao;
|
||||
|
||||
IF v_min_educacao IS NULL THEN
|
||||
SELECT id INTO v_min_educacao FROM ministry WHERE code = 'MINEDU';
|
||||
END IF;
|
||||
|
||||
-- Inserir Unidades Organicas
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
|
||||
VALUES ('44444444-4444-4444-4444-444444444444', 'DGT', 'Direcao-Geral do Tesouro', v_min_financas, NULL, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
|
||||
VALUES ('55555555-5555-5555-5555-555555555555', 'DGO', 'Direcao-Geral do Orcamento', v_min_financas, NULL, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
|
||||
VALUES ('66666666-6666-6666-6666-666666666666', 'HOSP-CENTRAL', 'Hospital Nacional Simao Mendes', v_min_saude, NULL, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO org_unit (id, code, name, ministry_id, parent_id, created_at, updated_at)
|
||||
VALUES ('77777777-7777-7777-7777-777777777777', 'ESC-SEC-BISSAU', 'Escola Secundaria de Bissau', v_min_educacao, NULL, now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- Inserir Cargos
|
||||
INSERT INTO position (id, code, title, description, created_at, updated_at)
|
||||
VALUES ('88888888-8888-8888-8888-888888888888', 'DIR-GERAL', 'Diretor-Geral', 'Cargo de direcao superior', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO position (id, code, title, description, created_at, updated_at)
|
||||
VALUES ('99999999-9999-9999-9999-999999999999', 'TEC-SUP', 'Tecnico Superior', 'Tecnico de nivel superior', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO position (id, code, title, description, created_at, updated_at)
|
||||
VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'MEDICO', 'Medico Especialista', 'Medico com especializacao', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO position (id, code, title, description, created_at, updated_at)
|
||||
VALUES ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'PROF', 'Professor do Ensino Secundario', 'Professor licenciado', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- Inserir Bancos
|
||||
INSERT INTO bank (id, code, name, swift_code, created_at, updated_at)
|
||||
VALUES ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'BCEAO', 'Banco Central dos Estados da Africa Ocidental', 'BCAOXXXX', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO bank (id, code, name, swift_code, created_at, updated_at)
|
||||
VALUES ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'BRS', 'Banco Regional de Solidariedade', 'BRSXGWGW', now(), now())
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
-- Obter estrutura salarial existente
|
||||
SELECT id INTO v_cat_ts FROM salary_category WHERE code = 'TS';
|
||||
SELECT id INTO v_grade_a FROM salary_grade WHERE code = 'A' AND category_id = v_cat_ts;
|
||||
SELECT id INTO v_step_1 FROM salary_step WHERE grade_id = v_grade_a AND step_number = 1;
|
||||
SELECT id INTO v_fy_2025 FROM fiscal_year WHERE year = 2025;
|
||||
|
||||
-- Adicionar escaloes (se nao existirem)
|
||||
INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at)
|
||||
VALUES ('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', v_grade_a, 2, now(), now())
|
||||
ON CONFLICT (grade_id, step_number) DO NOTHING;
|
||||
|
||||
INSERT INTO salary_step (id, grade_id, step_number, created_at, updated_at)
|
||||
VALUES ('ffffffff-ffff-ffff-ffff-ffffffffffff', v_grade_a, 3, now(), now())
|
||||
ON CONFLICT (grade_id, step_number) DO NOTHING;
|
||||
|
||||
-- Valores da grelha
|
||||
INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at)
|
||||
SELECT '10101010-1010-1010-1010-101010101010', id, 550000.00, '2024-01-01', now(), now()
|
||||
FROM salary_step WHERE grade_id = v_grade_a AND step_number = 2
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO salary_grid (id, step_id, base_amount, valid_from, created_at, updated_at)
|
||||
SELECT '20202020-2020-2020-2020-202020202020', id, 600000.00, '2024-01-01', now(), now()
|
||||
FROM salary_step WHERE grade_id = v_grade_a AND step_number = 3
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- Inserir Agentes (se nao existirem)
|
||||
INSERT INTO agents (
|
||||
id, matricula, nif, full_name, birth_date, nationality, bi_number,
|
||||
email, phone, address, hire_date, posse_date, appointment_type,
|
||||
functional_situation, literary_qualification, status,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
eligible_dependents_count, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
'a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', '2020/001', '100123456', 'Amilcar Cabral Silva', '1975-03-15', 'Guineense', 'BI123456',
|
||||
'amilcar.silva@minfin.gov.gw', '+245 955 123 456', 'Bairro de Penha, Bissau',
|
||||
'2020-01-15', '2020-02-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
ou.id, p.id, v_cat_ts, v_grade_a, ss.id, 2, now(), now()
|
||||
FROM org_unit ou, position p, salary_step ss
|
||||
WHERE ou.code = 'DGT' AND p.code = 'DIR-GERAL' AND ss.grade_id = v_grade_a AND ss.step_number = 3
|
||||
ON CONFLICT (matricula) DO NOTHING;
|
||||
|
||||
INSERT INTO agents (
|
||||
id, matricula, nif, full_name, birth_date, nationality, bi_number,
|
||||
email, phone, address, hire_date, posse_date, appointment_type,
|
||||
functional_situation, literary_qualification, status,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
eligible_dependents_count, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
'b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', '2021/045', '100234567', 'Francisca Pereira Gomes', '1988-07-22', 'Guineense', 'BI234567',
|
||||
'francisca.gomes@minfin.gov.gw', '+245 955 234 567', 'Bairro Militar, Bissau',
|
||||
'2021-03-10', '2021-04-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'MESTRADO', 'ACTIVE',
|
||||
ou.id, p.id, v_cat_ts, v_grade_a, ss.id, 1, now(), now()
|
||||
FROM org_unit ou, position p, salary_step ss
|
||||
WHERE ou.code = 'DGO' AND p.code = 'TEC-SUP' AND ss.grade_id = v_grade_a AND ss.step_number = 2
|
||||
ON CONFLICT (matricula) DO NOTHING;
|
||||
|
||||
INSERT INTO agents (
|
||||
id, matricula, nif, full_name, birth_date, nationality, bi_number,
|
||||
email, phone, address, hire_date, posse_date, appointment_type,
|
||||
functional_situation, literary_qualification, status,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
eligible_dependents_count, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
'c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', '2019/089', '100345678', 'Dr. Joao Vieira Mendes', '1982-11-30', 'Guineense', 'BI345678',
|
||||
'joao.mendes@minsaude.gov.gw', '+245 955 345 678', 'Bairro de Antula, Bissau',
|
||||
'2019-06-01', '2019-07-01', 'NOMEACAO_DEFINITIVA', 'ACTIVE', 'DOUTORAMENTO', 'ACTIVE',
|
||||
ou.id, p.id, v_cat_ts, v_grade_a, ss.id, 3, now(), now()
|
||||
FROM org_unit ou, position p, salary_step ss
|
||||
WHERE ou.code = 'HOSP-CENTRAL' AND p.code = 'MEDICO' AND ss.grade_id = v_grade_a AND ss.step_number = 3
|
||||
ON CONFLICT (matricula) DO NOTHING;
|
||||
|
||||
INSERT INTO agents (
|
||||
id, matricula, nif, full_name, birth_date, nationality, bi_number,
|
||||
email, phone, address, hire_date, posse_date, appointment_type,
|
||||
functional_situation, literary_qualification, status,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
eligible_dependents_count, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
'd4d4d4d4-d4d4-d4d4-d4d4-d4d4d4d4d4d4', '2022/112', '100456789', 'Maria da Luz Correia', '1990-05-18', 'Guineense', 'BI456789',
|
||||
'maria.correia@minedu.gov.gw', '+245 955 456 789', 'Bairro de Quelele, Bissau',
|
||||
'2022-09-01', '2022-10-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
ou.id, p.id, v_cat_ts, v_grade_a, v_step_1, 0, now(), now()
|
||||
FROM org_unit ou, position p
|
||||
WHERE ou.code = 'ESC-SEC-BISSAU' AND p.code = 'PROF'
|
||||
ON CONFLICT (matricula) DO NOTHING;
|
||||
|
||||
INSERT INTO agents (
|
||||
id, matricula, nif, full_name, birth_date, nationality, bi_number,
|
||||
email, phone, address, hire_date, posse_date, appointment_type,
|
||||
functional_situation, literary_qualification, status,
|
||||
org_unit_id, position_id, salary_category_id, salary_grade_id, salary_step_id,
|
||||
eligible_dependents_count, created_at, updated_at
|
||||
)
|
||||
SELECT
|
||||
'e5e5e5e5-e5e5-e5e5-e5e5-e5e5e5e5e5e5', '2024/201', '100567890', 'Samba Djalo', '1995-09-12', 'Guineense', 'BI567890',
|
||||
'samba.djalo@minfin.gov.gw', '+245 955 567 890', 'Bairro de Chao de Papel, Bissau',
|
||||
'2024-11-01', '2024-12-01', 'NOMEACAO_PROVISORIA', 'ACTIVE', 'LICENCIATURA', 'ACTIVE',
|
||||
ou.id, p.id, v_cat_ts, v_grade_a, v_step_1, 0, now(), now()
|
||||
FROM org_unit ou, position p
|
||||
WHERE ou.code = 'DGT' AND p.code = 'TEC-SUP'
|
||||
ON CONFLICT (matricula) DO NOTHING;
|
||||
|
||||
-- Linhas orcamentais
|
||||
INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
|
||||
SELECT 'f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1f1', v_fy_2025, '2025-MINFIN-311100', 'Vencimentos Base - Financas',
|
||||
v_min_financas, ou.id, '311100', now(), now()
|
||||
FROM org_unit ou WHERE ou.code = 'DGT'
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
|
||||
SELECT 'f2f2f2f2-f2f2-f2f2-f2f2-f2f2f2f2f2f2', v_fy_2025, '2025-MINSAUDE-311100', 'Vencimentos Base - Saude',
|
||||
v_min_saude, ou.id, '311100', now(), now()
|
||||
FROM org_unit ou WHERE ou.code = 'HOSP-CENTRAL'
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO budget_line (id, fiscal_year_id, code, description, ministry_id, org_unit_id, economic_class, created_at, updated_at)
|
||||
SELECT 'f3f3f3f3-f3f3-f3f3-f3f3-f3f3f3f3f3f3', v_fy_2025, '2025-MINEDU-311100', 'Vencimentos Base - Educacao',
|
||||
v_min_educacao, ou.id, '311100', now(), now()
|
||||
FROM org_unit ou WHERE ou.code = 'ESC-SEC-BISSAU'
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
RAISE NOTICE '=== DADOS DE TESTE INSERIDOS/ATUALIZADOS COM SUCESSO ===';
|
||||
RAISE NOTICE 'Script executado usando ministerio existente MIN-001';
|
||||
END $$;
|
||||
|
||||
-- Verificar resultados
|
||||
SELECT 'MINISTERIOS' as tipo, COUNT(*)::text as total FROM ministry
|
||||
UNION ALL
|
||||
SELECT 'UNIDADES ORGANICAS', COUNT(*)::text FROM org_unit
|
||||
UNION ALL
|
||||
SELECT 'CARGOS', COUNT(*)::text FROM position
|
||||
UNION ALL
|
||||
SELECT 'BANCOS', COUNT(*)::text FROM bank
|
||||
UNION ALL
|
||||
SELECT 'AGENTES', COUNT(*)::text FROM agents
|
||||
UNION ALL
|
||||
SELECT 'LINHAS ORCAMENTAIS', COUNT(*)::text FROM budget_line;
|
||||
@@ -0,0 +1,157 @@
|
||||
-- =====================================================
|
||||
-- ARQUITETURA COMPLETA DE TESOURO - NOVAS TABELAS
|
||||
-- Similar à arquitetura de Elaboração e Aprovação do Orçamento
|
||||
-- =====================================================
|
||||
|
||||
-- Contas de Caixa/Bancárias
|
||||
CREATE TABLE IF NOT EXISTS public.cash_account (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
code VARCHAR(50) UNIQUE NOT NULL,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
type VARCHAR(20) NOT NULL, -- CASH, BANK_ACCOUNT
|
||||
bank_id UUID,
|
||||
account_number VARCHAR(50),
|
||||
branch_code VARCHAR(20),
|
||||
currency VARCHAR(3) DEFAULT 'XOF',
|
||||
is_active BOOLEAN DEFAULT true,
|
||||
current_balance NUMERIC(19,2) DEFAULT 0,
|
||||
available_balance NUMERIC(19,2) DEFAULT 0,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
version BIGINT DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_cash_account_code ON public.cash_account(code);
|
||||
CREATE INDEX idx_cash_account_type ON public.cash_account(type);
|
||||
CREATE INDEX idx_cash_account_active ON public.cash_account(is_active);
|
||||
|
||||
-- Entradas de Tesouraria (Similar a budget_entry)
|
||||
CREATE TABLE IF NOT EXISTS public.treasury_entry (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
cash_account_id UUID NOT NULL REFERENCES public.cash_account(id),
|
||||
type VARCHAR(50) NOT NULL,
|
||||
amount NUMERIC(19,2) NOT NULL,
|
||||
transaction_date DATE NOT NULL,
|
||||
document_reference VARCHAR(100),
|
||||
description TEXT,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'DRAFT', -- DRAFT, PENDING_APPROVAL, APPROVED, REJECTED, EXECUTED
|
||||
approval_level INTEGER,
|
||||
approved_by UUID,
|
||||
approved_at TIMESTAMP,
|
||||
payment_order_id UUID,
|
||||
payment_batch_id UUID,
|
||||
budget_line_id UUID,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
version BIGINT DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_treasury_entry_cash_account ON public.treasury_entry(cash_account_id);
|
||||
CREATE INDEX idx_treasury_entry_type ON public.treasury_entry(type);
|
||||
CREATE INDEX idx_treasury_entry_status ON public.treasury_entry(status);
|
||||
CREATE INDEX idx_treasury_entry_date ON public.treasury_entry(transaction_date);
|
||||
CREATE INDEX idx_treasury_entry_payment_order ON public.treasury_entry(payment_order_id);
|
||||
|
||||
-- Autorizações de Pagamento
|
||||
CREATE TABLE IF NOT EXISTS public.payment_authorization (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
payment_order_id UUID,
|
||||
payment_batch_id UUID,
|
||||
requested_by UUID NOT NULL,
|
||||
requested_at TIMESTAMP NOT NULL,
|
||||
required_approval_level INTEGER NOT NULL,
|
||||
current_approval_level INTEGER DEFAULT 1,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'PENDING', -- PENDING, PARTIALLY_APPROVED, APPROVED, REJECTED
|
||||
rejection_reason TEXT,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
version BIGINT DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_auth_payment_order ON public.payment_authorization(payment_order_id);
|
||||
CREATE INDEX idx_auth_payment_batch ON public.payment_authorization(payment_batch_id);
|
||||
CREATE INDEX idx_auth_status ON public.payment_authorization(status);
|
||||
CREATE INDEX idx_auth_requested_by ON public.payment_authorization(requested_by);
|
||||
|
||||
-- Aprovações (Histórico)
|
||||
CREATE TABLE IF NOT EXISTS public.approval (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
authorization_id UUID NOT NULL REFERENCES public.payment_authorization(id),
|
||||
level INTEGER NOT NULL,
|
||||
approved_by UUID NOT NULL,
|
||||
approved_at TIMESTAMP NOT NULL,
|
||||
comments TEXT,
|
||||
signature_hash VARCHAR(255)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_approval_authorization ON public.approval(authorization_id);
|
||||
CREATE INDEX idx_approval_approver ON public.approval(approved_by);
|
||||
CREATE INDEX idx_approval_level ON public.approval(level);
|
||||
|
||||
-- Fluxo de Caixa
|
||||
CREATE TABLE IF NOT EXISTS public.cash_flow (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
cash_account_id UUID NOT NULL REFERENCES public.cash_account(id),
|
||||
transaction_date DATE NOT NULL,
|
||||
type VARCHAR(20) NOT NULL, -- INFLOW, OUTFLOW
|
||||
amount NUMERIC(19,2) NOT NULL,
|
||||
description TEXT,
|
||||
reference_id UUID,
|
||||
reference_type VARCHAR(50),
|
||||
balance_after NUMERIC(19,2) NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
version BIGINT DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_cash_flow_account ON public.cash_flow(cash_account_id);
|
||||
CREATE INDEX idx_cash_flow_date ON public.cash_flow(transaction_date);
|
||||
CREATE INDEX idx_cash_flow_type ON public.cash_flow(type);
|
||||
CREATE INDEX idx_cash_flow_reference ON public.cash_flow(reference_type, reference_id);
|
||||
|
||||
-- Conciliação Bancária
|
||||
CREATE TABLE IF NOT EXISTS public.bank_reconciliation (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
cash_account_id UUID NOT NULL REFERENCES public.cash_account(id),
|
||||
reconciliation_date DATE NOT NULL,
|
||||
statement_balance NUMERIC(19,2) NOT NULL,
|
||||
system_balance NUMERIC(19,2) NOT NULL,
|
||||
difference NUMERIC(19,2),
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'PENDING', -- PENDING, RECONCILED, DISCREPANCY
|
||||
reconciled_by UUID,
|
||||
reconciled_at TIMESTAMP,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
version BIGINT DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX idx_reconciliation_cash_account ON public.bank_reconciliation(cash_account_id);
|
||||
CREATE INDEX idx_reconciliation_date ON public.bank_reconciliation(reconciliation_date);
|
||||
CREATE INDEX idx_reconciliation_status ON public.bank_reconciliation(status);
|
||||
|
||||
-- Itens de Conciliação
|
||||
CREATE TABLE IF NOT EXISTS public.reconciliation_item (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
reconciliation_id UUID NOT NULL REFERENCES public.bank_reconciliation(id),
|
||||
transaction_date DATE NOT NULL,
|
||||
description TEXT,
|
||||
statement_amount NUMERIC(19,2),
|
||||
system_amount NUMERIC(19,2),
|
||||
match_status VARCHAR(20) NOT NULL DEFAULT 'PENDING', -- MATCHED, UNMATCHED, PENDING
|
||||
matched_transaction_id UUID,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX idx_reconciliation_item_reconciliation ON public.reconciliation_item(reconciliation_id);
|
||||
CREATE INDEX idx_reconciliation_item_status ON public.reconciliation_item(match_status);
|
||||
CREATE INDEX idx_reconciliation_item_date ON public.reconciliation_item(transaction_date);
|
||||
|
||||
-- Comentários
|
||||
COMMENT ON TABLE public.cash_account IS 'Contas de caixa e bancárias do Tesouro';
|
||||
COMMENT ON TABLE public.treasury_entry IS 'Entradas de tesouraria - rastreamento completo do ciclo de vida';
|
||||
COMMENT ON TABLE public.payment_authorization IS 'Workflow de aprovação hierárquica de pagamentos';
|
||||
COMMENT ON TABLE public.approval IS 'Histórico de aprovações individuais';
|
||||
COMMENT ON TABLE public.cash_flow IS 'Fluxo de caixa - entradas e saídas';
|
||||
COMMENT ON TABLE public.bank_reconciliation IS 'Conciliação bancária';
|
||||
COMMENT ON TABLE public.reconciliation_item IS 'Itens de conciliação bancária';
|
||||
|
||||
Reference in New Issue
Block a user