Compare commits
29 Commits
front/ui-i
...
pagamentos
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ff58cc51e | ||
|
|
813c968efd | ||
|
|
bdab631f0f | ||
|
|
91369f670f | ||
|
|
494b6262bf | ||
|
|
e01764ab40 | ||
|
|
279924a43c | ||
|
|
54191b8dde | ||
|
|
295a433d59 | ||
|
|
203751deeb | ||
|
|
71f926e6be | ||
|
|
8cef19576e | ||
|
|
abc46704c3 | ||
|
|
c640a756df | ||
|
|
3f2e6e3022 | ||
|
|
179ea3cad0 | ||
|
|
b47c9efc21 | ||
|
|
97711d30c7 | ||
|
|
50ef370c2b | ||
|
|
53594517c0 | ||
|
|
874df1d340 | ||
|
|
b170f94058 | ||
|
|
786040162b | ||
|
|
daaa7fd462 | ||
|
|
ad0ea2f259 | ||
|
|
74e5a1f7e3 | ||
|
|
d07a227e80 | ||
|
|
0635003485 | ||
|
|
d931fb4b5e |
50
.dockerignore
Normal file
50
.dockerignore
Normal file
@@ -0,0 +1,50 @@
|
||||
# Arquivos e diretórios do Git
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# Arquivos do Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
env/
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Arquivos de ambiente
|
||||
.env
|
||||
.venv
|
||||
venv/
|
||||
ENV/
|
||||
|
||||
# Arquivos de IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Arquivos de log
|
||||
*.log
|
||||
|
||||
# Arquivos de banco de dados
|
||||
*.db
|
||||
*.sqlite3
|
||||
|
||||
# Arquivos temporários
|
||||
*.tmp
|
||||
*.bak
|
||||
*.swp
|
||||
*~
|
||||
39
Dockerfile
Normal file
39
Dockerfile
Normal file
@@ -0,0 +1,39 @@
|
||||
FROM alpine:latest
|
||||
|
||||
# Instalar dependências do sistema
|
||||
RUN apk update && \
|
||||
apk add --no-cache \
|
||||
python3 \
|
||||
py3-pip \
|
||||
make \
|
||||
git \
|
||||
gcc \
|
||||
python3-dev \
|
||||
musl-dev \
|
||||
linux-headers
|
||||
|
||||
# Criar link simbólico para python3
|
||||
RUN ln -sf python3 /usr/bin/python
|
||||
|
||||
# Definir diretório de trabalho
|
||||
WORKDIR /app
|
||||
|
||||
# Copiar arquivos do projeto
|
||||
COPY . .
|
||||
|
||||
# Criar e ativar ambiente virtual
|
||||
RUN python -m venv /venv && \
|
||||
. /venv/bin/activate && \
|
||||
pip install --upgrade pip && \
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Expor a porta que o Flask usa
|
||||
EXPOSE 5000
|
||||
|
||||
# Definir o ambiente virtual como padrão
|
||||
ENV PATH="/venv/bin:$PATH"
|
||||
ENV FLASK_APP=app.py
|
||||
ENV FLASK_ENV=production
|
||||
|
||||
# Comando para rodar a aplicação
|
||||
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:app"]
|
||||
32
Makefile
32
Makefile
@@ -1,18 +1,38 @@
|
||||
.PHONY: install run test clean refresh
|
||||
|
||||
install:
|
||||
pip install -r requirements.txt
|
||||
pip install pytest pytest-cov
|
||||
|
||||
clean:
|
||||
rm -rf ~/.local/share/controles/database.db
|
||||
find . -type d -name "__pycache__" -exec rm -r {} +
|
||||
find . -type f -name "*.pyc" -delete
|
||||
find . -type f -name "*.pyo" -delete
|
||||
find . -type f -name "*.pyd" -delete
|
||||
find . -type f -name ".coverage" -delete
|
||||
find . -type d -name "*.egg-info" -exec rm -r {} +
|
||||
find . -type d -name "*.egg" -exec rm -r {} +
|
||||
find . -type d -name ".pytest_cache" -exec rm -r {} +
|
||||
find . -type d -name "htmlcov" -exec rm -r {} +
|
||||
rm -rf ~/.local/share/controles/database.db*
|
||||
rm -f admin_qr.png
|
||||
|
||||
init-db: clean
|
||||
python init_db.py
|
||||
|
||||
seed: init-db
|
||||
python seed.py
|
||||
|
||||
run:
|
||||
python app.py
|
||||
|
||||
seed:
|
||||
python seed.py
|
||||
|
||||
run-with-seed: clean
|
||||
python app.py & sleep 5 && python seed.py
|
||||
run-with-seed: seed run
|
||||
|
||||
reset-admin: clean
|
||||
python create_admin.py
|
||||
|
||||
test:
|
||||
pytest tests/ --cov=app --cov=functions --cov-report=term-missing
|
||||
|
||||
refresh: clean install test
|
||||
python app.py
|
||||
|
||||
103
create_admin.py
103
create_admin.py
@@ -41,102 +41,37 @@ def generate_qr_code(user):
|
||||
return qr_path, otp_uri
|
||||
|
||||
def create_admin_user():
|
||||
"""Cria ou atualiza o usuário admin"""
|
||||
"""Cria o usuário admin do sistema"""
|
||||
session = get_db_connection()
|
||||
try:
|
||||
# Inicializar banco de dados
|
||||
init_database()
|
||||
# Buscar role de administrador
|
||||
admin_role = session.query(Role).filter_by(nome="Administrador").first()
|
||||
if not admin_role:
|
||||
print("Role de administrador não encontrada!")
|
||||
return
|
||||
|
||||
# Criar sessão
|
||||
db = get_db_connection()
|
||||
|
||||
try:
|
||||
# Verificar se já existe um usuário admin
|
||||
admin = db.query(Usuario).filter_by(username="admin").first()
|
||||
|
||||
if admin:
|
||||
print("\n=== Usuário Admin Encontrado ===")
|
||||
if not admin.otp_secret:
|
||||
print("Gerando novo segredo OTP...")
|
||||
admin.generate_otp_secret()
|
||||
db.commit()
|
||||
else:
|
||||
print("\n=== Criando Novo Usuário Admin ===")
|
||||
# Criar novo usuário admin
|
||||
# Verificar se o usuário admin já existe
|
||||
if not session.query(Usuario).filter_by(username="admin").first():
|
||||
admin = Usuario(
|
||||
username="admin",
|
||||
email="admin@example.com",
|
||||
is_admin=True
|
||||
)
|
||||
admin.set_password("admin123")
|
||||
admin.generate_otp_secret()
|
||||
|
||||
# Adicionar e fazer commit
|
||||
db.add(admin)
|
||||
db.commit()
|
||||
|
||||
# Gerar QR code apenas se solicitado ou se for novo usuário
|
||||
if not os.path.exists('admin_qr.png'):
|
||||
qr_path, otp_uri = generate_qr_code(admin)
|
||||
print("\n=== QR Code Gerado ===")
|
||||
print(f"QR Code salvo em: {qr_path}")
|
||||
print(f"URI do OTP: {otp_uri}")
|
||||
admin.tipo = "ADMIN"
|
||||
admin.roles.append(admin_role)
|
||||
session.add(admin)
|
||||
session.commit()
|
||||
print("Usuário admin criado com sucesso!")
|
||||
else:
|
||||
print("\n=== QR Code Existente ===")
|
||||
print("Usando QR Code existente em: admin_qr.png")
|
||||
qr_path = 'admin_qr.png'
|
||||
|
||||
# Mostrar informações
|
||||
print("\n=== Informações do Admin ===")
|
||||
print(f"Username: {admin.username}")
|
||||
print(f"Email: {admin.email}")
|
||||
print(f"Senha: admin123")
|
||||
print(f"Segredo OTP: {admin.otp_secret}")
|
||||
|
||||
# Gerar código atual para verificação
|
||||
totp = pyotp.TOTP(admin.otp_secret)
|
||||
current_code = totp.now()
|
||||
print("\n=== Verificação do OTP ===")
|
||||
print(f"Código OTP atual: {current_code}")
|
||||
print(f"Verificação do código: {totp.verify(current_code)}")
|
||||
|
||||
print("\n=== Instruções para Configuração ===")
|
||||
print("1. Instale um aplicativo autenticador no seu celular")
|
||||
print(" (Google Authenticator, Microsoft Authenticator, etc)")
|
||||
print("2. Abra o aplicativo")
|
||||
print("3. Selecione a opção para adicionar uma nova conta")
|
||||
print("4. Escaneie o QR Code salvo em:", qr_path)
|
||||
print("\nOU configure manualmente:")
|
||||
print(f"- Nome da conta: {admin.username}")
|
||||
print(f"- Segredo: {admin.otp_secret}")
|
||||
print("- Tipo: Baseado em tempo (TOTP)")
|
||||
print("- Algoritmo: SHA1")
|
||||
print("- Dígitos: 6")
|
||||
print("- Intervalo: 30 segundos")
|
||||
|
||||
# Verificação final
|
||||
print("\n=== Teste de Verificação ===")
|
||||
test_code = totp.now()
|
||||
print(f"Código de teste: {test_code}")
|
||||
is_valid = admin.verify_otp(test_code)
|
||||
print(f"Verificação do código: {'Sucesso' if is_valid else 'Falha'}")
|
||||
|
||||
if not is_valid:
|
||||
print("\nALERTA: Verificação do OTP falhou!")
|
||||
print("Por favor, verifique se o segredo OTP está correto.")
|
||||
|
||||
# Fazer commit final para garantir que tudo foi salvo
|
||||
db.commit()
|
||||
print("Usuário admin já existe!")
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise e
|
||||
print(f"Erro ao criar usuário admin: {e}")
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nErro durante a execução: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
session.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_admin_user()
|
||||
|
||||
@@ -1,130 +1,65 @@
|
||||
from functions.database import get_db_connection, Usuario
|
||||
from functions.rbac import Role
|
||||
import pyotp
|
||||
import qrcode
|
||||
import os
|
||||
import base64
|
||||
from io import BytesIO
|
||||
from functions.database import Usuario, Role, get_db_connection
|
||||
|
||||
def create_test_users():
|
||||
"""Cria usuários de teste se não existirem"""
|
||||
db = get_db_connection()
|
||||
"""Cria usuários de teste para o sistema"""
|
||||
session = get_db_connection()
|
||||
try:
|
||||
# Usuários de teste
|
||||
test_users = [
|
||||
# Buscar roles
|
||||
secretario_celula = session.query(Role).filter_by(nivel=Role.SECRETARIO_CELULA).first()
|
||||
secretario_setor = session.query(Role).filter_by(nivel=Role.SECRETARIO_SETOR).first()
|
||||
secretario_cr = session.query(Role).filter_by(nivel=Role.SECRETARIO_CR).first()
|
||||
secretario_geral = session.query(Role).filter_by(nivel=Role.SECRETARIO_GERAL).first()
|
||||
|
||||
# Criar usuários de teste
|
||||
usuarios = [
|
||||
{
|
||||
'username': 'teste',
|
||||
'password': 'admin123', # Mesma senha do admin
|
||||
'email': 'teste@controles.com',
|
||||
'is_admin': True
|
||||
'username': 'celula',
|
||||
'email': 'celula@example.com',
|
||||
'password': 'celula123',
|
||||
'role': secretario_celula,
|
||||
'tipo': 'SECRETARIO_CELULA'
|
||||
},
|
||||
{
|
||||
'username': 'aligner',
|
||||
'password': 'Test123!@#',
|
||||
'email': 'aligner@controles.com',
|
||||
'is_admin': False
|
||||
'username': 'setor',
|
||||
'email': 'setor@example.com',
|
||||
'password': 'setor123',
|
||||
'role': secretario_setor,
|
||||
'tipo': 'SECRETARIO_SETOR'
|
||||
},
|
||||
{
|
||||
'username': 'tester',
|
||||
'password': 'Test123!@#',
|
||||
'email': 'tester@controles.com',
|
||||
'is_admin': False
|
||||
'username': 'cr',
|
||||
'email': 'cr@example.com',
|
||||
'password': 'cr123',
|
||||
'role': secretario_cr,
|
||||
'tipo': 'SECRETARIO_CR'
|
||||
},
|
||||
{
|
||||
'username': 'deployer',
|
||||
'password': 'Test123!@#',
|
||||
'email': 'deployer@controles.com',
|
||||
'is_admin': False
|
||||
'username': 'geral',
|
||||
'email': 'geral@example.com',
|
||||
'password': 'geral123',
|
||||
'role': secretario_geral,
|
||||
'tipo': 'SECRETARIO_GERAL'
|
||||
}
|
||||
]
|
||||
|
||||
# Obter o OTP secret do admin se existir
|
||||
admin = db.query(Usuario).filter_by(username='admin').first()
|
||||
admin_otp_secret = admin.otp_secret if admin else None
|
||||
|
||||
for user_data in test_users:
|
||||
for user_data in usuarios:
|
||||
# Verificar se o usuário já existe
|
||||
user = db.query(Usuario).filter_by(username=user_data['username']).first()
|
||||
|
||||
if not user:
|
||||
print(f"Criando usuário {user_data['username']}...")
|
||||
# Criar usuário
|
||||
if not session.query(Usuario).filter_by(username=user_data['username']).first():
|
||||
user = Usuario(
|
||||
username=user_data['username'],
|
||||
email=user_data['email'],
|
||||
is_admin=user_data['is_admin']
|
||||
email=user_data['email']
|
||||
)
|
||||
user.set_password(user_data['password'])
|
||||
user.tipo = "ADMIN" if user_data['is_admin'] else "USUARIO"
|
||||
user.tipo = user_data['tipo']
|
||||
user.roles.append(user_data['role'])
|
||||
session.add(user)
|
||||
|
||||
# Se for o usuário teste, usar o mesmo OTP do admin
|
||||
if user_data['username'] == 'teste' and admin_otp_secret:
|
||||
user.otp_secret = admin_otp_secret
|
||||
else:
|
||||
# Gerar novo OTP para outros usuários
|
||||
user.otp_secret = pyotp.random_base32()
|
||||
|
||||
db.add(user)
|
||||
db.commit()
|
||||
|
||||
# Atribuir role de Secretário Geral para o usuário teste
|
||||
if user_data['username'] == 'teste':
|
||||
admin_role = db.query(Role).filter_by(nivel=Role.SECRETARIO_GERAL).first()
|
||||
if admin_role:
|
||||
user.roles.append(admin_role)
|
||||
db.commit()
|
||||
|
||||
print(f"Usuário {user_data['username']} criado com sucesso!")
|
||||
|
||||
# Gerar QR code para o novo usuário
|
||||
qr_path = f"{user_data['username']}_qr.png"
|
||||
if not os.path.exists(qr_path):
|
||||
totp = pyotp.TOTP(user.otp_secret)
|
||||
qr = qrcode.QRCode(version=1, box_size=10, border=5)
|
||||
qr.add_data(totp.provisioning_uri(user.email, issuer_name="Sistema de Controles"))
|
||||
qr.make(fit=True)
|
||||
img = qr.make_image(fill_color="black", back_color="white")
|
||||
img.save(qr_path)
|
||||
print(f"QR Code gerado para {user_data['username']} em: {qr_path}")
|
||||
else:
|
||||
print(f"Usuário {user_data['username']} já existe")
|
||||
|
||||
# Se for o usuário teste e não tiver o OTP do admin, atualizar
|
||||
if user_data['username'] == 'teste' and admin_otp_secret and user.otp_secret != admin_otp_secret:
|
||||
user.otp_secret = admin_otp_secret
|
||||
db.commit()
|
||||
print(f"OTP do usuário teste atualizado para o mesmo do admin")
|
||||
elif not user.otp_secret:
|
||||
# Se não tiver OTP, gerar um novo
|
||||
user.otp_secret = pyotp.random_base32()
|
||||
db.commit()
|
||||
print(f"Novo OTP gerado para {user_data['username']}")
|
||||
|
||||
# Gerar QR code
|
||||
qr_path = f"{user_data['username']}_qr.png"
|
||||
if not os.path.exists(qr_path):
|
||||
totp = pyotp.TOTP(user.otp_secret)
|
||||
qr = qrcode.QRCode(version=1, box_size=10, border=5)
|
||||
qr.add_data(totp.provisioning_uri(user.email, issuer_name="Sistema de Controles"))
|
||||
qr.make(fit=True)
|
||||
img = qr.make_image(fill_color="black", back_color="white")
|
||||
img.save(qr_path)
|
||||
print(f"QR Code gerado para {user_data['username']} em: {qr_path}")
|
||||
|
||||
# Verificar se o usuário teste tem a role de Secretário Geral
|
||||
if user_data['username'] == 'teste':
|
||||
admin_role = db.query(Role).filter_by(nivel=Role.SECRETARIO_GERAL).first()
|
||||
if admin_role and admin_role not in user.roles:
|
||||
user.roles.append(admin_role)
|
||||
db.commit()
|
||||
print(f"Role de Secretário Geral atribuída ao usuário teste")
|
||||
session.commit()
|
||||
print("Usuários de teste criados com sucesso!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Erro ao criar usuários de teste: {str(e)}")
|
||||
db.rollback()
|
||||
print(f"Erro ao criar usuários de teste: {e}")
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
create_test_users()
|
||||
session.close()
|
||||
14
docker-compose.yml
Normal file
14
docker-compose.yml
Normal file
@@ -0,0 +1,14 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
ports:
|
||||
- "5000:5000"
|
||||
volumes:
|
||||
- .:/app
|
||||
- ~/.local/share/controles:/root/.local/share/controles
|
||||
environment:
|
||||
- FLASK_ENV=development
|
||||
- FLASK_APP=app.py
|
||||
restart: unless-stopped
|
||||
26
docs/rbac.md
26
docs/rbac.md
@@ -109,22 +109,26 @@ CREATE TABLE user_roles (
|
||||
- `manage_cell_members`: Gerenciar membros da célula
|
||||
- `create_cell_member`: Criar novos membros na célula
|
||||
- `view_cell_reports`: Visualizar relatórios da célula
|
||||
- `REGISTER_CELL_RECEIPT`: Registrar comprovantes da célula
|
||||
|
||||
### Permissões de Setor
|
||||
- `manage_sector_cells`: Gerenciar células do setor
|
||||
- `create_sector_cell`: Criar novas células no setor
|
||||
- `view_sector_reports`: Visualizar relatórios do setor
|
||||
- `REGISTER_SECTOR_RECEIPT`: Registrar comprovantes do setor
|
||||
|
||||
### Permissões de CR
|
||||
- `manage_cr_sectors`: Gerenciar setores do CR
|
||||
- `create_cr_sector`: Criar novos setores no CR
|
||||
- `view_cr_reports`: Visualizar relatórios do CR
|
||||
- `REGISTER_CR_RECEIPT`: Registrar comprovantes do CR
|
||||
|
||||
### Permissões de CC
|
||||
- `manage_cc_crs`: Gerenciar CRs
|
||||
- `create_cc_cr`: Criar novos CRs
|
||||
- `view_cc_reports`: Visualizar relatórios nacionais
|
||||
- `system_config`: Configurar o sistema
|
||||
- `REGISTER_CC_RECEIPT`: Registrar comprovantes do CC
|
||||
|
||||
## Uso no Código
|
||||
|
||||
@@ -166,12 +170,12 @@ O sistema possui uma estrutura hierárquica com os seguintes níveis:
|
||||
- `MANAGE_CELL_MEMBERS`: Gerenciar membros da célula
|
||||
- `VIEW_CELL_DATA`: Visualizar dados da célula
|
||||
- `VIEW_CELL_REPORTS`: Visualizar relatórios da célula
|
||||
- `REGISTER_CELL_PAYMENT`: Registrar pagamentos da célula
|
||||
- `REGISTER_CELL_RECEIPT`: Registrar comprovantes da célula
|
||||
|
||||
- **Tesoureiro(a)**:
|
||||
- `VIEW_CELL_DATA`: Visualizar dados da célula
|
||||
- `VIEW_CELL_REPORTS`: Visualizar relatórios da célula
|
||||
- `REGISTER_CELL_PAYMENT`: Registrar pagamentos da célula
|
||||
- `REGISTER_CELL_RECEIPT`: Registrar comprovantes da célula
|
||||
|
||||
- **Militante**:
|
||||
- `VIEW_OWN_DATA`: Visualizar apenas seus próprios dados
|
||||
@@ -180,32 +184,32 @@ O sistema possui uma estrutura hierárquica com os seguintes níveis:
|
||||
- **Secretário(a)**:
|
||||
- `MANAGE_SECTOR_CELLS`: Gerenciar células do setor
|
||||
- `VIEW_SECTOR_REPORTS`: Visualizar relatórios do setor
|
||||
- `REGISTER_SECTOR_PAYMENT`: Registrar pagamentos do setor
|
||||
- `REGISTER_SECTOR_RECEIPT`: Registrar comprovantes do setor
|
||||
|
||||
- **Tesoureiro(a)**:
|
||||
- `VIEW_SECTOR_REPORTS`: Visualizar relatórios do setor
|
||||
- `REGISTER_SECTOR_PAYMENT`: Registrar pagamentos do setor
|
||||
- `REGISTER_SECTOR_RECEIPT`: Registrar comprovantes do setor
|
||||
|
||||
### CR
|
||||
- **Secretário(a)**:
|
||||
- `MANAGE_CR_SECTORS`: Gerenciar setores do CR
|
||||
- `VIEW_CR_REPORTS`: Visualizar relatórios do CR
|
||||
- `REGISTER_CR_PAYMENT`: Registrar pagamentos do CR
|
||||
- `REGISTER_CR_RECEIPT`: Registrar comprovantes do CR
|
||||
|
||||
- **Tesoureiro(a)**:
|
||||
- `VIEW_CR_REPORTS`: Visualizar relatórios do CR
|
||||
- `REGISTER_CR_PAYMENT`: Registrar pagamentos do CR
|
||||
- `REGISTER_CR_RECEIPT`: Registrar comprovantes do CR
|
||||
|
||||
### CC
|
||||
- **Secretário(a)**:
|
||||
- `MANAGE_CC_CRS`: Gerenciar CRs
|
||||
- `VIEW_CC_REPORTS`: Visualizar relatórios do CC
|
||||
- `REGISTER_CC_PAYMENT`: Registrar pagamentos do CC
|
||||
- `REGISTER_CC_RECEIPT`: Registrar comprovantes do CC
|
||||
- `SYSTEM_CONFIG`: Configurar o sistema
|
||||
|
||||
- **Tesoureiro(a)**:
|
||||
- `VIEW_CC_REPORTS`: Visualizar relatórios do CC
|
||||
- `REGISTER_CC_PAYMENT`: Registrar pagamentos do CC
|
||||
- `REGISTER_CC_RECEIPT`: Registrar comprovantes do CC
|
||||
|
||||
## Regras de Acesso a Dados
|
||||
|
||||
@@ -214,10 +218,10 @@ O sistema possui uma estrutura hierárquica com os seguintes níveis:
|
||||
- Secretários e tesoureiros podem ver dados de sua instância
|
||||
- O CC tem acesso a todos os dados
|
||||
|
||||
2. **Registro de Pagamentos**:
|
||||
- Apenas tesoureiros e secretários podem registrar pagamentos
|
||||
2. **Registro de Comprovantes**:
|
||||
- Apenas tesoureiros e secretários podem registrar comprovantes
|
||||
- O registro é restrito à instância do usuário
|
||||
- O CC pode registrar pagamentos em qualquer nível
|
||||
- O CC pode registrar comprovantes em qualquer nível
|
||||
|
||||
## Implementação Técnica
|
||||
|
||||
|
||||
94
docs/regras_comprovantes.md
Normal file
94
docs/regras_comprovantes.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Regras de Negócio - Comprovantes
|
||||
|
||||
## 1. Estrutura do Comprovante
|
||||
|
||||
### 1.1 Dados Básicos
|
||||
- Todo comprovante deve ter:
|
||||
- Militante associado (obrigatório)
|
||||
- Data do comprovante (obrigatório)
|
||||
- Forma de pagamento (obrigatório)
|
||||
- Campanha financeira (opcional)
|
||||
|
||||
### 1.2 Formas de Pagamento
|
||||
- As formas de pagamento aceitas são:
|
||||
- PIX
|
||||
- Transferência/DOC
|
||||
- Depósito
|
||||
- Maquininha
|
||||
|
||||
## 2. Centralizações
|
||||
|
||||
### 2.1 Tipos de Centralização
|
||||
- Cada comprovante pode ter uma ou mais centralizações
|
||||
- Os tipos de centralização são:
|
||||
- Cota
|
||||
- Jornal
|
||||
- Assinatura
|
||||
|
||||
### 2.2 Valores
|
||||
- Cada centralização deve ter:
|
||||
- Tipo (obrigatório)
|
||||
- Valor (obrigatório, maior que zero)
|
||||
|
||||
## 3. Transações PIX
|
||||
|
||||
### 3.1 Dados da Transação
|
||||
- Para pagamentos via PIX, o comprovante deve incluir:
|
||||
- Chave PIX
|
||||
- Valor
|
||||
- Data de geração
|
||||
- Data de pagamento
|
||||
- Status (Pendente, Pago, Expirado)
|
||||
- QR Code (quando aplicável)
|
||||
|
||||
## 4. Validações
|
||||
|
||||
### 4.1 Obrigatoriedades
|
||||
- Um comprovante deve ter pelo menos uma centralização
|
||||
- O valor total do comprovante deve ser igual à soma das centralizações
|
||||
- A data do comprovante não pode ser futura
|
||||
|
||||
### 4.2 Restrições
|
||||
- Não é permitido excluir comprovantes com centralizações já registradas
|
||||
- Não é permitido alterar valores de centralizações após confirmação
|
||||
- O militante associado deve estar ativo no sistema
|
||||
|
||||
## 5. Permissões
|
||||
|
||||
### 5.1 Acesso
|
||||
- Apenas usuários com permissão `MANAGE_MATERIALS` podem:
|
||||
- Criar comprovantes
|
||||
- Editar comprovantes
|
||||
- Excluir comprovantes
|
||||
- Visualizar lista de comprovantes
|
||||
|
||||
### 5.2 Restrições
|
||||
- Usuários só podem editar comprovantes de sua própria célula/setor/CR
|
||||
- Apenas administradores podem editar comprovantes de qualquer nível
|
||||
|
||||
## 6. Relacionamentos
|
||||
|
||||
### 6.1 Militante
|
||||
- Todo comprovante deve estar associado a um militante
|
||||
- O militante deve estar ativo no sistema
|
||||
- O militante deve pertencer a uma célula/setor/CR válido
|
||||
|
||||
### 6.2 Campanha Financeira
|
||||
- O comprovante pode estar associado a uma campanha financeira
|
||||
- A campanha deve estar ativa no período do comprovante
|
||||
- O valor do comprovante é contabilizado no total da campanha
|
||||
|
||||
## 7. Histórico
|
||||
|
||||
### 7.1 Registro
|
||||
- Todas as alterações em comprovantes devem ser registradas
|
||||
- O sistema mantém histórico de:
|
||||
- Data de criação
|
||||
- Usuário que criou
|
||||
- Data de alteração
|
||||
- Usuário que alterou
|
||||
|
||||
### 7.2 Auditoria
|
||||
- Os comprovantes são auditáveis
|
||||
- O sistema mantém logs de todas as operações
|
||||
- As alterações podem ser rastreadas por usuário e data
|
||||
84
functions/controle.py
Normal file
84
functions/controle.py
Normal file
@@ -0,0 +1,84 @@
|
||||
from datetime import datetime, UTC
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from functions.database import get_db_connection, Controle as ControleModel
|
||||
|
||||
class Controle:
|
||||
def __init__(self):
|
||||
self.db = get_db_connection()
|
||||
|
||||
def registrar_controle(self, militante_id: int, tipo: str, valor: float, observacao: str = None) -> bool:
|
||||
"""
|
||||
Registra um novo controle no sistema
|
||||
|
||||
Args:
|
||||
militante_id: ID do militante
|
||||
tipo: Tipo do controle (ex: 'pagamento', 'cota')
|
||||
valor: Valor do controle
|
||||
observacao: Observação opcional sobre o controle
|
||||
|
||||
Returns:
|
||||
bool: True se o controle foi registrado com sucesso, False caso contrário
|
||||
"""
|
||||
try:
|
||||
data_registro = datetime.now(UTC)
|
||||
|
||||
novo_controle = ControleModel(
|
||||
militante_id=militante_id,
|
||||
tipo=tipo,
|
||||
valor=valor,
|
||||
data_registro=data_registro,
|
||||
observacao=observacao
|
||||
)
|
||||
|
||||
self.db.add(novo_controle)
|
||||
self.db.commit()
|
||||
return True
|
||||
|
||||
except SQLAlchemyError as e:
|
||||
self.db.rollback()
|
||||
print(f"Erro ao registrar controle: {str(e)}")
|
||||
return False
|
||||
finally:
|
||||
self.db.close()
|
||||
|
||||
def listar_controles(self, militante_id: int = None) -> list:
|
||||
"""
|
||||
Lista os controles registrados no sistema
|
||||
|
||||
Args:
|
||||
militante_id: ID do militante para filtrar (opcional)
|
||||
|
||||
Returns:
|
||||
list: Lista de controles encontrados
|
||||
"""
|
||||
try:
|
||||
query = self.db.query(ControleModel)
|
||||
|
||||
if militante_id:
|
||||
query = query.filter(ControleModel.militante_id == militante_id)
|
||||
|
||||
return query.all()
|
||||
|
||||
except SQLAlchemyError as e:
|
||||
print(f"Erro ao listar controles: {str(e)}")
|
||||
return []
|
||||
finally:
|
||||
self.db.close()
|
||||
|
||||
def buscar_controle(self, controle_id: int) -> ControleModel:
|
||||
"""
|
||||
Busca um controle específico pelo ID
|
||||
|
||||
Args:
|
||||
controle_id: ID do controle
|
||||
|
||||
Returns:
|
||||
ControleModel: Objeto do controle encontrado ou None
|
||||
"""
|
||||
try:
|
||||
return self.db.query(ControleModel).filter(ControleModel.id == controle_id).first()
|
||||
except SQLAlchemyError as e:
|
||||
print(f"Erro ao buscar controle: {str(e)}")
|
||||
return None
|
||||
finally:
|
||||
self.db.close()
|
||||
@@ -14,17 +14,24 @@ from flask_login import UserMixin
|
||||
from .rbac import Role, Permission, role_permissions, user_roles
|
||||
from .base import Base, engine, Session
|
||||
import logging
|
||||
import qrcode
|
||||
from PIL import Image
|
||||
import re
|
||||
|
||||
# Configurar caminho do banco de dados
|
||||
db_dir = Path.home() / '.local' / 'share' / 'controles'
|
||||
db_dir.mkdir(parents=True, exist_ok=True)
|
||||
db_path = db_dir / 'database.db'
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine)
|
||||
DATABASE_URL = f"sqlite:///{db_path}"
|
||||
engine = create_engine(DATABASE_URL)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
def get_db_connection():
|
||||
"""Retorna uma nova conexão com o banco de dados"""
|
||||
db = SessionLocal()
|
||||
"""Retorna uma nova sessão do banco de dados"""
|
||||
Session = sessionmaker(bind=engine)
|
||||
db = Session()
|
||||
|
||||
try:
|
||||
# Configurar SQLite para melhor tratamento de concorrência
|
||||
db.execute(text("PRAGMA journal_mode=WAL"))
|
||||
@@ -60,10 +67,10 @@ class Celula(Base):
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
nome = Column(String(100), nullable=False)
|
||||
setor_id = Column(Integer, ForeignKey('setores.id'))
|
||||
cr_id = Column(Integer, ForeignKey('comites_regionais.id'))
|
||||
secretario = Column(Integer, ForeignKey('militantes.id'))
|
||||
responsavel_financas = Column(Integer, ForeignKey('militantes.id'))
|
||||
setor_id = Column(Integer, ForeignKey('setores.id', use_alter=True, name='fk_celula_setor'))
|
||||
cr_id = Column(Integer, ForeignKey('comites_regionais.id', use_alter=True, name='fk_celula_cr'))
|
||||
secretario = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_celula_secretario'))
|
||||
responsavel_financas = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_celula_responsavel_financas'))
|
||||
quadro_orientador = Column(String(255))
|
||||
|
||||
# Relacionamentos
|
||||
@@ -80,10 +87,10 @@ class ComiteRegional(Base):
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
nome = Column(String(100), nullable=False)
|
||||
responsavel_financas = Column(Integer, ForeignKey('militantes.id'))
|
||||
responsavel_formacao = Column(Integer, ForeignKey('militantes.id'))
|
||||
secretario_organizacao = Column(Integer, ForeignKey('militantes.id'))
|
||||
correspondente_jornal = Column(Integer, ForeignKey('militantes.id'))
|
||||
responsavel_financas = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_cr_responsavel_financas'))
|
||||
responsavel_formacao = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_cr_responsavel_formacao'))
|
||||
secretario_organizacao = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_cr_secretario_organizacao'))
|
||||
correspondente_jornal = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_cr_correspondente_jornal'))
|
||||
|
||||
# Relacionamentos
|
||||
responsavel_financas_rel = relationship("Militante", foreign_keys=[responsavel_financas])
|
||||
@@ -141,7 +148,7 @@ class Militante(Base):
|
||||
# Relacionamento para múltiplos emails
|
||||
emails = relationship("EmailMilitante", back_populates="militante")
|
||||
# Endereço
|
||||
endereco_id = Column(Integer, ForeignKey('enderecos.id'))
|
||||
endereco_id = Column(Integer, ForeignKey('enderecos.id', use_alter=True, name='fk_militante_endereco'))
|
||||
endereco = relationship("Endereco", back_populates="militantes")
|
||||
# Redes sociais
|
||||
redes_sociais = relationship("RedeSocial", back_populates="militante")
|
||||
@@ -159,9 +166,9 @@ class Militante(Base):
|
||||
dirigente_sindical = Column(Boolean)
|
||||
central_sindical = Column(String(100))
|
||||
# Responsável pelo cadastro
|
||||
registrado_por = Column(Integer, ForeignKey('militantes.id'))
|
||||
registrado_por = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_militante_registrado_por'))
|
||||
# Campos existentes
|
||||
celula_id = Column(Integer, ForeignKey('celulas.id'))
|
||||
celula_id = Column(Integer, ForeignKey('celulas.id', use_alter=True, name='fk_militante_celula'))
|
||||
responsabilidades = Column(Integer, default=0)
|
||||
otp_secret = Column(String(32))
|
||||
temp_token = Column(String(64))
|
||||
@@ -186,6 +193,7 @@ class Militante(Base):
|
||||
vendas_jornais = relationship("VendaJornalAvulso", back_populates="militante")
|
||||
assinaturas = relationship("AssinaturaAnual", back_populates="militante")
|
||||
celula = relationship("Celula", back_populates="militantes", foreign_keys=[celula_id])
|
||||
comprovantes = relationship("Comprovante", back_populates="militante")
|
||||
|
||||
# Constantes para responsabilidades
|
||||
SECRETARIO = 1
|
||||
@@ -324,7 +332,6 @@ class Pagamento(Base):
|
||||
data_pagamento = Column(Date, nullable=False)
|
||||
|
||||
militante = relationship("Militante", back_populates="pagamentos")
|
||||
transacoes_pix = relationship("TransacaoPIX", back_populates="pagamento")
|
||||
|
||||
class TipoMaterial(Base):
|
||||
__tablename__ = 'tipos_materiais'
|
||||
@@ -378,9 +385,9 @@ class Setor(Base):
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
nome = Column(String(100), nullable=False)
|
||||
cr_id = Column(Integer, ForeignKey('comites_regionais.id'))
|
||||
responsavel = Column(Integer, ForeignKey('militantes.id'))
|
||||
responsavel_financas = Column(Integer, ForeignKey('militantes.id'))
|
||||
cr_id = Column(Integer, ForeignKey('comites_regionais.id', use_alter=True, name='fk_setor_cr'))
|
||||
responsavel = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_setor_responsavel'))
|
||||
responsavel_financas = Column(Integer, ForeignKey('militantes.id', use_alter=True, name='fk_setor_responsavel_financas'))
|
||||
|
||||
# Relacionamentos
|
||||
cr = relationship("ComiteRegional", back_populates="setores")
|
||||
@@ -603,6 +610,49 @@ class Relatorio(Base):
|
||||
setor = relationship("Setor", foreign_keys=[setor_id])
|
||||
cr = relationship("ComiteRegional", foreign_keys=[cr_id])
|
||||
|
||||
class CampanhaFinanceira(Base):
|
||||
__tablename__ = 'campanhas_financeiras'
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
nome = Column(String(100), nullable=False)
|
||||
descricao = Column(Text)
|
||||
data_inicio = Column(Date, nullable=False)
|
||||
data_fim = Column(Date, nullable=False)
|
||||
meta = Column(Numeric(10, 2), nullable=False)
|
||||
valor_arrecadado = Column(Numeric(10, 2), default=0)
|
||||
status = Column(String(20), default='Em andamento') # Em andamento, Concluída, Cancelada
|
||||
|
||||
comprovantes = relationship("Comprovante", back_populates="campanha")
|
||||
|
||||
class TipoComprovante(Base):
|
||||
__tablename__ = 'tipos_comprovante'
|
||||
id = Column(Integer, primary_key=True)
|
||||
descricao = Column(String(50), nullable=False)
|
||||
valor = Column(Numeric(10, 2), nullable=False)
|
||||
|
||||
class CentralizacaoComprovante(Base):
|
||||
__tablename__ = 'centralizacoes_comprovante'
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
comprovante_id = Column(Integer, ForeignKey('comprovantes.id'), nullable=False)
|
||||
tipo_comprovante = Column(String(50), nullable=False) # Cota, Jornal, Assinatura, etc.
|
||||
valor = Column(Numeric(10, 2), nullable=False)
|
||||
|
||||
comprovante = relationship("Comprovante", back_populates="centralizacoes")
|
||||
|
||||
class Comprovante(Base):
|
||||
__tablename__ = 'comprovantes'
|
||||
id = Column(Integer, primary_key=True)
|
||||
militante_id = Column(Integer, ForeignKey('militantes.id'), nullable=False)
|
||||
data_comprovante = Column(Date, nullable=False)
|
||||
forma_pagamento = Column(String(20), nullable=False) # PIX, transferência/DOC, depósito, maquininha
|
||||
campanha_id = Column(Integer, ForeignKey('campanhas_financeiras.id'))
|
||||
|
||||
militante = relationship("Militante", back_populates="comprovantes")
|
||||
transacoes_pix = relationship("TransacaoPIX", back_populates="comprovante")
|
||||
campanha = relationship("CampanhaFinanceira", back_populates="comprovantes")
|
||||
centralizacoes = relationship("CentralizacaoComprovante", back_populates="comprovante", cascade="all, delete-orphan")
|
||||
|
||||
class TransacaoPIX(Base):
|
||||
__tablename__ = 'transacoes_pix'
|
||||
|
||||
@@ -613,9 +663,9 @@ class TransacaoPIX(Base):
|
||||
data_pagamento = Column(DateTime)
|
||||
status = Column(String(20)) # Pendente, Pago, Expirado
|
||||
qr_code = Column(Text)
|
||||
pagamento_id = Column(Integer, ForeignKey('pagamentos.id'))
|
||||
comprovante_id = Column(Integer, ForeignKey('comprovantes.id'))
|
||||
|
||||
pagamento = relationship("Pagamento", back_populates="transacoes_pix")
|
||||
comprovante = relationship("Comprovante", back_populates="transacoes_pix")
|
||||
|
||||
def init_database():
|
||||
"""Inicializa o banco de dados com dados básicos"""
|
||||
@@ -623,10 +673,6 @@ def init_database():
|
||||
|
||||
session = get_db_connection()
|
||||
try:
|
||||
# Configurar SQLite para melhor tratamento de concorrência
|
||||
session.execute(text("PRAGMA journal_mode=WAL"))
|
||||
session.execute(text("PRAGMA busy_timeout=5000"))
|
||||
|
||||
# Criar todas as tabelas
|
||||
Base.metadata.drop_all(engine) # Remover todas as tabelas existentes
|
||||
Base.metadata.create_all(engine)
|
||||
@@ -660,23 +706,28 @@ def init_database():
|
||||
session.add(comite)
|
||||
session.commit()
|
||||
|
||||
# Verificar se existe um QR code salvo
|
||||
qr_path = Path('admin_qr.png')
|
||||
# Verificar se existe QR code do admin
|
||||
admin_otp_secret = None
|
||||
qr_path = 'admin_qr.png'
|
||||
|
||||
if qr_path.exists():
|
||||
if os.path.exists(qr_path):
|
||||
try:
|
||||
import re
|
||||
with open('admin_qr.txt', 'r') as f:
|
||||
qr_content = f.read()
|
||||
match = re.search(r'secret=([A-Z0-9]+)&', qr_content)
|
||||
# Tentar ler o QR code existente
|
||||
from pyzbar.pyzbar import decode
|
||||
qr_data = decode(Image.open(qr_path))
|
||||
if qr_data:
|
||||
# O URI do OTP está no formato: otpauth://totp/Sistema%20de%20Controles:admin?secret=XXXXX&issuer=Sistema%20de%20Controles
|
||||
uri = qr_data[0].data.decode('utf-8')
|
||||
# Extrair o secret do URI
|
||||
match = re.search(r'secret=([A-Z0-9]+)', uri)
|
||||
if match:
|
||||
admin_otp_secret = match.group(1)
|
||||
print(f"Usando OTP existente: {admin_otp_secret}")
|
||||
print("OTP existente encontrado no QR code")
|
||||
except Exception as e:
|
||||
print(f"Erro ao ler OTP existente: {e}")
|
||||
print(f"Erro ao ler QR code existente: {e}")
|
||||
|
||||
if not admin_otp_secret:
|
||||
# Se não conseguiu ler o QR code ou ele não existe, gera um novo
|
||||
admin_otp_secret = pyotp.random_base32()
|
||||
print(f"Novo OTP gerado: {admin_otp_secret}")
|
||||
|
||||
@@ -697,26 +748,22 @@ def init_database():
|
||||
session.add(admin)
|
||||
session.commit()
|
||||
|
||||
# Gerar novo QR code se não existir
|
||||
if not qr_path.exists():
|
||||
# Gerar QR code apenas se não existir
|
||||
if not os.path.exists(qr_path):
|
||||
totp = pyotp.totp.TOTP(admin_otp_secret)
|
||||
provisioning_uri = totp.provisioning_uri("admin", issuer_name="Sistema de Controles")
|
||||
|
||||
with open('admin_qr.txt', 'w') as f:
|
||||
f.write(provisioning_uri)
|
||||
|
||||
import qrcode
|
||||
qr = qrcode.QRCode(version=1, box_size=10, border=5)
|
||||
qr.add_data(provisioning_uri)
|
||||
qr.make(fit=True)
|
||||
img = qr.make_image(fill_color="black", back_color="white")
|
||||
img.save('admin_qr.png')
|
||||
img.save(qr_path)
|
||||
|
||||
print("=== Usuário Admin Criado ===")
|
||||
print(f"Username: admin")
|
||||
print(f"Senha: admin123")
|
||||
print(f"Email: {admin.email}")
|
||||
print(f"OTP Secret: {admin.otp_secret}")
|
||||
print(f"OTP Secret: {admin_otp_secret}")
|
||||
print(f"QR Code: {qr_path}")
|
||||
|
||||
# Importar e executar o seed após criar todas as dependências
|
||||
|
||||
1
functions/notificacao.py
Normal file
1
functions/notificacao.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
@@ -68,6 +68,8 @@ class Permission(Base):
|
||||
EDIT_OWN_DATA = "edit_own_data"
|
||||
VIEW_CELL_DATA = "view_cell_data"
|
||||
CREATE_MILITANT = "create_militant" # Nova permissão para criar militantes
|
||||
MANAGE_MATERIALS = "manage_materials" # Nova permissão para gerenciar materiais
|
||||
MANAGE_REPORTS = "manage_reports" # Nova permissão para gerenciar relatórios
|
||||
|
||||
# Permissões de célula
|
||||
MANAGE_CELL_MEMBERS = "manage_cell_members"
|
||||
@@ -102,13 +104,15 @@ class Permission(Base):
|
||||
(Permission.VIEW_OWN_DATA, "Visualizar próprios dados"),
|
||||
(Permission.EDIT_OWN_DATA, "Editar próprios dados"),
|
||||
(Permission.VIEW_CELL_DATA, "Visualizar dados da célula"),
|
||||
(Permission.CREATE_MILITANT, "Criar novos militantes"), # Nova permissão
|
||||
(Permission.CREATE_MILITANT, "Criar novos militantes"),
|
||||
(Permission.MANAGE_MATERIALS, "Gerenciar materiais"),
|
||||
(Permission.MANAGE_REPORTS, "Gerenciar relatórios"),
|
||||
|
||||
# Permissões de célula
|
||||
(Permission.MANAGE_CELL_MEMBERS, "Gerenciar membros da célula"),
|
||||
(Permission.CREATE_CELL_MEMBER, "Criar membros na célula"),
|
||||
(Permission.VIEW_CELL_REPORTS, "Visualizar relatórios da célula"),
|
||||
(Permission.MANAGE_CELL_REPORTS, "Gerenciar relatórios da célula"), # Nova permissão
|
||||
(Permission.MANAGE_CELL_REPORTS, "Gerenciar relatórios da célula"),
|
||||
(Permission.REGISTER_CELL_PAYMENT, "Registrar pagamentos da célula"),
|
||||
|
||||
# Permissões de setor
|
||||
@@ -193,7 +197,8 @@ def init_rbac():
|
||||
session.query(Permission).filter_by(nome=Permission.CREATE_CELL_MEMBER).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.VIEW_CELL_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_CELL_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CELL_PAYMENT).first()
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CELL_PAYMENT).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_MATERIALS).first()
|
||||
]
|
||||
|
||||
# Membro de Setor
|
||||
@@ -207,7 +212,8 @@ def init_rbac():
|
||||
session.query(Permission).filter_by(nome=Permission.VIEW_CELL_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_CELL_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.VIEW_SECTOR_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_SECTOR_PAYMENT).first()
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_SECTOR_PAYMENT).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_MATERIALS).first()
|
||||
]
|
||||
|
||||
# Secretário de Setor
|
||||
@@ -223,7 +229,8 @@ def init_rbac():
|
||||
session.query(Permission).filter_by(nome=Permission.VIEW_SECTOR_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_SECTOR_CELLS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.CREATE_SECTOR_CELL).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_SECTOR_PAYMENT).first()
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_SECTOR_PAYMENT).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_MATERIALS).first()
|
||||
]
|
||||
|
||||
# Membro de CR
|
||||
@@ -240,7 +247,8 @@ def init_rbac():
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_SECTOR_CELLS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.CREATE_SECTOR_CELL).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.VIEW_CR_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CR_PAYMENT).first()
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CR_PAYMENT).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_MATERIALS).first()
|
||||
]
|
||||
|
||||
# Secretário de CR
|
||||
@@ -259,7 +267,8 @@ def init_rbac():
|
||||
session.query(Permission).filter_by(nome=Permission.VIEW_CR_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_CR_SECTORS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.CREATE_CR_SECTOR).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CR_PAYMENT).first()
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CR_PAYMENT).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_MATERIALS).first()
|
||||
]
|
||||
|
||||
# Membro do CC
|
||||
@@ -279,7 +288,8 @@ def init_rbac():
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_CR_SECTORS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.CREATE_CR_SECTOR).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.VIEW_CC_REPORTS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CC_PAYMENT).first()
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CC_PAYMENT).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_MATERIALS).first()
|
||||
]
|
||||
|
||||
# Secretário Geral
|
||||
@@ -302,7 +312,8 @@ def init_rbac():
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_CC_CRS).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.CREATE_CC_CR).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.REGISTER_CC_PAYMENT).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.SYSTEM_CONFIG).first()
|
||||
session.query(Permission).filter_by(nome=Permission.SYSTEM_CONFIG).first(),
|
||||
session.query(Permission).filter_by(nome=Permission.MANAGE_MATERIALS).first()
|
||||
]
|
||||
|
||||
session.commit()
|
||||
|
||||
1
functions/relatorio.py
Normal file
1
functions/relatorio.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
23
functions/usuario.py
Normal file
23
functions/usuario.py
Normal file
@@ -0,0 +1,23 @@
|
||||
def get_permissoes_por_cargo(cargo_id):
|
||||
permissoes = {
|
||||
1: [ # Secretário Geral
|
||||
'gerenciar_relatorios_celula',
|
||||
'visualizar_relatorios_celula',
|
||||
'gerenciar_militantes',
|
||||
'gerenciar_tipos_comprovante'
|
||||
],
|
||||
2: [ # Admin
|
||||
'gerenciar_relatorios_celula',
|
||||
'visualizar_relatorios_celula',
|
||||
'gerenciar_militantes',
|
||||
'gerenciar_tipos_comprovante'
|
||||
],
|
||||
3: [ # Secretário Financeiro do Comitê Central
|
||||
'gerenciar_relatorios_celula',
|
||||
'visualizar_relatorios_celula',
|
||||
'gerenciar_militantes',
|
||||
'gerenciar_tipos_comprovante'
|
||||
],
|
||||
# ... existing code ...
|
||||
}
|
||||
return permissoes.get(cargo_id, [])
|
||||
19
init_db.py
Normal file
19
init_db.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from functions.database import init_database
|
||||
from functions.rbac import init_rbac
|
||||
from create_admin import create_admin_user
|
||||
from create_test_users import create_test_users
|
||||
|
||||
def init_system():
|
||||
print("Inicializando banco de dados...")
|
||||
init_database()
|
||||
|
||||
print("Inicializando sistema RBAC...")
|
||||
init_rbac()
|
||||
|
||||
print("Criando usuários iniciais...")
|
||||
create_admin_user()
|
||||
create_test_users()
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_system()
|
||||
print("Sistema inicializado com sucesso!")
|
||||
23
models.py
23
models.py
@@ -1,23 +0,0 @@
|
||||
from sqlalchemy import Column, Integer, String, Date, Float, Boolean, ForeignKey, Table, Enum, DateTime
|
||||
from sqlalchemy.orm import relationship, declarative_base
|
||||
from sqlalchemy.sql import func
|
||||
from datetime import datetime, date
|
||||
import enum
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
class AssinaturaAnual(Base):
|
||||
__tablename__ = 'assinaturas_anuais'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
militante_id = Column(Integer, ForeignKey('militantes.id'), nullable=False)
|
||||
data_inicio = Column(Date, nullable=False)
|
||||
data_fim = Column(Date, nullable=False)
|
||||
valor = Column(Float, nullable=False)
|
||||
|
||||
militante = relationship('Militante', backref='assinaturas')
|
||||
|
||||
@property
|
||||
def ativa(self):
|
||||
hoje = date.today()
|
||||
return self.data_inicio <= hoje <= self.data_fim
|
||||
@@ -15,3 +15,8 @@ bcrypt==4.1.2
|
||||
Bootstrap-Flask==2.3.3
|
||||
flask-bootstrap5==0.1.dev1
|
||||
PyJWT==2.8.0
|
||||
gunicorn==21.2.0
|
||||
Faker==19.13.0
|
||||
pytest==8.0.0
|
||||
pytest-cov==4.1.0
|
||||
pyzbar==0.1.9
|
||||
|
||||
32
seed.py
32
seed.py
@@ -1,32 +0,0 @@
|
||||
from seed_data import seed_database
|
||||
from functions.database import Base, engine, get_db_connection
|
||||
import time
|
||||
import os
|
||||
|
||||
def wait_for_db():
|
||||
db_path = os.path.expanduser("~/.local/share/controles/database.db")
|
||||
max_attempts = 30
|
||||
attempt = 0
|
||||
|
||||
while attempt < max_attempts:
|
||||
if os.path.exists(db_path):
|
||||
try:
|
||||
db = get_db_connection()
|
||||
db.execute("SELECT 1")
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
print(f"Aguardando banco de dados... tentativa {attempt + 1}/{max_attempts}")
|
||||
time.sleep(1)
|
||||
attempt += 1
|
||||
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Aguardando banco de dados estar pronto...")
|
||||
if wait_for_db():
|
||||
print("Iniciando população do banco de dados...")
|
||||
seed_database()
|
||||
print("Banco de dados populado com sucesso!")
|
||||
else:
|
||||
print("Erro: Banco de dados não ficou pronto a tempo.")
|
||||
354
seed_data.py
354
seed_data.py
@@ -1,32 +1,86 @@
|
||||
from datetime import datetime, timedelta
|
||||
from functions.database import (
|
||||
Base, Militante, CotaMensal, TipoPagamento, Pagamento,
|
||||
Base, Militante, CotaMensal, TipoComprovante, Comprovante,
|
||||
MaterialVendido, TipoMaterial, VendaJornalAvulso, AssinaturaAnual,
|
||||
RelatorioCotasMensais, RelatorioVendasMateriais, engine, SessionLocal,
|
||||
Setor, ComiteCentral, Usuario, Role, EmailMilitante, Endereco
|
||||
Setor, ComiteCentral, Usuario, Role, EmailMilitante, Endereco,
|
||||
ComiteRegional, Celula, EstadoMilitante, get_db_connection,
|
||||
init_database, CentralizacaoComprovante
|
||||
)
|
||||
import random
|
||||
from faker import Faker
|
||||
import time
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
fake = Faker('pt_BR')
|
||||
|
||||
def criar_tipos_pagamento(session):
|
||||
"""Cria tipos de pagamento padrão"""
|
||||
tipos = [
|
||||
"Dinheiro",
|
||||
"PIX",
|
||||
"Cartão de Crédito",
|
||||
"Cartão de Débito",
|
||||
"Transferência Bancária"
|
||||
]
|
||||
for tipo in tipos:
|
||||
if not session.query(TipoPagamento).filter_by(descricao=tipo).first():
|
||||
session.add(TipoPagamento(descricao=tipo))
|
||||
def criar_estrutura_organizacional(session):
|
||||
"""Cria a estrutura organizacional básica"""
|
||||
print("\nCriando estrutura organizacional...")
|
||||
|
||||
# Criar Comitê Central
|
||||
cc = ComiteCentral(nome="Comitê Central SP")
|
||||
session.add(cc)
|
||||
session.flush()
|
||||
|
||||
# Criar Comitês Regionais
|
||||
crs = []
|
||||
for nome in ["CR São Paulo", "CR ABC", "CR Campinas"]:
|
||||
cr = ComiteRegional(nome=nome)
|
||||
session.add(cr)
|
||||
session.flush()
|
||||
crs.append(cr)
|
||||
|
||||
# Criar Setores para cada CR
|
||||
setores = []
|
||||
for cr in crs:
|
||||
for i in range(2): # 2 setores por CR
|
||||
setor = Setor(
|
||||
nome=f"Setor {i+1} - {cr.nome}",
|
||||
cr_id=cr.id
|
||||
)
|
||||
session.add(setor)
|
||||
session.flush()
|
||||
setores.append(setor)
|
||||
|
||||
# Criar Células para cada Setor
|
||||
for setor in setores:
|
||||
for i in range(2): # 2 células por setor
|
||||
celula = Celula(
|
||||
nome=f"Célula {i+1} - {setor.nome}",
|
||||
setor_id=setor.id
|
||||
)
|
||||
session.add(celula)
|
||||
|
||||
session.commit()
|
||||
return crs, setores
|
||||
|
||||
def criar_tipos_comprovante(session):
|
||||
"""Cria tipos de comprovante padrão"""
|
||||
print("\nCriando tipos de comprovante...")
|
||||
tipos = [
|
||||
("Comprovante Padrão", 50.00),
|
||||
("Comprovante Especial", 100.00),
|
||||
("Comprovante Extraordinário", 200.00),
|
||||
("Jornal Avulso", 5.00),
|
||||
("Assinatura de Jornal", 30.00),
|
||||
("Campanha Financeira", 0.00) # Valor variável
|
||||
]
|
||||
|
||||
for descricao, valor in tipos:
|
||||
if not session.query(TipoComprovante).filter_by(descricao=descricao).first():
|
||||
session.add(TipoComprovante(descricao=descricao, valor=valor))
|
||||
|
||||
try:
|
||||
session.commit()
|
||||
print("Tipos de comprovante criados com sucesso!")
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f"Erro ao criar tipos de comprovante: {e}")
|
||||
|
||||
def criar_tipos_material(session):
|
||||
"""Cria tipos de material padrão"""
|
||||
print("\nCriando tipos de material...")
|
||||
tipos = [
|
||||
"Jornal",
|
||||
"Revista",
|
||||
@@ -39,42 +93,66 @@ def criar_tipos_material(session):
|
||||
session.add(TipoMaterial(descricao=tipo))
|
||||
session.commit()
|
||||
|
||||
def criar_militantes(session, num_militantes):
|
||||
def criar_militantes(session, num_militantes, setores):
|
||||
"""Cria militantes com todos os dados necessários"""
|
||||
print(f"\nCriando {num_militantes} militantes...")
|
||||
militantes = []
|
||||
emails_usados = set()
|
||||
|
||||
# Obter um setor existente
|
||||
setor = session.query(Setor).first()
|
||||
if not setor:
|
||||
print("Erro: Nenhum setor encontrado!")
|
||||
return []
|
||||
|
||||
for i in range(num_militantes):
|
||||
try:
|
||||
# Dados básicos
|
||||
nome = fake.name()
|
||||
cpf = fake.cpf()
|
||||
|
||||
# Email único
|
||||
while True:
|
||||
email = fake.email()
|
||||
if email not in emails_usados:
|
||||
emails_usados.add(email)
|
||||
break
|
||||
|
||||
# Criar endereço
|
||||
endereco = Endereco(
|
||||
cep=fake.postcode(),
|
||||
estado=fake.estado_sigla(),
|
||||
cidade=fake.city(),
|
||||
bairro=fake.bairro(),
|
||||
rua=fake.street_name(),
|
||||
numero=str(random.randint(1, 999)),
|
||||
complemento=f"Bloco {random.randint(1, 10)}, Apto {random.randint(1, 999)}" if random.random() < 0.3 else None,
|
||||
cep=fake.postcode()
|
||||
complemento=f"Bloco {random.randint(1, 10)}, Apto {random.randint(1, 999)}" if random.random() < 0.3 else None
|
||||
)
|
||||
session.add(endereco)
|
||||
session.flush()
|
||||
|
||||
print(f"Criando militante {i+1}: {nome} (CPF: {cpf})")
|
||||
# Selecionar setor e célula aleatórios
|
||||
setor = random.choice(setores)
|
||||
celula = random.choice(session.query(Celula).filter_by(setor_id=setor.id).all())
|
||||
|
||||
# Definir responsabilidades
|
||||
responsabilidades = 0
|
||||
if random.random() < 0.2: # 20% chance de ser Responsável de Finanças
|
||||
responsabilidades |= Militante.RESPONSAVEL_FINANCAS
|
||||
if random.random() < 0.2: # 20% chance de ser Responsável de Imprensa
|
||||
responsabilidades |= Militante.RESPONSAVEL_IMPRENSA
|
||||
if random.random() < 0.2: # 20% chance de ser Quadro-Orientador
|
||||
responsabilidades |= Militante.QUADRO_ORIENTADOR
|
||||
if random.random() < 0.2: # 20% chance de ser Secretário
|
||||
responsabilidades |= Militante.SECRETARIO
|
||||
if random.random() < 0.2: # 20% chance de ser MPS
|
||||
responsabilidades |= Militante.MPS
|
||||
if random.random() < 0.2: # 20% chance de ser Tesoureiro
|
||||
responsabilidades |= Militante.TESOUREIRO
|
||||
if random.random() < 0.2: # 20% chance de ser MNS
|
||||
responsabilidades |= Militante.MNS
|
||||
if random.random() < 0.2: # 20% chance de ser da Juventude
|
||||
responsabilidades |= Militante.JUVENTUDE
|
||||
if random.random() < 0.3: # 30% chance de ser Aspirante
|
||||
responsabilidades |= Militante.ASPIRANTE
|
||||
|
||||
print(f"Criando militante {i+1}: {nome}")
|
||||
|
||||
# Criar militante com todos os dados
|
||||
militante = Militante(
|
||||
nome=nome,
|
||||
cpf=cpf,
|
||||
@@ -95,11 +173,14 @@ def criar_militantes(session, num_militantes):
|
||||
dirigente_sindical=random.random() < 0.2,
|
||||
central_sindical=random.choice(['CUT', 'CSP-Conlutas', 'CTB', 'Força Sindical']) if random.random() < 0.4 else None,
|
||||
endereco_id=endereco.id,
|
||||
responsabilidades=random.randint(0, 1023)
|
||||
celula_id=celula.id,
|
||||
responsabilidades=responsabilidades,
|
||||
estado=random.choice(list(EstadoMilitante))
|
||||
)
|
||||
session.add(militante)
|
||||
session.flush()
|
||||
|
||||
# Criar email do militante
|
||||
email_militante = EmailMilitante(
|
||||
militante_id=militante.id,
|
||||
endereco_email=email
|
||||
@@ -107,8 +188,6 @@ def criar_militantes(session, num_militantes):
|
||||
session.add(email_militante)
|
||||
|
||||
militantes.append(militante)
|
||||
|
||||
# Commit a cada militante para evitar transações muito longas
|
||||
session.commit()
|
||||
|
||||
except Exception as e:
|
||||
@@ -118,12 +197,13 @@ def criar_militantes(session, num_militantes):
|
||||
|
||||
return militantes
|
||||
|
||||
def criar_cotas(session, militantes, quantidade_por_militante=3):
|
||||
print(f"Criando {quantidade_por_militante} cotas para cada um dos {len(militantes)} militantes...")
|
||||
def criar_cotas(session, militantes):
|
||||
"""Cria cotas mensais para os militantes"""
|
||||
print("\nCriando cotas mensais...")
|
||||
for militante in militantes:
|
||||
try:
|
||||
print(f"Criando cotas para militante {militante.nome}")
|
||||
for i in range(quantidade_por_militante):
|
||||
# Criar 12 cotas (1 ano) para cada militante
|
||||
for i in range(12):
|
||||
data_base = datetime.now() - timedelta(days=30 * i)
|
||||
valor = random.uniform(50, 200)
|
||||
cota = CotaMensal(
|
||||
@@ -139,28 +219,49 @@ def criar_cotas(session, militantes, quantidade_por_militante=3):
|
||||
except Exception as e:
|
||||
print(f"Erro ao criar cotas para militante {militante.nome}: {e}")
|
||||
session.rollback()
|
||||
continue
|
||||
print("Cotas criadas com sucesso!")
|
||||
|
||||
def criar_pagamentos(militantes):
|
||||
"""Cria pagamentos fictícios"""
|
||||
tipos_pagamento = ["Cota", "Jornal", "Assinatura", "Campanha Financeira"]
|
||||
def criar_comprovantes(session, militantes):
|
||||
"""Cria comprovantes para os militantes"""
|
||||
print("\nCriando comprovantes...")
|
||||
tipos_comprovante = session.query(TipoComprovante).all()
|
||||
|
||||
for militante in militantes:
|
||||
for _ in range(random.randint(1, 5)):
|
||||
pagamento = Pagamento(
|
||||
try:
|
||||
# Criar entre 3 e 8 comprovantes por militante
|
||||
for _ in range(random.randint(3, 8)):
|
||||
# Criar o comprovante base
|
||||
comprovante = Comprovante(
|
||||
militante_id=militante.id,
|
||||
tipo_pagamento=random.choice(tipos_pagamento),
|
||||
valor=random.uniform(50, 500),
|
||||
data_pagamento=fake.date_between(start_date='-1y', end_date='today')
|
||||
data_comprovante=fake.date_between(start_date='-1y', end_date='today'),
|
||||
forma_pagamento=random.choice(['PIX', 'transferência/DOC', 'depósito', 'maquininha'])
|
||||
)
|
||||
db_session.add(pagamento)
|
||||
db_session.commit()
|
||||
session.add(comprovante)
|
||||
session.flush() # Para obter o ID do comprovante
|
||||
|
||||
# Criar a centralização para o comprovante
|
||||
tipo = random.choice(tipos_comprovante)
|
||||
valor = random.uniform(10, 1000)
|
||||
centralizacao = CentralizacaoComprovante(
|
||||
comprovante_id=comprovante.id,
|
||||
tipo_comprovante=tipo.descricao,
|
||||
valor=valor
|
||||
)
|
||||
session.add(centralizacao)
|
||||
|
||||
session.commit()
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
print(f"Erro ao criar comprovantes para militante {militante.nome}: {e}")
|
||||
|
||||
def criar_materiais_vendidos(session, militantes):
|
||||
"""Cria registros de materiais vendidos"""
|
||||
print("\nCriando materiais vendidos...")
|
||||
tipos_material = session.query(TipoMaterial).all()
|
||||
|
||||
def criar_materiais_vendidos(militantes):
|
||||
"""Cria materiais vendidos fictícios"""
|
||||
tipos_material = db_session.query(TipoMaterial).all()
|
||||
for militante in militantes:
|
||||
for _ in range(random.randint(1, 3)):
|
||||
try:
|
||||
# Criar entre 2 e 5 materiais vendidos por militante
|
||||
for _ in range(random.randint(2, 5)):
|
||||
material = MaterialVendido(
|
||||
militante_id=militante.id,
|
||||
tipo_material_id=random.choice(tipos_material).id,
|
||||
@@ -168,27 +269,42 @@ def criar_materiais_vendidos(militantes):
|
||||
valor=random.uniform(20, 100),
|
||||
data_venda=fake.date_time_between(start_date='-1y', end_date='now')
|
||||
)
|
||||
db_session.add(material)
|
||||
db_session.commit()
|
||||
session.add(material)
|
||||
session.commit()
|
||||
except Exception as e:
|
||||
print(f"Erro ao criar materiais vendidos para militante {militante.nome}: {e}")
|
||||
session.rollback()
|
||||
|
||||
def criar_vendas_jornal(militantes):
|
||||
"""Cria vendas de jornal avulso fictícias"""
|
||||
def criar_vendas_jornal(session, militantes):
|
||||
"""Cria vendas de jornal avulso"""
|
||||
print("\nCriando vendas de jornal...")
|
||||
for militante in militantes:
|
||||
for _ in range(random.randint(1, 4)):
|
||||
try:
|
||||
# Criar entre 2 e 6 vendas de jornal por militante
|
||||
for _ in range(random.randint(2, 6)):
|
||||
quantidade = random.randint(1, 10)
|
||||
valor_unitario = random.uniform(5, 15)
|
||||
venda = VendaJornalAvulso(
|
||||
militante_id=militante.id,
|
||||
quantidade=random.randint(1, 10),
|
||||
valor_total=random.uniform(10, 100),
|
||||
quantidade=quantidade,
|
||||
valor_total=quantidade * valor_unitario,
|
||||
data_venda=fake.date_time_between(start_date='-1y', end_date='now')
|
||||
)
|
||||
db_session.add(venda)
|
||||
db_session.commit()
|
||||
session.add(venda)
|
||||
session.commit()
|
||||
except Exception as e:
|
||||
print(f"Erro ao criar vendas de jornal para militante {militante.nome}: {e}")
|
||||
session.rollback()
|
||||
|
||||
def criar_assinaturas(session, militantes):
|
||||
"""Cria assinaturas anuais"""
|
||||
print("\nCriando assinaturas anuais...")
|
||||
tipos_material = session.query(TipoMaterial).all()
|
||||
|
||||
def criar_assinaturas(militantes):
|
||||
"""Cria assinaturas anuais fictícias"""
|
||||
tipos_material = db_session.query(TipoMaterial).all()
|
||||
for militante in militantes:
|
||||
if random.random() < 0.3: # 30% de chance de ter assinatura
|
||||
try:
|
||||
# 30% de chance de ter assinatura
|
||||
if random.random() < 0.3:
|
||||
data_inicio = fake.date_time_between(start_date='-1y', end_date='now')
|
||||
assinatura = AssinaturaAnual(
|
||||
militante_id=militante.id,
|
||||
@@ -198,105 +314,39 @@ def criar_assinaturas(militantes):
|
||||
data_inicio=data_inicio,
|
||||
data_fim=data_inicio + timedelta(days=365)
|
||||
)
|
||||
db_session.add(assinatura)
|
||||
db_session.commit()
|
||||
|
||||
def criar_relatorios():
|
||||
"""Cria relatórios fictícios"""
|
||||
for _ in range(12): # Um relatório por mês do último ano
|
||||
data = fake.date_time_between(start_date='-1y', end_date='now')
|
||||
|
||||
relatorio_cotas = RelatorioCotasMensais(
|
||||
setor_id=random.randint(1, 5),
|
||||
comite_id=random.randint(1, 3),
|
||||
total_cotas=random.uniform(1000, 5000),
|
||||
data_relatorio=data
|
||||
)
|
||||
|
||||
relatorio_vendas = RelatorioVendasMateriais(
|
||||
setor_id=random.randint(1, 5),
|
||||
comite_id=random.randint(1, 3),
|
||||
total_vendas=random.uniform(500, 3000),
|
||||
data_relatorio=data
|
||||
)
|
||||
|
||||
db_session.add(relatorio_cotas)
|
||||
db_session.add(relatorio_vendas)
|
||||
|
||||
db_session.commit()
|
||||
|
||||
def criar_setores():
|
||||
"""Cria setores padrão"""
|
||||
setores = [
|
||||
"Setor 1",
|
||||
"Setor 2",
|
||||
"Setor 3",
|
||||
"Setor 4",
|
||||
"Setor 5"
|
||||
]
|
||||
for setor in setores:
|
||||
if not db_session.query(Setor).filter_by(nome=setor).first():
|
||||
db_session.add(Setor(nome=setor))
|
||||
db_session.commit()
|
||||
|
||||
def criar_comites():
|
||||
"""Cria comitês padrão"""
|
||||
comites = [
|
||||
"Comitê 1",
|
||||
"Comitê 2",
|
||||
"Comitê 3"
|
||||
]
|
||||
for comite in comites:
|
||||
if not db_session.query(ComiteCentral).filter_by(nome=comite).first():
|
||||
db_session.add(ComiteCentral(nome=comite))
|
||||
db_session.commit()
|
||||
|
||||
def criar_roles():
|
||||
"""Cria roles padrão"""
|
||||
roles = [
|
||||
("admin", 1), # Nível 1: Administrador
|
||||
("gestor", 2), # Nível 2: Gestor
|
||||
("usuario", 3) # Nível 3: Usuário comum
|
||||
]
|
||||
for nome, nivel in roles:
|
||||
if not db_session.query(Role).filter_by(nome=nome).first():
|
||||
db_session.add(Role(nome=nome, nivel=nivel))
|
||||
db_session.commit()
|
||||
|
||||
def criar_usuario_admin():
|
||||
"""Cria usuário admin inicial"""
|
||||
if not db_session.query(Usuario).filter_by(username='admin').first():
|
||||
role_admin = db_session.query(Role).filter_by(nome='admin').first()
|
||||
setor = db_session.query(Setor).first()
|
||||
|
||||
admin = Usuario(
|
||||
username='admin',
|
||||
email='admin@example.com',
|
||||
is_admin=True,
|
||||
ativo=True,
|
||||
role_id=role_admin.id if role_admin else None,
|
||||
setor_id=setor.id if setor else None
|
||||
)
|
||||
admin.set_password('admin123') # Método que deve existir na classe Usuario
|
||||
db_session.add(admin)
|
||||
db_session.commit()
|
||||
print("Usuário admin criado com sucesso!")
|
||||
session.add(assinatura)
|
||||
session.commit()
|
||||
except Exception as e:
|
||||
print(f"Erro ao criar assinatura para militante {militante.nome}: {e}")
|
||||
session.rollback()
|
||||
|
||||
def seed_database():
|
||||
"""Função principal para popular o banco de dados com dados fictícios"""
|
||||
print("Populando banco de dados com dados fictícios...")
|
||||
|
||||
session = SessionLocal()
|
||||
"""Função principal para popular o banco de dados"""
|
||||
session = get_db_connection()
|
||||
try:
|
||||
criar_tipos_pagamento(session)
|
||||
print("Iniciando população do banco de dados...")
|
||||
|
||||
# Criar estrutura organizacional
|
||||
crs, setores = criar_estrutura_organizacional(session)
|
||||
|
||||
# Criar tipos básicos
|
||||
criar_tipos_comprovante(session)
|
||||
criar_tipos_material(session)
|
||||
|
||||
militantes = criar_militantes(session, 50)
|
||||
if militantes:
|
||||
# Criar militantes (30 militantes para teste)
|
||||
militantes = criar_militantes(session, 30, setores)
|
||||
|
||||
# Criar dados financeiros e materiais
|
||||
criar_cotas(session, militantes)
|
||||
print("Dados fictícios criados com sucesso!")
|
||||
criar_comprovantes(session, militantes)
|
||||
criar_materiais_vendidos(session, militantes)
|
||||
criar_vendas_jornal(session, militantes)
|
||||
criar_assinaturas(session, militantes)
|
||||
|
||||
print("\nBanco de dados populado com sucesso!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Erro ao popular banco de dados: {e}")
|
||||
print(f"Erro durante a população do banco: {e}")
|
||||
session.rollback()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
18
setup.py
18
setup.py
@@ -1,18 +0,0 @@
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="controles",
|
||||
version="0.1.0",
|
||||
packages=find_packages(),
|
||||
install_requires=[
|
||||
"fastapi",
|
||||
"uvicorn",
|
||||
"sqlalchemy",
|
||||
"python-jose[cryptography]",
|
||||
"passlib[bcrypt]",
|
||||
"python-multipart",
|
||||
"qrcode",
|
||||
"pillow",
|
||||
"python-dotenv"
|
||||
],
|
||||
)
|
||||
@@ -561,3 +561,51 @@ input.btn-secondary:hover,
|
||||
color: white !important;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
|
||||
}
|
||||
|
||||
/* Estilos para alertas */
|
||||
.alert {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 9999;
|
||||
min-width: 300px;
|
||||
max-width: 600px;
|
||||
text-align: center;
|
||||
padding: 1rem 2.5rem 1rem 1rem;
|
||||
margin: 0;
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.alert .btn-close {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 1rem;
|
||||
transform: translateY(-50%);
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.alert-success {
|
||||
color: #0f5132;
|
||||
background-color: #d1e7dd;
|
||||
border-color: #badbcc;
|
||||
}
|
||||
|
||||
.alert-danger {
|
||||
color: #842029;
|
||||
background-color: #f8d7da;
|
||||
border-color: #f5c2c7;
|
||||
}
|
||||
|
||||
.alert-warning {
|
||||
color: #664d03;
|
||||
background-color: #fff3cd;
|
||||
border-color: #ffecb5;
|
||||
}
|
||||
|
||||
.alert-info {
|
||||
color: #055160;
|
||||
background-color: #cff4fc;
|
||||
border-color: #b6effb;
|
||||
}
|
||||
53
static/css/styles.css
Normal file
53
static/css/styles.css
Normal file
@@ -0,0 +1,53 @@
|
||||
/* Estilos globais para alertas do sistema */
|
||||
.alert {
|
||||
position: relative;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
/* Estilo base para o botão de fechar */
|
||||
.alert .btn-close {
|
||||
filter: none;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Alert Success */
|
||||
.alert-success .btn-close {
|
||||
background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23198754'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
|
||||
}
|
||||
|
||||
/* Alert Danger */
|
||||
.alert-danger .btn-close {
|
||||
background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23842029'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
|
||||
}
|
||||
|
||||
/* Alert Warning */
|
||||
.alert-warning .btn-close {
|
||||
background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23997404'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
|
||||
}
|
||||
|
||||
/* Alert Info */
|
||||
.alert-info .btn-close {
|
||||
background: transparent url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23055160'%3e%3cpath d='M.293.293a1 1 0 011.414 0L8 6.586 14.293.293a1 1 0 111.414 1.414L9.414 8l6.293 6.293a1 1 0 01-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 01-1.414-1.414L6.586 8 .293 1.707a1 1 0 010-1.414z'/%3e%3c/svg%3e") center/1em auto no-repeat;
|
||||
}
|
||||
|
||||
/* Efeito hover para todos os botões de fechar */
|
||||
.alert .btn-close:hover {
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
/* Estilo das abas do modal */
|
||||
.nav-tabs .nav-link {
|
||||
/* remover estilos */
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link.active {
|
||||
/* remover estilos */
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link:hover:not(.active) {
|
||||
/* remover estilos */
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link i {
|
||||
/* remover estilos */
|
||||
}
|
||||
1
static/img/favicon.ico
Normal file
1
static/img/favicon.ico
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
51
static/js/comprovantes.js
Normal file
51
static/js/comprovantes.js
Normal file
@@ -0,0 +1,51 @@
|
||||
$(document).ready(function() {
|
||||
// Inicialização da tabela
|
||||
$('#tabelaComprovantes').DataTable({
|
||||
language: {
|
||||
url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/pt-BR.json'
|
||||
}
|
||||
});
|
||||
|
||||
// Modal de edição
|
||||
$('#modalEditarComprovante').on('show.bs.modal', function(event) {
|
||||
var button = $(event.relatedTarget);
|
||||
var comprovanteId = button.data('comprovante-id');
|
||||
var militanteId = button.data('militante-id');
|
||||
var militanteNome = button.data('militante-nome');
|
||||
var tipoComprovante = button.data('tipo-comprovante');
|
||||
var valor = button.data('valor');
|
||||
var dataComprovante = button.data('data-comprovante');
|
||||
|
||||
var modal = $(this);
|
||||
modal.find('#editMilitante').val(militanteId);
|
||||
modal.find('#editMilitanteNome').val(militanteNome);
|
||||
modal.find('#editTipoComprovante').val(tipoComprovante);
|
||||
modal.find('#editValor').val(valor);
|
||||
modal.find('#editDataComprovante').val(dataComprovante);
|
||||
|
||||
modal.find('form').attr('action', '/comprovantes/editar/' + comprovanteId);
|
||||
});
|
||||
|
||||
// Modal de exclusão
|
||||
$('#modalExcluirComprovante').on('show.bs.modal', function(event) {
|
||||
var button = $(event.relatedTarget);
|
||||
var comprovanteId = button.data('comprovante-id');
|
||||
var comprovanteInfo = button.data('comprovante-info');
|
||||
|
||||
var modal = $(this);
|
||||
modal.find('#comprovanteInfo').text(comprovanteInfo);
|
||||
modal.find('form').attr('action', '/comprovantes/excluir/' + comprovanteId);
|
||||
});
|
||||
|
||||
// Formatação de valores monetários
|
||||
$('.money').mask('000.000.000.000.000,00', {reverse: true});
|
||||
|
||||
// Validação de formulários
|
||||
$('form').on('submit', function(e) {
|
||||
if (!this.checkValidity()) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
$(this).addClass('was-validated');
|
||||
});
|
||||
});
|
||||
@@ -106,30 +106,87 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
});
|
||||
|
||||
// Validação de datas
|
||||
const dateInputs = document.querySelectorAll('input[type="date"]');
|
||||
const dateInputs = document.querySelectorAll('input[type="date"], input.date-mask');
|
||||
dateInputs.forEach(input => {
|
||||
input.addEventListener('change', function() {
|
||||
const date = new Date(this.value);
|
||||
const today = new Date();
|
||||
console.log('Validando data:', this.value);
|
||||
|
||||
let dataValida = true;
|
||||
let mensagemErro = '';
|
||||
|
||||
// Se for um campo com máscara, validar o formato
|
||||
if (this.classList.contains('date-mask')) {
|
||||
if (!validarData(this.value)) {
|
||||
dataValida = false;
|
||||
mensagemErro = 'Por favor, insira uma data válida no formato DD/MM/AAAA';
|
||||
}
|
||||
} else {
|
||||
// Para campos type="date", converter para Date
|
||||
const date = new Date(this.value);
|
||||
if (isNaN(date.getTime())) {
|
||||
dataValida = false;
|
||||
mensagemErro = 'Data inválida';
|
||||
}
|
||||
}
|
||||
|
||||
// Validar limites de data
|
||||
if (dataValida) {
|
||||
const hoje = new Date();
|
||||
hoje.setHours(0, 0, 0, 0);
|
||||
|
||||
let dataComparacao;
|
||||
if (this.classList.contains('date-mask')) {
|
||||
const [dia, mes, ano] = this.value.split('/').map(Number);
|
||||
dataComparacao = new Date(ano, mes - 1, dia);
|
||||
} else {
|
||||
dataComparacao = new Date(this.value);
|
||||
}
|
||||
|
||||
// Verificar data mínima
|
||||
if (this.hasAttribute('min')) {
|
||||
const minDate = new Date(this.getAttribute('min'));
|
||||
if (date < minDate) {
|
||||
this.setCustomValidity(`A data não pode ser anterior a ${minDate.toLocaleDateString()}`);
|
||||
this.classList.add('is-invalid');
|
||||
return;
|
||||
if (dataComparacao < minDate) {
|
||||
dataValida = false;
|
||||
mensagemErro = `A data não pode ser anterior a ${minDate.toLocaleDateString()}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Verificar data máxima
|
||||
if (this.hasAttribute('max')) {
|
||||
const maxDate = new Date(this.getAttribute('max'));
|
||||
if (date > maxDate) {
|
||||
this.setCustomValidity(`A data não pode ser posterior a ${maxDate.toLocaleDateString()}`);
|
||||
this.classList.add('is-invalid');
|
||||
return;
|
||||
if (dataComparacao > maxDate) {
|
||||
dataValida = false;
|
||||
mensagemErro = `A data não pode ser posterior a ${maxDate.toLocaleDateString()}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Verificar se é data futura (quando não permitido)
|
||||
if (this.hasAttribute('data-no-future') && dataComparacao > hoje) {
|
||||
dataValida = false;
|
||||
mensagemErro = 'A data não pode ser futura';
|
||||
}
|
||||
}
|
||||
|
||||
// Atualizar validação do campo
|
||||
if (!dataValida) {
|
||||
console.warn('Data inválida:', this.value, mensagemErro);
|
||||
this.setCustomValidity(mensagemErro);
|
||||
this.classList.add('is-invalid');
|
||||
|
||||
// Atualizar mensagem de feedback
|
||||
const feedback = this.nextElementSibling;
|
||||
if (feedback && feedback.classList.contains('invalid-feedback')) {
|
||||
feedback.textContent = mensagemErro;
|
||||
}
|
||||
} else {
|
||||
console.log('Data válida:', this.value);
|
||||
this.setCustomValidity('');
|
||||
this.classList.remove('is-invalid');
|
||||
}
|
||||
});
|
||||
|
||||
// Limpar validação ao começar a digitar
|
||||
input.addEventListener('input', function() {
|
||||
this.setCustomValidity('');
|
||||
this.classList.remove('is-invalid');
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Configurar clique nos itens da lista de pagamentos
|
||||
document.querySelectorAll('.list-group-item[onclick*="carregarDadosPagamento"]').forEach(item => {
|
||||
// Configurar clique nos itens da lista de comprovantes
|
||||
document.querySelectorAll('.list-group-item[onclick*="carregarDadosComprovante"]').forEach(item => {
|
||||
item.addEventListener('click', function(e) {
|
||||
const pagamentoId = this.getAttribute('data-pagamento-id');
|
||||
if (pagamentoId) {
|
||||
carregarDadosPagamento(pagamentoId);
|
||||
const comprovanteId = this.getAttribute('data-comprovante-id');
|
||||
if (comprovanteId) {
|
||||
carregarDadosComprovante(comprovanteId);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
// Configuração do token CSRF para requisições AJAX
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
|
||||
$.ajaxSetup({
|
||||
beforeSend: function(xhr, settings) {
|
||||
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
|
||||
xhr.setRequestHeader("X-CSRFToken", csrfToken);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Máscaras para campos de formulário
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Máscara para CPF
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,256 +0,0 @@
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
console.log('Carregando script pagamentos.js...');
|
||||
|
||||
// Inicializar DataTable
|
||||
const table = $('#tabelaPagamentos').DataTable({
|
||||
language: {
|
||||
url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/pt-BR.json'
|
||||
},
|
||||
order: [[3, 'desc']], // Ordenar por data de pagamento (decrescente)
|
||||
columnDefs: [
|
||||
{ targets: -1, orderable: false } // Desabilitar ordenação na coluna de ações
|
||||
]
|
||||
});
|
||||
|
||||
// Configuração do modal de edição
|
||||
const modalEditarPagamento = document.getElementById('modalEditarPagamento');
|
||||
if (modalEditarPagamento) {
|
||||
modalEditarPagamento.addEventListener('show.bs.modal', function(event) {
|
||||
console.log('Modal de edição sendo exibido');
|
||||
const button = event.relatedTarget;
|
||||
|
||||
if (!button) {
|
||||
console.error('Botão não encontrado!');
|
||||
return;
|
||||
}
|
||||
|
||||
const pagamentoId = button.getAttribute('data-pagamento-id');
|
||||
console.log('ID do pagamento:', pagamentoId);
|
||||
|
||||
// Dados do pagamento
|
||||
const dados = {
|
||||
militanteId: button.getAttribute('data-militante-id'),
|
||||
militanteNome: button.closest('tr').querySelector('td').textContent.trim(),
|
||||
tipoPagamento: button.getAttribute('data-tipo-pagamento'),
|
||||
valor: button.getAttribute('data-valor'),
|
||||
dataPagamento: button.getAttribute('data-data-pagamento')
|
||||
};
|
||||
console.log('Dados do pagamento:', dados);
|
||||
|
||||
// Preencher campos
|
||||
document.getElementById('editMilitante').value = dados.militanteId;
|
||||
document.getElementById('editMilitanteNome').value = dados.militanteNome;
|
||||
document.getElementById('editTipoPagamento').value = dados.tipoPagamento;
|
||||
document.getElementById('editValor').value = dados.valor;
|
||||
document.getElementById('editDataPagamento').value = dados.dataPagamento;
|
||||
|
||||
// Configurar formulário
|
||||
const form = document.getElementById('formEditarPagamento');
|
||||
if (form) {
|
||||
form.action = `/pagamentos/editar/${pagamentoId}`;
|
||||
console.log('Action do formulário:', form.action);
|
||||
|
||||
// Remover listeners antigos para evitar duplicação
|
||||
const newForm = form.cloneNode(true);
|
||||
form.parentNode.replaceChild(newForm, form);
|
||||
|
||||
// Adicionar listener para o submit do formulário
|
||||
newForm.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
console.log('Formulário submetido');
|
||||
|
||||
// Criar FormData com os dados do formulário
|
||||
const formData = new FormData(this);
|
||||
|
||||
// Log dos dados sendo enviados
|
||||
console.log('Dados do formulário:');
|
||||
for (let [key, value] of formData.entries()) {
|
||||
console.log(key + ': ' + value);
|
||||
}
|
||||
|
||||
// Enviar requisição
|
||||
fetch(this.action, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Status da resposta:', response.status);
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Resposta:', data);
|
||||
if (data.status === 'success') {
|
||||
// Fechar modal
|
||||
const modal = bootstrap.Modal.getInstance(modalEditarPagamento);
|
||||
modal.hide();
|
||||
|
||||
// Recarregar página
|
||||
window.location.reload();
|
||||
} else {
|
||||
alert('Erro ao atualizar pagamento: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao atualizar pagamento. Por favor, tente novamente.');
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Configuração do modal de exclusão
|
||||
const modalExcluirPagamento = document.getElementById('modalExcluirPagamento');
|
||||
if (modalExcluirPagamento) {
|
||||
modalExcluirPagamento.addEventListener('show.bs.modal', function(event) {
|
||||
console.log('Modal de exclusão sendo exibido');
|
||||
const button = event.relatedTarget;
|
||||
|
||||
if (!button) {
|
||||
console.error('Botão não encontrado!');
|
||||
return;
|
||||
}
|
||||
|
||||
const pagamentoId = button.getAttribute('data-pagamento-id');
|
||||
const pagamentoInfo = button.getAttribute('data-pagamento-info');
|
||||
console.log('ID do pagamento:', pagamentoId);
|
||||
|
||||
// Atualizar informações no modal
|
||||
document.getElementById('pagamentoInfo').textContent = pagamentoInfo;
|
||||
|
||||
// Configurar formulário
|
||||
const form = document.getElementById('formExcluirPagamento');
|
||||
if (form) {
|
||||
form.action = `/pagamentos/excluir/${pagamentoId}`;
|
||||
console.log('Action do formulário:', form.action);
|
||||
|
||||
// Remover listeners antigos para evitar duplicação
|
||||
const newForm = form.cloneNode(true);
|
||||
form.parentNode.replaceChild(newForm, form);
|
||||
|
||||
// Adicionar listener para o submit do formulário
|
||||
newForm.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
console.log('Formulário submetido');
|
||||
|
||||
// Enviar requisição
|
||||
fetch(this.action, {
|
||||
method: 'POST'
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Status da resposta:', response.status);
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Resposta:', data);
|
||||
if (data.status === 'success') {
|
||||
// Fechar modal
|
||||
const modal = bootstrap.Modal.getInstance(modalExcluirPagamento);
|
||||
modal.hide();
|
||||
|
||||
// Recarregar página
|
||||
window.location.reload();
|
||||
} else {
|
||||
alert('Erro ao excluir pagamento: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao excluir pagamento. Por favor, tente novamente.');
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Configuração do formulário de novo pagamento
|
||||
const formNovoPagamento = document.getElementById('formNovoPagamento');
|
||||
if (formNovoPagamento) {
|
||||
formNovoPagamento.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
console.log('Formulário de novo pagamento submetido');
|
||||
|
||||
// Criar FormData com os dados do formulário
|
||||
const formData = new FormData(this);
|
||||
|
||||
// Log dos dados sendo enviados
|
||||
console.log('Dados do formulário:');
|
||||
for (let [key, value] of formData.entries()) {
|
||||
console.log(key + ': ' + value);
|
||||
}
|
||||
|
||||
// Enviar requisição
|
||||
fetch(this.action, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Status da resposta:', response.status);
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Resposta:', data);
|
||||
if (data.status === 'success') {
|
||||
// Fechar modal
|
||||
const modal = bootstrap.Modal.getInstance(document.getElementById('modalNovoPagamento'));
|
||||
modal.hide();
|
||||
|
||||
// Recarregar página
|
||||
window.location.reload();
|
||||
} else {
|
||||
alert('Erro ao adicionar pagamento: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao adicionar pagamento. Por favor, tente novamente.');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Configuração do botão de exportar
|
||||
const btnExportar = document.getElementById('btnExportar');
|
||||
if (btnExportar) {
|
||||
btnExportar.addEventListener('click', function() {
|
||||
console.log('Exportando dados...');
|
||||
|
||||
// Coletar dados da tabela
|
||||
const dados = [];
|
||||
table.rows().every(function() {
|
||||
const row = this.data();
|
||||
dados.push({
|
||||
militante: row[0],
|
||||
tipo_pagamento: row[1],
|
||||
valor: row[2].replace('R$ ', ''),
|
||||
data_pagamento: row[3]
|
||||
});
|
||||
});
|
||||
|
||||
// Converter para CSV
|
||||
const csv = [
|
||||
['Militante', 'Tipo de Pagamento', 'Valor', 'Data do Pagamento'],
|
||||
...dados.map(row => [
|
||||
row.militante,
|
||||
row.tipo_pagamento,
|
||||
row.valor,
|
||||
row.data_pagamento
|
||||
])
|
||||
]
|
||||
.map(row => row.join(','))
|
||||
.join('\n');
|
||||
|
||||
// Criar blob e fazer download
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const link = document.createElement('a');
|
||||
if (link.download !== undefined) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
link.setAttribute('href', url);
|
||||
link.setAttribute('download', 'pagamentos.csv');
|
||||
link.style.visibility = 'hidden';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
208
static/js/table_sort.js
Normal file
208
static/js/table_sort.js
Normal file
@@ -0,0 +1,208 @@
|
||||
// Função para converter data DD/MM/YYYY para objeto Date
|
||||
function converterDataParaComparacao(dataStr) {
|
||||
console.log('Convertendo data para comparação:', dataStr);
|
||||
|
||||
if (!dataStr) return null;
|
||||
|
||||
try {
|
||||
// Se já estiver no formato ISO
|
||||
if (/^\d{4}-\d{2}-\d{2}/.test(dataStr)) {
|
||||
const data = new Date(dataStr);
|
||||
console.log('Data ISO convertida:', data);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Se estiver no formato DD/MM/YYYY
|
||||
if (/^\d{2}\/\d{2}\/\d{4}/.test(dataStr)) {
|
||||
const [dia, mes, ano] = dataStr.split('/').map(Number);
|
||||
const data = new Date(ano, mes - 1, dia);
|
||||
console.log('Data DD/MM/YYYY convertida:', data);
|
||||
return data;
|
||||
}
|
||||
|
||||
console.warn('Formato de data não reconhecido:', dataStr);
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Erro ao converter data:', error, 'Data:', dataStr);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Função para ordenar tabelas
|
||||
function configurarOrdenacaoTabela(tabelaId) {
|
||||
console.log('Configurando ordenação para tabela:', tabelaId);
|
||||
|
||||
const table = document.getElementById(tabelaId);
|
||||
if (!table) {
|
||||
console.warn('Tabela não encontrada:', tabelaId);
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = table.querySelectorAll('th[data-sort]');
|
||||
headers.forEach(header => {
|
||||
if (header.dataset.sort) {
|
||||
header.addEventListener('click', () => {
|
||||
const column = header.dataset.sort;
|
||||
const tbody = table.getElementsByTagName('tbody')[0];
|
||||
const rows = Array.from(tbody.getElementsByTagName('tr'));
|
||||
|
||||
console.log('Ordenando coluna:', column);
|
||||
|
||||
rows.sort((a, b) => {
|
||||
const aValue = a.querySelector(`td[data-${column}]`).dataset[column];
|
||||
const bValue = b.querySelector(`td[data-${column}]`).dataset[column];
|
||||
|
||||
// Ordenação por data
|
||||
if (column === 'data' ||
|
||||
column === 'data_vencimento' ||
|
||||
column === 'data_alteracao' ||
|
||||
column === 'data_comprovante' ||
|
||||
column === 'data_venda' ||
|
||||
column === 'data_relatorio') {
|
||||
const aDate = converterDataParaComparacao(aValue);
|
||||
const bDate = converterDataParaComparacao(bValue);
|
||||
|
||||
// Se alguma data for inválida
|
||||
if (!aDate && !bDate) return 0;
|
||||
if (!aDate) return 1;
|
||||
if (!bDate) return -1;
|
||||
|
||||
return aDate - bDate;
|
||||
}
|
||||
|
||||
// Ordenação por valor monetário
|
||||
if (column === 'valor' ||
|
||||
column === 'valor_total' ||
|
||||
column === 'valor_antigo' ||
|
||||
column === 'valor_novo') {
|
||||
const aNum = parseFloat(aValue.replace(/[^\d,-]/g, '').replace(',', '.'));
|
||||
const bNum = parseFloat(bValue.replace(/[^\d,-]/g, '').replace(',', '.'));
|
||||
return aNum - bNum;
|
||||
}
|
||||
|
||||
// Ordenação padrão para texto
|
||||
return aValue.localeCompare(bValue);
|
||||
});
|
||||
|
||||
// Alternar direção da ordenação
|
||||
if (header.classList.contains('asc')) {
|
||||
rows.reverse();
|
||||
header.classList.remove('asc');
|
||||
header.classList.add('desc');
|
||||
console.log('Ordenação descendente');
|
||||
} else {
|
||||
header.classList.remove('desc');
|
||||
header.classList.add('asc');
|
||||
console.log('Ordenação ascendente');
|
||||
}
|
||||
|
||||
// Atualizar tabela
|
||||
tbody.innerHTML = '';
|
||||
rows.forEach(row => tbody.appendChild(row));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Configurar ordenação para todas as tabelas que precisam
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
console.log('Configurando ordenação para todas as tabelas...');
|
||||
|
||||
const tabelas = [
|
||||
'materiaisTable',
|
||||
'vendasTable',
|
||||
'cotasTable',
|
||||
'comprovantesTable'
|
||||
];
|
||||
|
||||
tabelas.forEach(tabelaId => {
|
||||
configurarOrdenacaoTabela(tabelaId);
|
||||
});
|
||||
});
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
console.log('Carregando script table_sort.js...');
|
||||
|
||||
// Função para comparar datas no formato DD/MM/YYYY
|
||||
function compararDatas(a, b) {
|
||||
if (!a || !b) return 0;
|
||||
|
||||
const [diaA, mesA, anoA] = a.split('/').map(Number);
|
||||
const [diaB, mesB, anoB] = b.split('/').map(Number);
|
||||
|
||||
const dataA = new Date(anoA, mesA - 1, diaA);
|
||||
const dataB = new Date(anoB, mesB - 1, diaB);
|
||||
|
||||
return dataA - dataB;
|
||||
}
|
||||
|
||||
// Função para comparar valores monetários
|
||||
function compararValores(a, b) {
|
||||
const valorA = parseFloat(a.replace('R$ ', '').replace('.', '').replace(',', '.'));
|
||||
const valorB = parseFloat(b.replace('R$ ', '').replace('.', '').replace(',', '.'));
|
||||
|
||||
if (isNaN(valorA)) return -1;
|
||||
if (isNaN(valorB)) return 1;
|
||||
|
||||
return valorA - valorB;
|
||||
}
|
||||
|
||||
// Configurar ordenação para todas as tabelas com classe 'table-sort'
|
||||
document.querySelectorAll('table.table-sort').forEach(tabela => {
|
||||
const tbody = tabela.querySelector('tbody');
|
||||
const headers = tabela.querySelectorAll('th[data-sort]');
|
||||
|
||||
headers.forEach(header => {
|
||||
const tipoOrdenacao = header.dataset.sort;
|
||||
|
||||
header.addEventListener('click', () => {
|
||||
const rows = Array.from(tbody.querySelectorAll('tr'));
|
||||
const colIndex = Array.from(header.parentNode.children).indexOf(header);
|
||||
|
||||
rows.sort((rowA, rowB) => {
|
||||
const cellA = rowA.children[colIndex].dataset[tipoOrdenacao] || rowA.children[colIndex].textContent.trim();
|
||||
const cellB = rowB.children[colIndex].dataset[tipoOrdenacao] || rowB.children[colIndex].textContent.trim();
|
||||
|
||||
switch (tipoOrdenacao) {
|
||||
case 'data':
|
||||
return compararDatas(cellA, cellB);
|
||||
case 'valor':
|
||||
return compararValores(cellA, cellB);
|
||||
case 'numero':
|
||||
return parseFloat(cellA) - parseFloat(cellB);
|
||||
default:
|
||||
return cellA.localeCompare(cellB);
|
||||
}
|
||||
});
|
||||
|
||||
if (header.classList.contains('asc')) {
|
||||
rows.reverse();
|
||||
header.classList.remove('asc');
|
||||
header.classList.add('desc');
|
||||
} else {
|
||||
header.classList.remove('desc');
|
||||
header.classList.add('asc');
|
||||
}
|
||||
|
||||
// Remover classes de ordenação de outros headers
|
||||
headers.forEach(h => {
|
||||
if (h !== header) {
|
||||
h.classList.remove('asc', 'desc');
|
||||
}
|
||||
});
|
||||
|
||||
// Atualizar tabela
|
||||
tbody.innerHTML = '';
|
||||
rows.forEach(row => tbody.appendChild(row));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function sortTable(table, column, type = 'text') {
|
||||
// ... existing code ...
|
||||
if (column === 'data_comprovante') {
|
||||
// ... existing code ...
|
||||
}
|
||||
// ... existing code ...
|
||||
}
|
||||
284
static/js/testes.js
Normal file
284
static/js/testes.js
Normal file
@@ -0,0 +1,284 @@
|
||||
// Testes para o formulário de edição de militantes
|
||||
console.log('Iniciando testes do formulário de edição...');
|
||||
|
||||
// Lista de campos que devem existir no formulário
|
||||
const camposEsperados = {
|
||||
'edit_militante_id': { tipo: 'hidden', obrigatorio: true },
|
||||
'edit_nome': { tipo: 'text', obrigatorio: true },
|
||||
'edit_cpf': { tipo: 'text', obrigatorio: true },
|
||||
'edit_titulo_eleitoral': { tipo: 'text', obrigatorio: false },
|
||||
'edit_data_nascimento': { tipo: 'text', obrigatorio: false },
|
||||
'edit_data_entrada_oci': { tipo: 'text', obrigatorio: false },
|
||||
'edit_data_efetivacao_oci': { tipo: 'text', obrigatorio: false },
|
||||
'edit_email': { tipo: 'email', obrigatorio: true },
|
||||
'edit_telefone1': { tipo: 'text', obrigatorio: false },
|
||||
'edit_telefone2': { tipo: 'text', obrigatorio: false },
|
||||
'edit_cep': { tipo: 'text', obrigatorio: false },
|
||||
'edit_estado': { tipo: 'select', obrigatorio: false },
|
||||
'edit_cidade': { tipo: 'text', obrigatorio: false },
|
||||
'edit_bairro': { tipo: 'text', obrigatorio: false },
|
||||
'edit_rua': { tipo: 'text', obrigatorio: false },
|
||||
'edit_numero': { tipo: 'text', obrigatorio: false },
|
||||
'edit_complemento': { tipo: 'text', obrigatorio: false },
|
||||
'edit_empresa': { tipo: 'text', obrigatorio: false },
|
||||
'edit_contratante': { tipo: 'text', obrigatorio: false },
|
||||
'edit_instituicao_ensino': { tipo: 'text', obrigatorio: false },
|
||||
'edit_tipo_instituicao': { tipo: 'select', obrigatorio: false },
|
||||
'edit_sindicato': { tipo: 'text', obrigatorio: false },
|
||||
'edit_cargo_sindical': { tipo: 'text', obrigatorio: false },
|
||||
'edit_central_sindical': { tipo: 'text', obrigatorio: false },
|
||||
'edit_celula': { tipo: 'select', obrigatorio: false },
|
||||
'responsabilidades_values': { tipo: 'hidden', obrigatorio: false }
|
||||
};
|
||||
|
||||
// Função para testar a existência e configuração dos campos
|
||||
function testarCamposFormulario() {
|
||||
console.log('Testando campos do formulário...');
|
||||
const form = document.getElementById('formEditarMilitante');
|
||||
const erros = [];
|
||||
|
||||
if (!form) {
|
||||
console.error('Formulário não encontrado!');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Testar cada campo esperado
|
||||
for (const [id, config] of Object.entries(camposEsperados)) {
|
||||
const campo = document.getElementById(id);
|
||||
if (!campo) {
|
||||
erros.push(`Campo ${id} não encontrado`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verificar tipo
|
||||
if (campo.type !== config.tipo && config.tipo !== 'select') {
|
||||
erros.push(`Campo ${id} tem tipo ${campo.type}, esperado ${config.tipo}`);
|
||||
}
|
||||
|
||||
// Verificar obrigatoriedade
|
||||
if (config.obrigatorio && !campo.hasAttribute('required')) {
|
||||
erros.push(`Campo ${id} deveria ser obrigatório`);
|
||||
}
|
||||
|
||||
// Verificar se o campo tem name attribute
|
||||
if (!campo.hasAttribute('name')) {
|
||||
erros.push(`Campo ${id} não tem atributo name`);
|
||||
}
|
||||
}
|
||||
|
||||
// Reportar erros encontrados
|
||||
if (erros.length > 0) {
|
||||
console.error('Erros encontrados nos campos:', erros);
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('Todos os campos estão configurados corretamente');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Função para testar o carregamento de dados
|
||||
async function testarCarregamentoDados(militanteId) {
|
||||
console.log('Testando carregamento de dados...');
|
||||
try {
|
||||
const response = await fetch(`/militantes/dados/${militanteId}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Erro HTTP: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Dados recebidos:', data);
|
||||
|
||||
// Verificar se os dados foram carregados corretamente
|
||||
const erros = [];
|
||||
|
||||
// Verificar campos básicos
|
||||
if (!data.nome) erros.push('Nome não carregado');
|
||||
if (!data.cpf) erros.push('CPF não carregado');
|
||||
|
||||
// Verificar se os campos foram preenchidos
|
||||
for (const [id, config] of Object.entries(camposEsperados)) {
|
||||
const campo = document.getElementById(id);
|
||||
if (!campo) continue;
|
||||
|
||||
// Mapear campos do servidor para campos do formulário
|
||||
let valorEsperado = '';
|
||||
switch(id) {
|
||||
case 'edit_nome': valorEsperado = data.nome; break;
|
||||
case 'edit_cpf': valorEsperado = data.cpf; break;
|
||||
case 'edit_email': valorEsperado = data.emails?.[0]; break;
|
||||
case 'edit_telefone1': valorEsperado = data.telefone1; break;
|
||||
case 'edit_celula': valorEsperado = data.celula_id?.toString(); break;
|
||||
case 'edit_cargo_sindical': valorEsperado = data.cargo_sindical; break;
|
||||
case 'edit_central_sindical': valorEsperado = data.central_sindical; break;
|
||||
case 'edit_sindicato': valorEsperado = data.sindicato; break;
|
||||
// Adicione mais campos conforme necessário
|
||||
}
|
||||
|
||||
if (config.obrigatorio && !valorEsperado) {
|
||||
erros.push(`Campo obrigatório ${id} não tem valor no servidor`);
|
||||
}
|
||||
|
||||
if (valorEsperado && campo.value !== valorEsperado) {
|
||||
erros.push(`Campo ${id} tem valor diferente do servidor. Esperado: ${valorEsperado}, Atual: ${campo.value}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (erros.length > 0) {
|
||||
console.error('Erros no carregamento:', erros);
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('Dados carregados corretamente');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Função para testar o salvamento de dados
|
||||
async function testarSalvamentoDados(militanteId) {
|
||||
console.log('Testando salvamento de dados...');
|
||||
try {
|
||||
const form = document.getElementById('formEditarMilitante');
|
||||
const formData = new FormData(form);
|
||||
|
||||
// Guardar valores originais para comparação
|
||||
const valoresOriginais = {
|
||||
nome: formData.get('nome'),
|
||||
cpf: formData.get('cpf'),
|
||||
email: formData.get('email'),
|
||||
celula: formData.get('celula'),
|
||||
cargo_sindical: formData.get('cargo_sindical'),
|
||||
central_sindical: formData.get('central_sindical'),
|
||||
sindicato: formData.get('sindicato'),
|
||||
responsabilidades: formData.get('responsabilidades_values')
|
||||
};
|
||||
|
||||
const response = await fetch(`/militantes/editar/${militanteId}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
|
||||
},
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Erro HTTP: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Resposta do servidor:', data);
|
||||
|
||||
// Verificar se os dados foram salvos corretamente
|
||||
const row = document.querySelector(`tr[data-militante="${militanteId}"]`);
|
||||
if (!row) {
|
||||
console.error('Linha da tabela não encontrada após salvamento');
|
||||
return false;
|
||||
}
|
||||
|
||||
const erros = [];
|
||||
|
||||
// Verificar dados básicos na tabela
|
||||
const nome = row.querySelector('td[data-nome]')?.textContent;
|
||||
const cpf = row.querySelector('td[data-cpf]')?.textContent;
|
||||
const email = row.querySelector('td[data-email]')?.textContent;
|
||||
|
||||
if (nome !== valoresOriginais.nome) erros.push(`Nome não atualizado na tabela. Esperado: ${valoresOriginais.nome}, Atual: ${nome}`);
|
||||
if (cpf !== valoresOriginais.cpf) erros.push(`CPF não atualizado na tabela. Esperado: ${valoresOriginais.cpf}, Atual: ${cpf}`);
|
||||
if (email !== valoresOriginais.email) erros.push(`Email não atualizado na tabela. Esperado: ${valoresOriginais.email}, Atual: ${email}`);
|
||||
|
||||
// Verificar atributos para filtros
|
||||
const celulaId = row.getAttribute('data-celula-id');
|
||||
const responsabilidades = row.getAttribute('data-responsabilidades');
|
||||
|
||||
if (celulaId !== valoresOriginais.celula) erros.push(`Célula não atualizada na tabela. Esperado: ${valoresOriginais.celula}, Atual: ${celulaId}`);
|
||||
if (responsabilidades !== valoresOriginais.responsabilidades) erros.push(`Responsabilidades não atualizadas na tabela. Esperado: ${valoresOriginais.responsabilidades}, Atual: ${responsabilidades}`);
|
||||
|
||||
// Verificar botão de edição
|
||||
const btnEditar = row.querySelector('button[data-bs-target="#modalEditarMilitante"]');
|
||||
if (btnEditar) {
|
||||
if (btnEditar.getAttribute('data-militante-nome') !== valoresOriginais.nome) {
|
||||
erros.push('Nome não atualizado no botão de edição');
|
||||
}
|
||||
if (btnEditar.getAttribute('data-celula-id') !== valoresOriginais.celula) {
|
||||
erros.push('Célula não atualizada no botão de edição');
|
||||
}
|
||||
}
|
||||
|
||||
if (erros.length > 0) {
|
||||
console.error('Erros no salvamento:', erros);
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('Dados salvos e atualizados corretamente');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar dados:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Função principal de teste
|
||||
async function testarFormularioEdicao(militanteId) {
|
||||
console.log('Iniciando teste completo do formulário...');
|
||||
|
||||
// Testar campos do formulário
|
||||
if (!testarCamposFormulario()) {
|
||||
console.error('Teste dos campos falhou');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Testar carregamento de dados
|
||||
if (!await testarCarregamentoDados(militanteId)) {
|
||||
console.error('Teste de carregamento falhou');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Testar salvamento de dados
|
||||
if (!await testarSalvamentoDados(militanteId)) {
|
||||
console.error('Teste de salvamento falhou');
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('Todos os testes passaram com sucesso!');
|
||||
return true;
|
||||
}
|
||||
|
||||
// Executar testes quando o documento estiver carregado
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Adicionar botão de teste na interface
|
||||
const btnTeste = document.createElement('button');
|
||||
btnTeste.className = 'btn btn-info me-2';
|
||||
btnTeste.innerHTML = '<i class="fas fa-vial me-2"></i>Testar Formulário';
|
||||
btnTeste.onclick = function() {
|
||||
// Pegar ID do primeiro militante da lista
|
||||
const primeiraLinha = document.querySelector('#militantesTable tbody tr');
|
||||
if (!primeiraLinha) {
|
||||
mostrarAlerta('danger', 'Nenhum militante encontrado para teste');
|
||||
return;
|
||||
}
|
||||
|
||||
const militanteId = primeiraLinha.getAttribute('data-militante');
|
||||
if (!militanteId) {
|
||||
mostrarAlerta('danger', 'ID do militante não encontrado');
|
||||
return;
|
||||
}
|
||||
|
||||
// Executar testes
|
||||
testarFormularioEdicao(militanteId).then(sucesso => {
|
||||
if (sucesso) {
|
||||
mostrarAlerta('success', 'Testes concluídos com sucesso!');
|
||||
} else {
|
||||
mostrarAlerta('danger', 'Alguns testes falharam. Verifique o console para mais detalhes.');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Adicionar botão ao lado do botão de exportar
|
||||
const btnExportar = document.querySelector('.btn-exportar');
|
||||
if (btnExportar && btnExportar.parentNode) {
|
||||
btnExportar.parentNode.insertBefore(btnTeste, btnExportar);
|
||||
}
|
||||
});
|
||||
119
static/js/vendas.js
Normal file
119
static/js/vendas.js
Normal file
@@ -0,0 +1,119 @@
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
console.log('Carregando script vendas.js...');
|
||||
|
||||
// Funções de validação e formatação de datas
|
||||
function validarData(data) {
|
||||
if (!data) return false;
|
||||
|
||||
const dataObj = new Date(data);
|
||||
if (isNaN(dataObj.getTime())) return false;
|
||||
|
||||
const hoje = new Date();
|
||||
hoje.setHours(0, 0, 0, 0);
|
||||
|
||||
return dataObj <= hoje;
|
||||
}
|
||||
|
||||
function formatarData(data) {
|
||||
if (!data) return '';
|
||||
|
||||
const dataObj = new Date(data);
|
||||
if (isNaN(dataObj.getTime())) return '';
|
||||
|
||||
return dataObj.toLocaleDateString('pt-BR');
|
||||
}
|
||||
|
||||
// Configurar campos de data
|
||||
const camposData = document.querySelectorAll('input[type="date"]');
|
||||
camposData.forEach(campo => {
|
||||
// Definir data máxima como hoje
|
||||
const hoje = new Date().toISOString().split('T')[0];
|
||||
campo.setAttribute('max', hoje);
|
||||
|
||||
campo.addEventListener('change', function() {
|
||||
if (!validarData(this.value)) {
|
||||
this.setCustomValidity('Data inválida ou futura');
|
||||
this.classList.add('is-invalid');
|
||||
} else {
|
||||
this.setCustomValidity('');
|
||||
this.classList.remove('is-invalid');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Configurar tabela de vendas
|
||||
const tabelaVendas = $('#vendasTable').DataTable({
|
||||
language: {
|
||||
url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/pt-BR.json'
|
||||
},
|
||||
columnDefs: [
|
||||
{
|
||||
targets: 3, // Coluna de data
|
||||
type: 'date-br',
|
||||
render: function(data, type, row) {
|
||||
if (type === 'sort') {
|
||||
return data.split('/').reverse().join('');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
},
|
||||
{
|
||||
targets: 2, // Coluna de valor
|
||||
type: 'numeric',
|
||||
render: function(data, type, row) {
|
||||
if (type === 'sort') {
|
||||
return parseFloat(data.replace('R$ ', '').replace(',', '.'));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
},
|
||||
{ targets: -1, orderable: false } // Coluna de ações
|
||||
],
|
||||
order: [[3, 'desc']] // Ordenar por data decrescente por padrão
|
||||
});
|
||||
|
||||
// Atualizar valor total ao mudar quantidade ou material
|
||||
const campoQuantidade = document.getElementById('quantidade');
|
||||
const campoMaterial = document.getElementById('material_id');
|
||||
const campoValorTotal = document.getElementById('valor_total');
|
||||
|
||||
function atualizarValorTotal() {
|
||||
if (!campoQuantidade || !campoMaterial || !campoValorTotal) return;
|
||||
|
||||
const quantidade = parseInt(campoQuantidade.value) || 0;
|
||||
const materialSelecionado = campoMaterial.options[campoMaterial.selectedIndex];
|
||||
const preco = materialSelecionado ? parseFloat(materialSelecionado.dataset.preco) || 0 : 0;
|
||||
|
||||
campoValorTotal.value = (quantidade * preco).toFixed(2);
|
||||
}
|
||||
|
||||
if (campoQuantidade) {
|
||||
campoQuantidade.addEventListener('change', atualizarValorTotal);
|
||||
}
|
||||
if (campoMaterial) {
|
||||
campoMaterial.addEventListener('change', atualizarValorTotal);
|
||||
}
|
||||
|
||||
// Configurar modal de edição
|
||||
const modalEditarVenda = document.getElementById('modalEditarVenda');
|
||||
if (modalEditarVenda) {
|
||||
modalEditarVenda.addEventListener('show.bs.modal', function(event) {
|
||||
const button = event.relatedTarget;
|
||||
if (!button) return;
|
||||
|
||||
const vendaId = button.getAttribute('data-venda-id');
|
||||
const militanteId = button.getAttribute('data-militante-id');
|
||||
const materialId = button.getAttribute('data-material-id');
|
||||
const quantidade = button.getAttribute('data-quantidade');
|
||||
const valorTotal = button.getAttribute('data-valor-total');
|
||||
const dataVenda = button.getAttribute('data-data-venda');
|
||||
|
||||
document.getElementById('editVendaId').value = vendaId;
|
||||
document.getElementById('editMilitanteId').value = militanteId;
|
||||
document.getElementById('editMaterialId').value = materialId;
|
||||
document.getElementById('editQuantidade').value = quantidade;
|
||||
document.getElementById('editValorTotal').value = valorTotal;
|
||||
document.getElementById('editDataVenda').value = dataVenda;
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
||||
<link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
|
||||
<title>{% block title %}{% endblock %} - Controles OCI</title>
|
||||
|
||||
<!-- Bootstrap 5 CSS -->
|
||||
@@ -540,8 +541,8 @@
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item" href="{{ url_for('listar_pagamentos') }}">
|
||||
<i class="fas fa-receipt"></i>Pagamentos
|
||||
<a class="dropdown-item" href="{{ url_for('listar_comprovantes') }}">
|
||||
<i class="fas fa-receipt"></i>Comprovantes
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
@@ -562,8 +563,8 @@
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item" href="{{ url_for('listar_assinaturas') }}">
|
||||
<i class="fas fa-file-signature"></i>Assinaturas
|
||||
<a class="dropdown-item" href="{{ url_for('listar_vendas_jornal') }}">
|
||||
<i class="fas fa-file-signature"></i>Assinaturas de Jornal
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
{% endwith %}
|
||||
|
||||
<form method="POST" class="needs-validation" novalidate>
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="nome" class="form-label">Nome</label>
|
||||
|
||||
43
templates/editar_comprovante.html
Normal file
43
templates/editar_comprovante.html
Normal file
@@ -0,0 +1,43 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}Editar Comprovante{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-8 offset-md-2">
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header bg-light">
|
||||
<h4 class="card-title mb-0">
|
||||
<i class="fas fa-money-bill-wave me-2"></i>Editar Comprovante
|
||||
</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<div class="form-group">
|
||||
<label for="tipo_comprovante_id">Tipo de Comprovante</label>
|
||||
<select class="form-control" id="tipo_comprovante_id" name="tipo_comprovante_id" required>
|
||||
<option value="1" {% if comprovante.tipo_comprovante_id == 1 %}selected{% endif %}>1 - Comprovante Padrão</option>
|
||||
{% if current_user.has_permission('gerenciar_tipos_comprovante') %}
|
||||
<option value="2" {% if comprovante.tipo_comprovante_id == 2 %}selected{% endif %}>2 - Comprovante Especial</option>
|
||||
<option value="3" {% if comprovante.tipo_comprovante_id == 3 %}selected{% endif %}>3 - Comprovante Extraordinário</option>
|
||||
<option value="4" {% if comprovante.tipo_comprovante_id == 4 %}selected{% endif %}>4 - Jornal Avulso</option>
|
||||
<option value="5" {% if comprovante.tipo_comprovante_id == 5 %}selected{% endif %}>5 - Assinatura de Jornal</option>
|
||||
<option value="6" {% if comprovante.tipo_comprovante_id == 6 %}selected{% endif %}>6 - Campanha Financeira</option>
|
||||
{% endif %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="data_comprovante" class="form-label">Data do Comprovante:</label>
|
||||
<input type="date" class="form-control" id="data_comprovante" name="data_comprovante"
|
||||
required max="{{ hoje }}">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Salvar</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -16,7 +16,9 @@
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<form method="POST" class="needs-validation" novalidate>
|
||||
<form id="formEditarMilitante" method="POST" class="needs-validation" novalidate>
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" name="militante_id" value="{{ militante.id }}">
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="nome" class="form-label">Nome</label>
|
||||
@@ -28,7 +30,7 @@
|
||||
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="email" class="form-label">Email</label>
|
||||
<input type="email" class="form-control" id="email" name="email" value="{{ militante.email }}" required>
|
||||
<input type="email" class="form-control" id="email" name="email" value="{{ militante.emails[0].endereco_email if militante.emails else '' }}" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira um email válido.
|
||||
</div>
|
||||
@@ -209,21 +211,43 @@
|
||||
<script>
|
||||
// Validação do formulário
|
||||
(function () {
|
||||
'use strict'
|
||||
'use strict';
|
||||
|
||||
var forms = document.querySelectorAll('.needs-validation')
|
||||
var forms = document.querySelectorAll('.needs-validation');
|
||||
|
||||
Array.prototype.slice.call(forms)
|
||||
.forEach(function (form) {
|
||||
form.addEventListener('submit', function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
if (!form.checkValidity()) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
event.stopPropagation();
|
||||
} else {
|
||||
salvarAlteracoesMilitante({{ militante.id }});
|
||||
}
|
||||
|
||||
form.classList.add('was-validated')
|
||||
}, false)
|
||||
})
|
||||
})()
|
||||
form.classList.add('was-validated');
|
||||
}, false);
|
||||
});
|
||||
})();
|
||||
|
||||
// Função para mostrar alertas
|
||||
function mostrarAlerta(mensagem, tipo) {
|
||||
const alertDiv = document.createElement('div');
|
||||
alertDiv.className = `alert alert-${tipo} alert-dismissible fade show`;
|
||||
alertDiv.role = 'alert';
|
||||
alertDiv.innerHTML = `
|
||||
${mensagem}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
`;
|
||||
|
||||
const container = document.querySelector('.container');
|
||||
container.insertBefore(alertDiv, container.firstChild);
|
||||
|
||||
// Remover o alerta após 5 segundos
|
||||
setTimeout(() => {
|
||||
alertDiv.remove();
|
||||
}, 5000);
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -1,12 +1,12 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}Editar Relatório de Pagamentos{% endblock %}
|
||||
{% block title %}Editar Relatório de Comprovantes{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1 class="mb-4">Editar Relatório de Pagamentos</h1>
|
||||
<h1 class="mb-4">Editar Relatório de Comprovantes</h1>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
@@ -44,10 +44,10 @@
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="total_pagamentos" class="form-label">Total de Pagamentos</label>
|
||||
<input type="number" class="form-control" id="total_pagamentos" name="total_pagamentos" step="0.01" value="{{ relatorio.total_pagamentos }}" required>
|
||||
<label for="total_comprovantes" class="form-label">Total de Comprovantes</label>
|
||||
<input type="number" class="form-control" id="total_comprovantes" name="total_comprovantes" step="0.01" value="{{ relatorio.total_comprovantes }}" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira o total de pagamentos.
|
||||
Por favor, insira o total de comprovantes.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
|
||||
<div class="d-flex justify-content-between">
|
||||
<button type="submit" class="btn btn-success">Salvar</button>
|
||||
<a href="{{ url_for('listar_relatorios_pagamentos') }}" class="btn btn-outline-secondary">Voltar</a>
|
||||
<a href="{{ url_for('listar_relatorios_comprovantes') }}" class="btn btn-outline-secondary">Voltar</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -57,7 +57,7 @@
|
||||
<div class="stats-card yellow">
|
||||
<div class="title">Assinaturas Ativas</div>
|
||||
<div class="value">{{ total_assinaturas }}</div>
|
||||
<a href="{{ url_for('listar_assinaturas') }}" class="link">
|
||||
<a href="{{ url_for('listar_vendas_jornal') }}" class="link">
|
||||
Ver detalhes <i class="fas fa-arrow-right"></i>
|
||||
</a>
|
||||
<div class="icon">
|
||||
@@ -87,7 +87,7 @@
|
||||
data-militante-nome="{{ militante.nome }}">
|
||||
<div class="militante-info">
|
||||
<h6 class="mb-1">{{ militante.nome }}</h6>
|
||||
<small>{{ militante.email }}</small>
|
||||
<small>{{ militante.emails[0].endereco_email if militante.emails else '' }}</small>
|
||||
</div>
|
||||
<i class="fas fa-chevron-right text-muted"></i>
|
||||
</div>
|
||||
|
||||
49
templates/lista_comprovantes.html
Normal file
49
templates/lista_comprovantes.html
Normal file
@@ -0,0 +1,49 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}Lista de Comprovantes{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header bg-light">
|
||||
<h4 class="card-title mb-0">
|
||||
<i class="fas fa-list me-2"></i>Lista de Comprovantes
|
||||
</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Data</th>
|
||||
<th>Valor</th>
|
||||
<th>Tipo</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for comprovante in comprovantes %}
|
||||
<tr>
|
||||
<td>{{ comprovante.id }}</td>
|
||||
<td>{{ comprovante.data.strftime('%d/%m/%Y') }}</td>
|
||||
<td>R$ {{ "%.2f"|format(comprovante.valor) }}</td>
|
||||
<td>
|
||||
{% if comprovante.tipo_comprovante_id == 1 %}
|
||||
1 - Comprovante Padrão
|
||||
{% elif current_user.has_permission('gerenciar_tipos_comprovante') %}
|
||||
{% if comprovante.tipo_comprovante_id == 2 %}
|
||||
2 - Comprovante Especial
|
||||
<td>{{ comprovante.tipo }}</td>
|
||||
<td>{{ comprovante.data }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
309
templates/listar_comprovantes.html
Normal file
309
templates/listar_comprovantes.html
Normal file
@@ -0,0 +1,309 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Comprovantes{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container-fluid mt-3">
|
||||
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||
<h2><i class="fas fa-money-bill-wave"></i> Comprovantes</h2>
|
||||
<div>
|
||||
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#novoComprovanteModal">
|
||||
<i class="fas fa-plus"></i> Novo Comprovante
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-primary" id="btnExportar">
|
||||
<i class="fas fa-file-export"></i> Exportar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-hover" id="tabelaComprovantes">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Militante</th>
|
||||
<th>Data</th>
|
||||
<th>Forma de Pagamento</th>
|
||||
<th>Campanha</th>
|
||||
<th>Centralizações</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for comprovante in comprovantes %}
|
||||
<tr>
|
||||
<td>{{ comprovante.id }}</td>
|
||||
<td>{{ comprovante.militante.nome }}</td>
|
||||
<td>{{ comprovante.data_comprovante.strftime('%d/%m/%Y') }}</td>
|
||||
<td>{{ comprovante.forma_pagamento }}</td>
|
||||
<td>{{ comprovante.campanha.nome if comprovante.campanha else '-' }}</td>
|
||||
<td>
|
||||
<ul class="list-unstyled">
|
||||
{% for centralizacao in comprovante.centralizacoes %}
|
||||
<li>{{ centralizacao.tipo_comprovante }}: R$ {{ "%.2f"|format(centralizacao.valor) }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</td>
|
||||
<td>
|
||||
<button type="button"
|
||||
class="btn btn-sm btn-outline-primary"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalEditarComprovante"
|
||||
data-comprovante-id="{{ comprovante.id }}"
|
||||
data-militante-id="{{ comprovante.militante_id }}"
|
||||
data-militante-nome="{{ comprovante.militante.nome }}"
|
||||
data-data-comprovante="{{ comprovante.data_comprovante.strftime('%Y-%m-%d') }}"
|
||||
title="Editar">
|
||||
<i class="fas fa-edit"></i>
|
||||
</button>
|
||||
<button type="button"
|
||||
class="btn btn-sm btn-outline-danger"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalExcluirComprovante"
|
||||
data-comprovante-id="{{ comprovante.id }}"
|
||||
data-comprovante-info="Comprovante de {{ comprovante.militante.nome }} - Total: R$ {{ "%.2f"|format(comprovante.centralizacoes|sum(attribute='valor')) }}"
|
||||
title="Excluir">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Novo Comprovante -->
|
||||
<div class="modal fade" id="novoComprovanteModal" tabindex="-1" aria-labelledby="novoComprovanteModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="novoComprovanteModalLabel">Novo Comprovante</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="novoComprovanteForm">
|
||||
<!-- Dados únicos do comprovante -->
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-6">
|
||||
<label for="militante_id" class="form-label">Militante</label>
|
||||
<select class="form-select" id="militante_id" name="militante_id" required>
|
||||
<option value="">Selecione o militante</option>
|
||||
{% for militante in militantes %}
|
||||
<option value="{{ militante.id }}">{{ militante.nome }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label for="data_comprovante" class="form-label">Data do Comprovante</label>
|
||||
<input type="date" class="form-control" id="data_comprovante" name="data_comprovante" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mb-3">
|
||||
<div class="col-md-6">
|
||||
<label for="forma_pagamento" class="form-label">Forma de Pagamento</label>
|
||||
<select class="form-select" id="forma_pagamento" name="forma_pagamento" required>
|
||||
<option value="">Selecione a forma de pagamento</option>
|
||||
<option value="PIX">PIX</option>
|
||||
<option value="TRANSFERENCIA">Transferência/DOC</option>
|
||||
<option value="DEPOSITO">Depósito</option>
|
||||
<option value="MAQUININHA">Maquininha</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label for="campanha_id" class="form-label">Campanha</label>
|
||||
<select class="form-select" id="campanha_id" name="campanha_id">
|
||||
<option value="">Selecione a campanha</option>
|
||||
{% for campanha in campanhas %}
|
||||
<option value="{{ campanha.id }}">{{ campanha.nome }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Centralizações -->
|
||||
<div class="centralizacoes-container">
|
||||
<h6 class="mb-3">Centralizações</h6>
|
||||
<div class="centralizacao-item mb-3">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Tipo de Comprovante</label>
|
||||
<select class="form-select tipo-comprovante" name="tipo_comprovante[]" required>
|
||||
<option value="">Selecione o tipo</option>
|
||||
<option value="COTA">Cota</option>
|
||||
<option value="JORNAL">Jornal</option>
|
||||
<option value="ASSINATURA">Assinatura</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label">Valor</label>
|
||||
<input type="number" class="form-control valor" name="valor[]" step="0.01" required>
|
||||
</div>
|
||||
<div class="col-md-1 d-flex align-items-end">
|
||||
<button type="button" class="btn btn-danger btn-sm remover-centralizacao">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="btn btn-secondary btn-sm mb-3" id="adicionar-centralizacao">
|
||||
<i class="bi bi-plus"></i> Adicionar Centralização
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="button" class="btn btn-primary" id="salvarComprovante">Salvar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.centralizacao-item {
|
||||
background-color: #f8f9fa;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid #dee2e6;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Adicionar nova centralização
|
||||
document.getElementById('adicionar-centralizacao').addEventListener('click', function() {
|
||||
const container = document.querySelector('.centralizacoes-container');
|
||||
const newItem = document.querySelector('.centralizacao-item').cloneNode(true);
|
||||
newItem.querySelector('.valor').value = '';
|
||||
newItem.querySelector('.tipo-comprovante').value = '';
|
||||
container.appendChild(newItem);
|
||||
});
|
||||
|
||||
// Remover centralização
|
||||
document.addEventListener('click', function(e) {
|
||||
if (e.target.closest('.remover-centralizacao')) {
|
||||
const centralizacoes = document.querySelectorAll('.centralizacao-item');
|
||||
if (centralizacoes.length > 1) {
|
||||
e.target.closest('.centralizacao-item').remove();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Salvar comprovante
|
||||
document.getElementById('salvarComprovante').addEventListener('click', function() {
|
||||
const form = document.getElementById('novoComprovanteForm');
|
||||
const formData = new FormData(form);
|
||||
|
||||
// Coletar dados das centralizações
|
||||
const centralizacoes = [];
|
||||
document.querySelectorAll('.centralizacao-item').forEach(item => {
|
||||
centralizacoes.push({
|
||||
tipo_comprovante: item.querySelector('.tipo-comprovante').value,
|
||||
valor: item.querySelector('.valor').value
|
||||
});
|
||||
});
|
||||
|
||||
// Adicionar centralizações ao formData
|
||||
formData.append('centralizacoes', JSON.stringify(centralizacoes));
|
||||
|
||||
fetch('/comprovantes/novo', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
alert(data.message || 'Erro ao salvar comprovante');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
alert('Erro ao salvar comprovante');
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Modal Editar Comprovante -->
|
||||
<div class="modal fade" id="modalEditarComprovante" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"><i class="fas fa-edit"></i> Editar Comprovante</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="formEditarComprovante" method="post">
|
||||
<div class="mb-3">
|
||||
<label for="editMilitante" class="form-label">Militante:</label>
|
||||
<input type="text" class="form-control bg-light" id="editMilitanteNome" readonly>
|
||||
<input type="hidden" id="editMilitante" name="militante_id">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="editTipoComprovante" class="form-label">Tipo de Comprovante:</label>
|
||||
<select class="form-select" id="editTipoComprovante" name="tipo_comprovante" required>
|
||||
<option value="">Selecione o tipo</option>
|
||||
<option value="1">Cota</option>
|
||||
{% if current_user.has_permission('gerenciar_tipos_comprovante') %}
|
||||
<option value="2">Contribuição Extra</option>
|
||||
<option value="3">Doação</option>
|
||||
<option value="4">Taxa de Evento</option>
|
||||
<option value="5">Jornal Avulso</option>
|
||||
<option value="6">Assinatura de Jornal</option>
|
||||
<option value="7">Campanha Financeira</option>
|
||||
<option value="8">Outros</option>
|
||||
{% endif %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="editValor" class="form-label">Valor:</label>
|
||||
<input type="number" step="0.01" class="form-control" id="editValor" name="valor" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="editDataComprovante" class="form-label">Data do Comprovante:</label>
|
||||
<input type="date" class="form-control" id="editDataComprovante" name="data_comprovante" required>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary">Salvar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Excluir Comprovante -->
|
||||
<div class="modal fade" id="modalExcluirComprovante" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"><i class="fas fa-trash"></i> Excluir Comprovante</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Tem certeza que deseja excluir este comprovante?</p>
|
||||
<p id="comprovanteInfo" class="text-muted"></p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<form id="formExcluirComprovante" method="post">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-danger">Excluir</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/comprovantes.js') }}"></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,24 +1,35 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block head %}
|
||||
<!-- Bootstrap Datepicker CSS -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
|
||||
{% endblock %}
|
||||
|
||||
{% block title %}Militantes{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row mb-4">
|
||||
<div class="container-fluid">
|
||||
<div class="row mb-4">
|
||||
<div class="col-12">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<h1 class="h3 mb-0">
|
||||
<i class="fas fa-users me-2"></i>Militantes
|
||||
</h1>
|
||||
{% if current_user.has_permission('gerenciar_militantes') %}
|
||||
<div>
|
||||
<button type="button" class="btn btn-outline-primary me-2" id="btnExportar">
|
||||
<i class="fas fa-file-export me-2"></i>Exportar
|
||||
</button>
|
||||
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalNovoMilitante">
|
||||
<i class="fas fa-user-plus me-2"></i>Novo Militante
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="row mb-4">
|
||||
<div class="col-md-6">
|
||||
@@ -39,19 +50,23 @@
|
||||
<li><a class="dropdown-item" href="#" data-filter="todos">Todos</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><h6 class="dropdown-header">Responsabilidades</h6></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="financas">Finanças</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="imprensa">Imprensa</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="responsavel-financas">Responsável de Finanças</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="responsavel-imprensa">Responsável de Imprensa</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="quadro-orientador">Quadro-Orientador</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="secretario">Secretário</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="tesoureiro">Tesoureiro</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="imprensa">Imprensa</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="mns">MNS</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="mps">MPS</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="juventude">Juventude</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="aspirante">Aspirante</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><h6 class="dropdown-header">Célula</h6></li>
|
||||
{% for celula in celulas %}
|
||||
<li><a class="dropdown-item" href="#" data-filter="celula" data-celula="{{ celula.nome }}">{{ celula.nome }}</a></li>
|
||||
<li><a class="dropdown-item" href="#" data-filter="celula" data-celula="{{ celula.id }}">{{ celula.nome }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-outline-primary btn-fixed-width" type="button" id="btnExportar">
|
||||
<i class="fas fa-file-export me-2"></i>Exportar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -63,44 +78,61 @@
|
||||
<th data-sort="cpf">CPF <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="email">Email <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="telefone">Telefone <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="celula">Célula <i class="fas fa-sort"></i></th>
|
||||
<th>Responsabilidades</th>
|
||||
<th class="text-end">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for militante in militantes %}
|
||||
<tr data-militante="{{ militante.id }}" data-filiado="{{ 'sim' if militante.filiado else 'nao' }}">
|
||||
<tr data-militante="{{ militante.id }}"
|
||||
data-celula-id="{{ militante.celula_id }}"
|
||||
data-responsabilidades="{{ militante.responsabilidades }}">
|
||||
<td data-nome="{{ militante.nome }}">{{ militante.nome }}</td>
|
||||
<td data-cpf="{{ militante.cpf }}">{{ militante.cpf }}</td>
|
||||
<td data-email="{{ militante.email }}">{{ militante.email }}</td>
|
||||
<td data-telefone="{{ militante.telefone }}">{{ militante.telefone }}</td>
|
||||
<td data-celula="{{ militante.celula.nome }}">{{ militante.celula.nome }}</td>
|
||||
<td data-email="{{ militante.emails[0].endereco_email if militante.emails else '' }}">{{ militante.emails[0].endereco_email if militante.emails else '' }}</td>
|
||||
<td data-telefone="{{ militante.telefone1 }}">{{ militante.telefone1 }}</td>
|
||||
<td>
|
||||
{% if militante.responsabilidades is defined and militante.responsabilidades %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.RESPONSAVEL_FINANCAS) %}
|
||||
<span class="badge bg-primary">Finanças</span>
|
||||
<span class="badge bg-primary" title="Responsável de Finanças">RFI</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.RESPONSAVEL_IMPRENSA) %}
|
||||
<span class="badge bg-info">Imprensa</span>
|
||||
<span class="badge bg-info" title="Responsável de Imprensa">RIM</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.QUADRO_ORIENTADOR) %}
|
||||
<span class="badge bg-success">Quadro-Orientador</span>
|
||||
<span class="badge bg-success" title="Quadro-Orientador">QOR</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.SECRETARIO) %}
|
||||
<span class="badge bg-secondary" title="Secretário">SEC</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.TESOUREIRO) %}
|
||||
<span class="badge bg-warning" title="Tesoureiro">TES</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.IMPRENSA) %}
|
||||
<span class="badge bg-danger" title="Imprensa">IMP</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.MNS) %}
|
||||
<span class="badge bg-purple" title="MNS">MNS</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.MPS) %}
|
||||
<span class="badge bg-teal" title="MPS">MPS</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.JUVENTUDE) %}
|
||||
<span class="badge bg-orange" title="Juventude">JUV</span>
|
||||
{% endif %}
|
||||
{% if militante.responsabilidades|bitwise_and(Militante.ASPIRANTE) %}
|
||||
<span class="badge bg-dark" title="Aspirante">ASP</span>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-end">
|
||||
<div class="btn-group">
|
||||
{% if current_user.has_permission('gerenciar_militantes') %}
|
||||
<button type="button"
|
||||
class="btn btn-sm btn-outline-primary"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalEditarMilitante"
|
||||
data-militante-id="{{ militante.id }}"
|
||||
data-militante-nome="{{ militante.nome }}"
|
||||
data-militante-cpf="{{ militante.cpf }}"
|
||||
data-militante-email="{{ militante.email }}"
|
||||
data-militante-telefone="{{ militante.telefone }}"
|
||||
data-militante-endereco="{{ militante.endereco }}"
|
||||
data-militante-filiado="{{ militante.filiado }}"
|
||||
title="Editar">
|
||||
<i class="fas fa-edit"></i>
|
||||
</button>
|
||||
@@ -113,7 +145,6 @@
|
||||
title="Excluir">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -153,6 +184,9 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modais -->
|
||||
@@ -162,11 +196,70 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/militantes.js') }}"></script>
|
||||
<!-- jQuery -->
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
|
||||
<!-- jQuery Mask Plugin -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
|
||||
|
||||
<!-- Nosso script -->
|
||||
<script src="{{ url_for('static', filename='js/militantes.js') }}"></script>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
<style>
|
||||
/* Estilo para o botão Novo Militante */
|
||||
.btn-primary {
|
||||
background-color: var(--bs-danger);
|
||||
border-color: var(--bs-danger);
|
||||
}
|
||||
|
||||
.btn-primary:hover,
|
||||
.btn-primary:focus,
|
||||
.btn-primary:active {
|
||||
background-color: var(--bs-danger-dark, #b02a37) !important;
|
||||
border-color: var(--bs-danger-dark, #b02a37) !important;
|
||||
}
|
||||
|
||||
/* Estilo para os switches */
|
||||
.form-check-input {
|
||||
background-color: #fff;
|
||||
border-color: rgba(220, 53, 69, 0.5);
|
||||
}
|
||||
|
||||
.form-check-input:checked {
|
||||
background-color: var(--bs-danger);
|
||||
border-color: var(--bs-danger);
|
||||
}
|
||||
|
||||
.form-check-input:focus {
|
||||
border-color: var(--bs-danger);
|
||||
box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
|
||||
}
|
||||
|
||||
.form-switch .form-check-input {
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%28220, 53, 69, 0.85%29'/%3e%3c/svg%3e");
|
||||
background-position: left center;
|
||||
border-radius: 2em;
|
||||
transition: background-position .15s ease-in-out;
|
||||
}
|
||||
|
||||
.form-switch .form-check-input:checked {
|
||||
background-position: right center;
|
||||
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e");
|
||||
}
|
||||
|
||||
.form-check {
|
||||
min-height: 1.5rem;
|
||||
padding-left: 2.8em;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.form-check-label {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Estilo para o backdrop com blur em todos os modais */
|
||||
.modal-backdrop.show {
|
||||
backdrop-filter: blur(8px);
|
||||
@@ -238,7 +331,41 @@ th[data-sort].sort-desc i {
|
||||
/* Estilo para badges */
|
||||
.badge {
|
||||
font-weight: 500;
|
||||
padding: 0.5em 0.8em;
|
||||
padding: 0.4em 0.6em;
|
||||
font-size: 0.75rem;
|
||||
margin-right: 0.3rem;
|
||||
min-width: 2em;
|
||||
text-align: center;
|
||||
border-radius: 4px;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.badge:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
/* Cores personalizadas para badges */
|
||||
.bg-purple { background-color: #6f42c1 !important; color: white !important; }
|
||||
.bg-teal { background-color: #20c997 !important; color: white !important; }
|
||||
.bg-orange { background-color: #fd7e14 !important; color: white !important; }
|
||||
.bg-indigo { background-color: #6610f2 !important; color: white !important; }
|
||||
.bg-pink { background-color: #d63384 !important; color: white !important; }
|
||||
|
||||
/* Cores do Bootstrap que vamos usar */
|
||||
.badge.bg-primary { background-color: #0d6efd !important; }
|
||||
.badge.bg-info { background-color: #0dcaf0 !important; }
|
||||
.badge.bg-success { background-color: #198754 !important; }
|
||||
.badge.bg-danger { background-color: #dc3545 !important; }
|
||||
.badge.bg-dark { background-color: #212529 !important; }
|
||||
|
||||
/* Tooltip personalizado */
|
||||
.tooltip {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.tooltip .tooltip-inner {
|
||||
padding: 0.5rem 0.75rem;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
/* Estilo para botões de ação */
|
||||
@@ -294,5 +421,91 @@ th[data-sort].sort-desc i {
|
||||
min-width: 120px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Estilos personalizados para o Bootstrap Datepicker */
|
||||
.datepicker {
|
||||
padding: 4px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #dee2e6;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
|
||||
font-size: 0.875rem;
|
||||
background-color: white !important;
|
||||
color: #212529 !important;
|
||||
}
|
||||
|
||||
.datepicker table {
|
||||
background-color: white !important;
|
||||
}
|
||||
|
||||
.datepicker table tr td,
|
||||
.datepicker table tr th {
|
||||
text-align: center;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 2px;
|
||||
color: #212529 !important;
|
||||
background-color: white !important;
|
||||
}
|
||||
|
||||
.datepicker table tr td.day:hover,
|
||||
.datepicker table tr td.focused {
|
||||
background: #f8f9fa !important;
|
||||
color: #212529 !important;
|
||||
}
|
||||
|
||||
.datepicker table tr td.active,
|
||||
.datepicker table tr td.active:hover {
|
||||
background-color: var(--bs-primary) !important;
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.datepicker table tr td.today {
|
||||
background-color: #e9ecef !important;
|
||||
color: #212529 !important;
|
||||
}
|
||||
|
||||
.datepicker .datepicker-switch,
|
||||
.datepicker .prev,
|
||||
.datepicker .next {
|
||||
font-weight: normal;
|
||||
padding: 4px;
|
||||
color: #212529 !important;
|
||||
background-color: white !important;
|
||||
}
|
||||
|
||||
.datepicker .dow {
|
||||
font-weight: normal;
|
||||
padding: 4px;
|
||||
color: #212529 !important;
|
||||
background-color: white !important;
|
||||
}
|
||||
|
||||
.datepicker-dropdown:after {
|
||||
border-bottom-color: white !important;
|
||||
}
|
||||
|
||||
.datepicker-dropdown.datepicker-orient-top:after {
|
||||
border-top-color: white !important;
|
||||
}
|
||||
|
||||
/* Estilo para os campos de data */
|
||||
.datepicker-input {
|
||||
background-color: white !important;
|
||||
color: #212529 !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.datepicker-clear-btn {
|
||||
color: #6c757d !important;
|
||||
background-color: white !important;
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.datepicker-clear-btn:hover {
|
||||
background-color: #f8f9fa !important;
|
||||
color: #495057 !important;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
@@ -1,203 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Pagamentos{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container-fluid mt-3">
|
||||
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||
<h2><i class="fas fa-money-bill-wave"></i> Pagamentos</h2>
|
||||
<div>
|
||||
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalNovoPagamento">
|
||||
<i class="fas fa-plus"></i> Novo Pagamento
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-primary" id="btnExportar">
|
||||
<i class="fas fa-file-export"></i> Exportar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-hover" id="tabelaPagamentos">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Militante</th>
|
||||
<th>Tipo de Pagamento</th>
|
||||
<th>Valor</th>
|
||||
<th>Data do Pagamento</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for pagamento in pagamentos %}
|
||||
<tr>
|
||||
<td data-militante="{{ pagamento.militante_id }}">{{ pagamento.militante.nome if pagamento.militante else 'N/A' }}</td>
|
||||
<td data-tipo="{{ pagamento.tipo_pagamento }}">
|
||||
{% if pagamento.tipo_pagamento == 1 %}
|
||||
Mensalidade
|
||||
{% elif pagamento.tipo_pagamento == 2 %}
|
||||
Contribuição Extra
|
||||
{% elif pagamento.tipo_pagamento == 3 %}
|
||||
Doação
|
||||
{% elif pagamento.tipo_pagamento == 4 %}
|
||||
Taxa de Evento
|
||||
{% elif pagamento.tipo_pagamento == 5 %}
|
||||
Outros
|
||||
{% else %}
|
||||
Não Definido
|
||||
{% endif %}
|
||||
</td>
|
||||
<td data-valor="{{ pagamento.valor }}">R$ {{ "%.2f"|format(pagamento.valor) }}</td>
|
||||
<td data-data="{{ pagamento.data_pagamento }}">{{ pagamento.data_pagamento.strftime('%d/%m/%Y') }}</td>
|
||||
<td>
|
||||
<button type="button"
|
||||
class="btn btn-sm btn-outline-primary"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalEditarPagamento"
|
||||
data-pagamento-id="{{ pagamento.id }}"
|
||||
data-militante-id="{{ pagamento.militante_id }}"
|
||||
data-tipo-pagamento="{{ pagamento.tipo_pagamento }}"
|
||||
data-valor="{{ pagamento.valor }}"
|
||||
data-data-pagamento="{{ pagamento.data_pagamento.strftime('%Y-%m-%d') }}"
|
||||
title="Editar">
|
||||
<i class="fas fa-edit"></i>
|
||||
</button>
|
||||
<button type="button"
|
||||
class="btn btn-sm btn-outline-danger"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalExcluirPagamento"
|
||||
data-pagamento-id="{{ pagamento.id }}"
|
||||
data-pagamento-info="Pagamento de {{ pagamento.militante.nome if pagamento.militante else 'N/A' }} - R$ {{ "%.2f"|format(pagamento.valor) }}"
|
||||
title="Excluir">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Novo Pagamento -->
|
||||
<div class="modal fade" id="modalNovoPagamento" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"><i class="fas fa-plus"></i> Novo Pagamento</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="formNovoPagamento" method="post" action="{{ url_for('adicionar_pagamento') }}">
|
||||
<div class="mb-3">
|
||||
<label for="militante" class="form-label">Militante:</label>
|
||||
<select class="form-select" id="militante" name="militante_id" required>
|
||||
<option value="">Selecione um militante</option>
|
||||
{% for militante in militantes %}
|
||||
<option value="{{ militante.id }}">{{ militante.nome }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="tipoPagamento" class="form-label">Tipo de Pagamento:</label>
|
||||
<select class="form-select" id="tipoPagamento" name="tipo_pagamento" required>
|
||||
<option value="">Selecione o tipo</option>
|
||||
<option value="1">Mensalidade</option>
|
||||
<option value="2">Contribuição Extra</option>
|
||||
<option value="3">Doação</option>
|
||||
<option value="4">Taxa de Evento</option>
|
||||
<option value="5">Outros</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="valor" class="form-label">Valor:</label>
|
||||
<input type="number" step="0.01" class="form-control" id="valor" name="valor" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="dataPagamento" class="form-label">Data do Pagamento:</label>
|
||||
<input type="date" class="form-control" id="dataPagamento" name="data_pagamento" required>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary">Salvar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Editar Pagamento -->
|
||||
<div class="modal fade" id="modalEditarPagamento" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"><i class="fas fa-edit"></i> Editar Pagamento</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form id="formEditarPagamento" method="post">
|
||||
<div class="mb-3">
|
||||
<label for="editMilitante" class="form-label">Militante:</label>
|
||||
<input type="text" class="form-control bg-light" id="editMilitanteNome" readonly>
|
||||
<input type="hidden" id="editMilitante" name="militante_id">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="editTipoPagamento" class="form-label">Tipo de Pagamento:</label>
|
||||
<select class="form-select" id="editTipoPagamento" name="tipo_pagamento" required>
|
||||
<option value="">Selecione o tipo</option>
|
||||
<option value="1">Mensalidade</option>
|
||||
<option value="2">Contribuição Extra</option>
|
||||
<option value="3">Doação</option>
|
||||
<option value="4">Taxa de Evento</option>
|
||||
<option value="5">Outros</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="editValor" class="form-label">Valor:</label>
|
||||
<input type="number" step="0.01" class="form-control" id="editValor" name="valor" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="editDataPagamento" class="form-label">Data do Pagamento:</label>
|
||||
<input type="date" class="form-control" id="editDataPagamento" name="data_pagamento" required>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary">Salvar</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Excluir Pagamento -->
|
||||
<div class="modal fade" id="modalExcluirPagamento" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"><i class="fas fa-trash"></i> Excluir Pagamento</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Tem certeza que deseja excluir este pagamento?</p>
|
||||
<p id="pagamentoInfo" class="text-muted"></p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<form id="formExcluirPagamento" method="post">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-danger">Excluir</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/pagamentos.js') }}"></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}Listar Relatórios de Pagamentos{% endblock %}
|
||||
{% block title %}Listar Relatórios de Comprovantes{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1 class="mb-4">Lista de Relatórios de Pagamentos</h1>
|
||||
<h1 class="mb-4">Lista de Relatórios de Comprovantes</h1>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
@@ -17,7 +17,7 @@
|
||||
{% endwith %}
|
||||
|
||||
<div class="d-flex justify-content-between mb-4">
|
||||
<a href="{{ url_for('novo_relatorio_pagamentos') }}" class="btn btn-success">Novo Relatório</a>
|
||||
<a href="{{ url_for('novo_relatorio_comprovantes') }}" class="btn btn-success">Novo Relatório</a>
|
||||
<a href="{{ url_for('home') }}" class="btn btn-outline-primary">Início</a>
|
||||
</div>
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<th>ID</th>
|
||||
<th>Setor</th>
|
||||
<th>Comitê Central</th>
|
||||
<th>Total de Pagamentos</th>
|
||||
<th>Total de Comprovantes</th>
|
||||
<th>Data do Relatório</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
@@ -39,11 +39,11 @@
|
||||
<td>{{ relatorio.id }}</td>
|
||||
<td>{{ relatorio.setor.nome }}</td>
|
||||
<td>{{ relatorio.comite.nome }}</td>
|
||||
<td>R$ {{ "%.2f"|format(relatorio.total_pagamentos) }}</td>
|
||||
<td>R$ {{ "%.2f"|format(relatorio.total_comprovantes) }}</td>
|
||||
<td>{{ relatorio.data_relatorio.strftime('%d/%m/%Y') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('editar_relatorio_pagamentos', id=relatorio.id) }}" class="btn btn-primary btn-sm">Editar</a>
|
||||
<a href="{{ url_for('deletar_relatorio_pagamentos', id=relatorio.id) }}" class="btn btn-danger btn-sm" onclick="return confirm('Tem certeza que deseja excluir este relatório?')">Excluir</a>
|
||||
<a href="{{ url_for('editar_relatorio_comprovantes', id=relatorio.id) }}" class="btn btn-primary btn-sm">Editar</a>
|
||||
<a href="{{ url_for('deletar_relatorio_comprovantes', id=relatorio.id) }}" class="btn btn-danger btn-sm" onclick="return confirm('Tem certeza que deseja excluir este relatório?')">Excluir</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
@@ -3,47 +3,47 @@
|
||||
{% block title %}Listar Relatórios de Cotas{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1 class="mb-4">Lista de Relatórios de Cotas</h1>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
<div class="alert alert-{{ category }}">{{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<div class="d-flex justify-content-between mb-4">
|
||||
<a href="{{ url_for('novo_relatorio_cotas') }}" class="btn btn-success">Novo Relatório</a>
|
||||
<a href="{{ url_for('home') }}" class="btn btn-outline-primary">Início</a>
|
||||
<div class="container mt-4">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<h5 class="mb-0"><i class="fas fa-file-invoice-dollar me-2"></i>Relatórios de Cotas</h5>
|
||||
<a href="{{ url_for('novo_relatorio_cotas') }}" class="btn btn-success">
|
||||
<i class="fas fa-plus me-2"></i>Novo Relatório
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-hover">
|
||||
<table class="table table-hover" id="relatoriosTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Setor</th>
|
||||
<th>Comitê Central</th>
|
||||
<th>Total de Cotas</th>
|
||||
<th>Data do Relatório</th>
|
||||
<th>Ações</th>
|
||||
<th data-sort="id">ID <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="setor">Setor <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="comite">Comitê Central <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="total">Total de Cotas <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="data">Data do Relatório <i class="fas fa-sort"></i></th>
|
||||
<th class="text-end">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for relatorio in relatorios %}
|
||||
<tr>
|
||||
<td>{{ relatorio.id }}</td>
|
||||
<td>{{ relatorio.setor.nome }}</td>
|
||||
<td>{{ relatorio.comite.nome }}</td>
|
||||
<td>R$ {{ "%.2f"|format(relatorio.total_cotas) }}</td>
|
||||
<td>{{ relatorio.data_relatorio.strftime('%d/%m/%Y') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('editar_relatorio_cotas', id=relatorio.id) }}" class="btn btn-primary btn-sm">Editar</a>
|
||||
<a href="{{ url_for('deletar_relatorio_cotas', id=relatorio.id) }}" class="btn btn-danger btn-sm" onclick="return confirm('Tem certeza que deseja excluir este relatório?')">Excluir</a>
|
||||
<td data-id="{{ relatorio.id }}">{{ relatorio.id }}</td>
|
||||
<td data-setor="{{ relatorio.setor.nome }}">{{ relatorio.setor.nome }}</td>
|
||||
<td data-comite="{{ relatorio.comite.nome }}">{{ relatorio.comite.nome }}</td>
|
||||
<td data-total="{{ relatorio.total_cotas }}">R$ {{ "%.2f"|format(relatorio.total_cotas) }}</td>
|
||||
<td data-data="{{ relatorio.data_relatorio }}">{{ relatorio.data_relatorio.strftime('%d/%m/%Y') }}</td>
|
||||
<td class="text-end">
|
||||
<a href="{{ url_for('editar_relatorio_cotas', id=relatorio.id) }}"
|
||||
class="btn btn-primary btn-sm"
|
||||
title="Editar">
|
||||
<i class="fas fa-edit"></i>
|
||||
</a>
|
||||
<a href="{{ url_for('deletar_relatorio_cotas', id=relatorio.id) }}"
|
||||
class="btn btn-danger btn-sm"
|
||||
onclick="return confirm('Tem certeza que deseja excluir este relatório?')"
|
||||
title="Excluir">
|
||||
<i class="fas fa-trash"></i>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
@@ -53,5 +53,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="{{ url_for('static', filename='js/table_sort.js') }}"></script>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
@@ -3,47 +3,47 @@
|
||||
{% block title %}Listar Relatórios de Vendas{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1 class="mb-4">Lista de Relatórios de Vendas</h1>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
<div class="alert alert-{{ category }}">{{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
|
||||
<div class="d-flex justify-content-between mb-4">
|
||||
<a href="{{ url_for('novo_relatorio_vendas') }}" class="btn btn-success">Novo Relatório</a>
|
||||
<a href="{{ url_for('home') }}" class="btn btn-outline-primary">Início</a>
|
||||
<div class="container mt-4">
|
||||
<div class="card">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<h5 class="mb-0"><i class="fas fa-file-invoice me-2"></i>Relatórios de Vendas</h5>
|
||||
<a href="{{ url_for('novo_relatorio_vendas') }}" class="btn btn-success">
|
||||
<i class="fas fa-plus me-2"></i>Novo Relatório
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-hover">
|
||||
<table class="table table-hover" id="relatoriosTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Setor</th>
|
||||
<th>Comitê Central</th>
|
||||
<th>Total de Vendas</th>
|
||||
<th>Data do Relatório</th>
|
||||
<th>Ações</th>
|
||||
<th data-sort="id">ID <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="setor">Setor <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="comite">Comitê Central <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="total">Total de Vendas <i class="fas fa-sort"></i></th>
|
||||
<th data-sort="data">Data do Relatório <i class="fas fa-sort"></i></th>
|
||||
<th class="text-end">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for relatorio in relatorios %}
|
||||
<tr>
|
||||
<td>{{ relatorio.id }}</td>
|
||||
<td>{{ relatorio.setor.nome }}</td>
|
||||
<td>{{ relatorio.comite.nome }}</td>
|
||||
<td>R$ {{ "%.2f"|format(relatorio.total_vendas) }}</td>
|
||||
<td>{{ relatorio.data_relatorio.strftime('%d/%m/%Y') }}</td>
|
||||
<td>
|
||||
<a href="{{ url_for('editar_relatorio_vendas', id=relatorio.id) }}" class="btn btn-primary btn-sm">Editar</a>
|
||||
<a href="{{ url_for('deletar_relatorio_vendas', id=relatorio.id) }}" class="btn btn-danger btn-sm" onclick="return confirm('Tem certeza que deseja excluir este relatório?')">Excluir</a>
|
||||
<td data-id="{{ relatorio.id }}">{{ relatorio.id }}</td>
|
||||
<td data-setor="{{ relatorio.setor.nome }}">{{ relatorio.setor.nome }}</td>
|
||||
<td data-comite="{{ relatorio.comite.nome }}">{{ relatorio.comite.nome }}</td>
|
||||
<td data-total="{{ relatorio.total_vendas }}">R$ {{ "%.2f"|format(relatorio.total_vendas) }}</td>
|
||||
<td data-data="{{ relatorio.data_relatorio }}">{{ relatorio.data_relatorio.strftime('%d/%m/%Y') }}</td>
|
||||
<td class="text-end">
|
||||
<a href="{{ url_for('editar_relatorio_vendas', id=relatorio.id) }}"
|
||||
class="btn btn-primary btn-sm"
|
||||
title="Editar">
|
||||
<i class="fas fa-edit"></i>
|
||||
</a>
|
||||
<a href="{{ url_for('deletar_relatorio_vendas', id=relatorio.id) }}"
|
||||
class="btn btn-danger btn-sm"
|
||||
onclick="return confirm('Tem certeza que deseja excluir este relatório?')"
|
||||
title="Excluir">
|
||||
<i class="fas fa-trash"></i>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
@@ -53,4 +53,6 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="{{ url_for('static', filename='js/table_sort.js') }}"></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -5,13 +5,7 @@
|
||||
{% block navbar %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="login-container">
|
||||
<div class="login-content">
|
||||
<div class="login-header">
|
||||
<img src="{{ url_for('static', filename='img/logo001-alpha.png') }}" alt="Logo OCI" class="login-logo">
|
||||
<h4 class="login-title">Controles OCI</h4>
|
||||
</div>
|
||||
|
||||
<div class="alert-container">
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
@@ -22,10 +16,17 @@
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
</div>
|
||||
|
||||
<div class="login-container">
|
||||
<div class="login-content">
|
||||
<div class="login-header">
|
||||
<img src="{{ url_for('static', filename='img/logo001-alpha.png') }}" alt="Logo OCI" class="login-logo">
|
||||
<h4 class="login-title">Controles OCI</h4>
|
||||
</div>
|
||||
|
||||
<form method="POST" action="{{ url_for('login') }}" class="needs-validation" novalidate>
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
|
||||
<div class="form-floating mb-3">
|
||||
<input type="text" class="form-control" id="email" name="email" placeholder="Email ou Usuário" required>
|
||||
<label for="email">Email ou Usuário</label>
|
||||
@@ -46,7 +47,7 @@
|
||||
</div>
|
||||
|
||||
<div class="form-floating mb-4">
|
||||
<input type="text" class="form-control" id="otp" name="otp" placeholder="Código OTP" required>
|
||||
<input type="text" class="form-control" id="otp" name="otp" placeholder="Código OTP">
|
||||
<label for="otp">Código OTP</label>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, informe o código OTP.
|
||||
@@ -208,4 +209,7 @@ form {
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/components.css') }}">
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
|
||||
{% endblock %}
|
||||
@@ -21,3 +21,15 @@
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{% include 'modals/militante_editar.html' %}
|
||||
{% include 'modals/militante_excluir.html' %}
|
||||
|
||||
<!-- Scripts -->
|
||||
<script src="{{ url_for('static', filename='js/militantes.js') }}"></script>
|
||||
{% if config.DEBUG %}
|
||||
<script src="{{ url_for('static', filename='js/tests/militantes.test.js') }}"></script>
|
||||
<script>ativarTestesMilitantes();</script>
|
||||
{% endif %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,54 +1,60 @@
|
||||
<!-- Modal de Editar Militante -->
|
||||
<div class="modal fade" id="modalEditarMilitante" tabindex="-1">
|
||||
<div class="modal fade" id="modalEditarMilitante" tabindex="-1" aria-labelledby="modalEditarMilitanteLabel" aria-hidden="true" data-bs-backdrop="true" data-bs-keyboard="true">
|
||||
<div class="modal-dialog modal-lg modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">
|
||||
<h5 class="modal-title" id="modalEditarMilitanteLabel">
|
||||
<i class="fas fa-user-edit me-2"></i>Editar Militante
|
||||
</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
|
||||
</div>
|
||||
<form id="formEditarMilitante" method="POST">
|
||||
<input type="hidden" id="edit_militante_id" name="militante_id">
|
||||
<form id="formEditarMilitante" method="POST" action="/militantes/editar/" novalidate>
|
||||
<input type="hidden" id="edit_militante_id" name="militante_id" value="">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" id="responsabilidades_values" name="responsabilidades_valor" value="0">
|
||||
|
||||
<div class="modal-body">
|
||||
<!-- Nav tabs -->
|
||||
<ul class="nav nav-tabs nav-fill mb-3" role="tablist">
|
||||
<!-- Tabs de navegação -->
|
||||
<ul class="nav nav-tabs nav-fill" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link active" data-bs-toggle="tab" data-bs-target="#edit-dados-basicos" type="button">
|
||||
<button class="nav-link active" data-bs-toggle="tab" data-bs-target="#edit-dados-basicos" type="button" role="tab">
|
||||
<i class="fas fa-user me-2"></i>Dados Básicos
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-contato" type="button">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-contato" type="button" role="tab">
|
||||
<i class="fas fa-address-book me-2"></i>Contato
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-profissional" type="button">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-profissional" type="button" role="tab">
|
||||
<i class="fas fa-briefcase me-2"></i>Profissional
|
||||
</button>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-organizacao" type="button">
|
||||
<i class="fas fa-users me-2"></i>Organização
|
||||
<button class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-organizacao" type="button" role="tab">
|
||||
<i class="fas fa-sitemap me-2"></i>Organização
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<!-- Tab content -->
|
||||
<div class="tab-content">
|
||||
<!-- Conteúdo das tabs -->
|
||||
<div class="tab-content p-3">
|
||||
<!-- Dados Básicos -->
|
||||
<div class="tab-pane fade show active" id="edit-dados-basicos">
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_nome" class="form-label">Nome</label>
|
||||
<input type="text" class="form-control" id="edit_nome" name="nome" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira o nome do militante.
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_cpf" class="form-label">CPF</label>
|
||||
<input type="text" class="form-control" id="edit_cpf" name="cpf" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira um CPF válido.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
@@ -58,17 +64,47 @@
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_data_nascimento" class="form-label">Data de Nascimento</label>
|
||||
<input type="date" class="form-control" id="edit_data_nascimento" name="data_nascimento">
|
||||
<input type="text"
|
||||
class="form-control date-mask"
|
||||
id="edit_data_nascimento"
|
||||
name="data_nascimento"
|
||||
placeholder="DD/MM/AAAA"
|
||||
maxlength="10"
|
||||
pattern="\d{2}/\d{2}/\d{4}"
|
||||
title="Data no formato DD/MM/AAAA">
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira uma data válida no formato DD/MM/AAAA.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_data_entrada" class="form-label">Data de Entrada OCI</label>
|
||||
<input type="date" class="form-control" id="edit_data_entrada" name="data_entrada_oci">
|
||||
<label for="edit_data_entrada_oci" class="form-label">Data de Entrada na OCI</label>
|
||||
<input type="text"
|
||||
class="form-control date-mask"
|
||||
id="edit_data_entrada_oci"
|
||||
name="data_entrada_oci"
|
||||
placeholder="DD/MM/AAAA"
|
||||
maxlength="10"
|
||||
pattern="\d{2}/\d{2}/\d{4}"
|
||||
title="Data no formato DD/MM/AAAA">
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira uma data válida no formato DD/MM/AAAA.
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_data_efetivacao" class="form-label">Data de Efetivação</label>
|
||||
<input type="date" class="form-control" id="edit_data_efetivacao" name="data_efetivacao_oci">
|
||||
<label for="edit_data_efetivacao_oci" class="form-label">Data de Efetivação na OCI</label>
|
||||
<input type="text"
|
||||
class="form-control date-mask"
|
||||
id="edit_data_efetivacao_oci"
|
||||
name="data_efetivacao_oci"
|
||||
placeholder="DD/MM/AAAA"
|
||||
maxlength="10"
|
||||
pattern="\d{2}/\d{2}/\d{4}"
|
||||
title="Data no formato DD/MM/AAAA">
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira uma data válida no formato DD/MM/AAAA.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -89,7 +125,14 @@
|
||||
<!-- Email Principal -->
|
||||
<div class="mb-3">
|
||||
<label for="edit_email" class="form-label">Email Principal</label>
|
||||
<input type="email" class="form-control" id="edit_email" name="email" required>
|
||||
<input type="email"
|
||||
class="form-control"
|
||||
id="edit_email"
|
||||
name="email"
|
||||
required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira um email válido.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Endereço -->
|
||||
@@ -134,22 +177,6 @@
|
||||
|
||||
<!-- Profissional -->
|
||||
<div class="tab-pane fade" id="edit-profissional">
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_profissao" class="form-label">Profissão</label>
|
||||
<input type="text" class="form-control" id="edit_profissao" name="profissao">
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_regime_trabalho" class="form-label">Regime de Trabalho</label>
|
||||
<select class="form-select" id="edit_regime_trabalho" name="regime_trabalho">
|
||||
<option value="">Selecione...</option>
|
||||
<option value="CLT">CLT</option>
|
||||
<option value="Estatutário">Estatutário</option>
|
||||
<option value="Terceirizado">Terceirizado</option>
|
||||
<option value="Autônomo">Autônomo</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="edit_empresa" class="form-label">Empresa</label>
|
||||
@@ -229,27 +256,20 @@
|
||||
</div>
|
||||
</div>
|
||||
<!-- Responsabilidades -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label d-block">Responsabilidades</label>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4">
|
||||
<div class="form-check">
|
||||
<input type="checkbox" class="form-check-input" id="edit_resp_1" name="responsabilidades" value="256">
|
||||
<label class="form-check-label" for="edit_resp_1">Finanças</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="form-check">
|
||||
<input type="checkbox" class="form-check-input" id="edit_resp_2" name="responsabilidades" value="512">
|
||||
<label class="form-check-label" for="edit_resp_2">Imprensa</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<div class="form-check">
|
||||
<input type="checkbox" class="form-check-input" id="edit_resp_4" name="responsabilidades" value="64">
|
||||
<label class="form-check-label" for="edit_resp_4">Quadro-Orientador</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<label class="form-label">Responsabilidades</label>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<span class="badge badge-clickable bg-secondary" data-value="{{ Militante.SECRETARIO }}" data-original-class="bg-secondary" title="Secretário">SEC</span>
|
||||
<span class="badge badge-clickable bg-warning" data-value="{{ Militante.TESOUREIRO }}" data-original-class="bg-warning" title="Tesoureiro">TES</span>
|
||||
<span class="badge badge-clickable bg-danger" data-value="{{ Militante.IMPRENSA }}" data-original-class="bg-danger" title="Imprensa">IMP</span>
|
||||
<span class="badge badge-clickable bg-purple" data-value="{{ Militante.MNS }}" data-original-class="bg-purple" title="MNS">MNS</span>
|
||||
<span class="badge badge-clickable bg-teal" data-value="{{ Militante.MPS }}" data-original-class="bg-teal" title="MPS">MPS</span>
|
||||
<span class="badge badge-clickable bg-orange" data-value="{{ Militante.JUVENTUDE }}" data-original-class="bg-orange" title="Juventude">JUV</span>
|
||||
<span class="badge badge-clickable bg-success" data-value="{{ Militante.QUADRO_ORIENTADOR }}" data-original-class="bg-success" title="Quadro-Orientador">QOR</span>
|
||||
<span class="badge badge-clickable bg-primary" data-value="{{ Militante.RESPONSAVEL_FINANCAS }}" data-original-class="bg-primary" title="Responsável de Finanças">RFI</span>
|
||||
<span class="badge badge-clickable bg-info" data-value="{{ Militante.RESPONSAVEL_IMPRENSA }}" data-original-class="bg-info" title="Responsável de Imprensa">RIM</span>
|
||||
<span class="badge badge-clickable bg-dark" data-value="{{ Militante.ASPIRANTE }}" data-original-class="bg-dark" title="Aspirante">ASP</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -265,3 +285,150 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* Estilo para badges clicáveis */
|
||||
.badge-clickable {
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease-in-out;
|
||||
opacity: 0.7;
|
||||
font-size: 0.8rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
min-width: 50px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.badge-clickable:hover {
|
||||
opacity: 1;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.badge-clickable.active {
|
||||
opacity: 1;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
|
||||
}
|
||||
|
||||
/* Cores personalizadas para badges */
|
||||
.bg-purple {
|
||||
background-color: #6f42c1;
|
||||
}
|
||||
|
||||
.bg-teal {
|
||||
background-color: #20c997;
|
||||
}
|
||||
|
||||
.bg-orange {
|
||||
background-color: #fd7e14;
|
||||
}
|
||||
|
||||
.responsabilidades-container {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 0.375rem;
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
|
||||
/* Cores personalizadas para badges */
|
||||
.bg-purple { background-color: #6f42c1 !important; color: white !important; }
|
||||
.bg-teal { background-color: #20c997 !important; color: white !important; }
|
||||
.bg-orange { background-color: #fd7e14 !important; color: white !important; }
|
||||
.bg-indigo { background-color: #6610f2 !important; color: white !important; }
|
||||
.bg-pink { background-color: #d63384 !important; color: white !important; }
|
||||
|
||||
/* Cores do Bootstrap que vamos usar */
|
||||
.active.bg-primary { background-color: #0d6efd !important; color: white !important; }
|
||||
.active.bg-success { background-color: #198754 !important; color: white !important; }
|
||||
.active.bg-info { background-color: #0dcaf0 !important; color: white !important; }
|
||||
.active.bg-danger { background-color: #dc3545 !important; color: white !important; }
|
||||
.active.bg-dark { background-color: #212529 !important; color: white !important; }
|
||||
|
||||
/* Estilos para as tabs */
|
||||
.nav-tabs {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link {
|
||||
border: none;
|
||||
color: var(--bs-danger);
|
||||
padding: 0.75rem 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link:hover {
|
||||
border: none;
|
||||
color: var(--bs-danger);
|
||||
background-color: rgba(var(--bs-danger-rgb), 0.1);
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link.active {
|
||||
color: var(--bs-danger);
|
||||
background-color: rgba(var(--bs-danger-rgb), 0.1);
|
||||
border-bottom: 2px solid var(--bs-danger);
|
||||
}
|
||||
|
||||
/* Adicionar nav-fill para distribuir as abas igualmente */
|
||||
.nav-tabs {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.nav-tabs .nav-item {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Estilos para o conteúdo das tabs */
|
||||
.tab-content {
|
||||
background-color: #fff;
|
||||
border-radius: 0 0 0.25rem 0.25rem;
|
||||
}
|
||||
|
||||
.tab-pane {
|
||||
padding: 1rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const modalEditarMilitante = document.getElementById('modalEditarMilitante');
|
||||
if (modalEditarMilitante) {
|
||||
modalEditarMilitante.addEventListener('hidden.bs.modal', function() {
|
||||
// Limpar formulário
|
||||
const form = this.querySelector('form');
|
||||
if (form) {
|
||||
form.reset();
|
||||
}
|
||||
|
||||
// Limpar campos hidden
|
||||
document.getElementById('edit_militante_id').value = '';
|
||||
document.getElementById('responsabilidades_values').value = '0';
|
||||
|
||||
// Resetar badges
|
||||
this.querySelectorAll('.badge-clickable').forEach(badge => {
|
||||
badge.classList.remove('active');
|
||||
const originalClass = badge.getAttribute('data-original-class');
|
||||
if (originalClass) {
|
||||
badge.className = `badge badge-clickable ${originalClass}`;
|
||||
}
|
||||
});
|
||||
|
||||
// Limpar mensagens de erro
|
||||
this.querySelectorAll('.is-invalid').forEach(field => {
|
||||
field.classList.remove('is-invalid');
|
||||
});
|
||||
this.querySelectorAll('.invalid-feedback').forEach(feedback => {
|
||||
feedback.style.display = 'none';
|
||||
});
|
||||
|
||||
// Voltar para a primeira aba
|
||||
const firstTab = this.querySelector('button[data-bs-target="#edit-dados-basicos"]');
|
||||
if (firstTab) {
|
||||
firstTab.click();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -57,17 +57,20 @@
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="data_nascimento" class="form-label">Data de Nascimento</label>
|
||||
<input type="date" class="form-control" id="data_nascimento" name="data_nascimento">
|
||||
<input type="text" class="form-control date-mask" id="data_nascimento" name="data_nascimento"
|
||||
placeholder="DD/MM/AAAA" maxlength="10">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="data_entrada" class="form-label">Data de Entrada OCI</label>
|
||||
<input type="date" class="form-control" id="data_entrada" name="data_entrada_oci">
|
||||
<input type="text" class="form-control date-mask" id="data_entrada" name="data_entrada_oci"
|
||||
placeholder="DD/MM/AAAA" maxlength="10">
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label for="data_efetivacao" class="form-label">Data de Efetivação</label>
|
||||
<input type="date" class="form-control" id="data_efetivacao" name="data_efetivacao_oci">
|
||||
<input type="text" class="form-control date-mask" id="data_efetivacao" name="data_efetivacao_oci"
|
||||
placeholder="DD/MM/AAAA" maxlength="10">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -227,19 +230,33 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label d-block">Responsabilidades</label>
|
||||
<div class="row g-3">
|
||||
{% for valor, nome in Militante.get_responsabilidades_list() %}
|
||||
<div class="col-md-6">
|
||||
<div class="form-check">
|
||||
<input type="checkbox" class="form-check-input" id="resp_{{ valor }}"
|
||||
name="responsabilidades" value="{{ valor }}">
|
||||
<label class="form-check-label" for="resp_{{ valor }}">{{ nome }}</label>
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<label class="form-label">Responsabilidades</label>
|
||||
<div class="responsabilidades-container">
|
||||
<input type="hidden" name="responsabilidades" id="novo_responsabilidades_values" value="0">
|
||||
|
||||
<span class="badge badge-clickable bg-secondary" data-value="{{ Militante.SECRETARIO }}" data-bs-toggle="tooltip" title="Clique para alternar">Secretário</span>
|
||||
|
||||
<span class="badge badge-clickable bg-info" data-value="{{ Militante.RESPONSAVEL_IMPRENSA }}" data-bs-toggle="tooltip" title="Clique para alternar">Responsável de Imprensa</span>
|
||||
|
||||
<span class="badge badge-clickable bg-warning text-dark" data-value="{{ Militante.IMPRENSA }}" data-bs-toggle="tooltip" title="Clique para alternar">Imprensa</span>
|
||||
|
||||
<span class="badge badge-clickable bg-warning text-dark" data-value="{{ Militante.MPS }}" data-bs-toggle="tooltip" title="Clique para alternar">MPS</span>
|
||||
|
||||
<span class="badge badge-clickable bg-success" data-value="{{ Militante.QUADRO_ORIENTADOR }}" data-bs-toggle="tooltip" title="Clique para alternar">Quadro-Orientador</span>
|
||||
|
||||
<span class="badge badge-clickable bg-primary" data-value="{{ Militante.RESPONSAVEL_FINANCAS }}" data-bs-toggle="tooltip" title="Clique para alternar">Responsável de Finanças</span>
|
||||
|
||||
<span class="badge badge-clickable bg-dark" data-value="{{ Militante.TESOUREIRO }}" data-bs-toggle="tooltip" title="Clique para alternar">Tesoureiro</span>
|
||||
|
||||
<span class="badge badge-clickable bg-info" data-value="{{ Militante.MNS }}" data-bs-toggle="tooltip" title="Clique para alternar">MNS</span>
|
||||
|
||||
<span class="badge badge-clickable bg-danger" data-value="{{ Militante.JUVENTUDE }}" data-bs-toggle="tooltip" title="Clique para alternar">Juventude</span>
|
||||
|
||||
<span class="badge badge-clickable bg-light text-dark border" data-value="{{ Militante.ASPIRANTE }}" data-bs-toggle="tooltip" title="Clique para alternar">Aspirante</span>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -254,3 +271,33 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.badge-clickable {
|
||||
font-size: 0.9rem;
|
||||
padding: 0.5rem 1rem;
|
||||
margin: 0.3rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
opacity: 0.5;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.badge-clickable:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.badge-clickable.active {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.responsabilidades-container {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid #dee2e6;
|
||||
border-radius: 0.375rem;
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
</style>
|
||||
@@ -31,7 +31,7 @@
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button type="submit" class="btn btn-primary">Registrar</button>
|
||||
<a href="{{ url_for('listar_assinaturas') }}" class="btn btn-secondary">Voltar</a>
|
||||
<a href="{{ url_for('listar_vendas_jornal') }}" class="btn btn-secondary">Voltar</a>
|
||||
<a href="{{ url_for('home') }}" class="btn btn-outline-primary">Início</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}Novo Pagamento{% endblock %}
|
||||
{% block title %}Novo Comprovante{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
@@ -9,7 +9,7 @@
|
||||
<div class="card shadow-sm">
|
||||
<div class="card-header bg-light">
|
||||
<h4 class="card-title mb-0">
|
||||
<i class="fas fa-money-bill-wave me-2"></i>Registrar Novo Pagamento
|
||||
<i class="fas fa-money-bill-wave me-2"></i>Registrar Novo Comprovante
|
||||
</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
@@ -27,17 +27,18 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="tipo_pagamento_id" class="form-label">Tipo de Pagamento:</label>
|
||||
<select class="form-select" id="tipo_pagamento_id" name="tipo_pagamento_id" required>
|
||||
<option value="">Selecione o tipo de pagamento</option>
|
||||
{% for tipo in tipos_pagamento %}
|
||||
<option value="{{ tipo.id }}">{{ tipo.descricao }}</option>
|
||||
{% endfor %}
|
||||
<div class="form-group">
|
||||
<label for="tipo_comprovante_id">Tipo de Comprovante</label>
|
||||
<select class="form-control" id="tipo_comprovante_id" name="tipo_comprovante_id" required>
|
||||
<option value="1">1 - Comprovante Padrão</option>
|
||||
{% if current_user.has_permission('gerenciar_tipos_comprovante') %}
|
||||
<option value="2">2 - Comprovante Especial</option>
|
||||
<option value="3">3 - Comprovante Extraordinário</option>
|
||||
<option value="4">4 - Jornal Avulso</option>
|
||||
<option value="5">5 - Assinatura de Jornal</option>
|
||||
<option value="6">6 - Campanha Financeira</option>
|
||||
{% endif %}
|
||||
</select>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, selecione o tipo de pagamento.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
@@ -52,8 +53,8 @@
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="data_pagamento" class="form-label">Data do Pagamento:</label>
|
||||
<input type="date" class="form-control" id="data_pagamento" name="data_pagamento"
|
||||
<label for="data_comprovante" class="form-label">Data do Comprovante:</label>
|
||||
<input type="date" class="form-control" id="data_comprovante" name="data_comprovante"
|
||||
required max="{{ hoje }}">
|
||||
<div class="invalid-feedback">
|
||||
Por favor, informe uma data válida.
|
||||
@@ -64,7 +65,7 @@
|
||||
<button type="submit" class="btn btn-primary">
|
||||
<i class="fas fa-save me-1"></i>Registrar
|
||||
</button>
|
||||
<a href="{{ url_for('listar_pagamentos') }}" class="btn btn-secondary">
|
||||
<a href="{{ url_for('listar_comprovantes') }}" class="btn btn-secondary">
|
||||
<i class="fas fa-arrow-left me-1"></i>Voltar
|
||||
</a>
|
||||
</div>
|
||||
@@ -1,12 +1,12 @@
|
||||
{% extends 'base.html' %}
|
||||
|
||||
{% block title %}Novo Relatório de Pagamentos{% endblock %}
|
||||
{% block title %}Novo Relatório de Comprovantes{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1 class="mb-4">Novo Relatório de Pagamentos</h1>
|
||||
<h1 class="mb-4">Novo Relatório de Comprovantes</h1>
|
||||
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
@@ -44,10 +44,10 @@
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="total_pagamentos" class="form-label">Total de Pagamentos</label>
|
||||
<input type="number" class="form-control" id="total_pagamentos" name="total_pagamentos" step="0.01" required>
|
||||
<label for="total_comprovantes" class="form-label">Total de Comprovantes</label>
|
||||
<input type="number" class="form-control" id="total_comprovantes" name="total_comprovantes" step="0.01" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira o total de pagamentos.
|
||||
Por favor, insira o total de comprovantes.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
|
||||
<div class="d-flex justify-content-between">
|
||||
<button type="submit" class="btn btn-success">Registrar</button>
|
||||
<a href="{{ url_for('listar_relatorios_pagamentos') }}" class="btn btn-outline-secondary">Voltar</a>
|
||||
<a href="{{ url_for('listar_relatorios_comprovantes') }}" class="btn btn-outline-secondary">Voltar</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -3,11 +3,12 @@
|
||||
{% block title %}Novo Relatório de Cotas{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1 class="mb-4">Novo Relatório de Cotas</h1>
|
||||
|
||||
<div class="container mt-4">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0"><i class="fas fa-file-invoice-dollar me-2"></i>Novo Relatório de Cotas</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
@@ -20,7 +21,7 @@
|
||||
<div class="mb-3">
|
||||
<label for="setor_id" class="form-label">Setor</label>
|
||||
<select class="form-select" id="setor_id" name="setor_id" required>
|
||||
<option value="">Selecione um setor</option>
|
||||
<option value="">Selecione o setor</option>
|
||||
{% for setor in setores %}
|
||||
<option value="{{ setor.id }}">{{ setor.nome }}</option>
|
||||
{% endfor %}
|
||||
@@ -33,35 +34,53 @@
|
||||
<div class="mb-3">
|
||||
<label for="comite_id" class="form-label">Comitê Central</label>
|
||||
<select class="form-select" id="comite_id" name="comite_id" required>
|
||||
<option value="">Selecione um comitê</option>
|
||||
<option value="">Selecione o comitê</option>
|
||||
{% for comite in comites %}
|
||||
<option value="{{ comite.id }}">{{ comite.nome }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, selecione o comitê central.
|
||||
Por favor, selecione o comitê.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="total_cotas" class="form-label">Total de Cotas</label>
|
||||
<input type="number" class="form-control" id="total_cotas" name="total_cotas" step="0.01" required>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">R$</span>
|
||||
<input type="number"
|
||||
class="form-control"
|
||||
id="total_cotas"
|
||||
name="total_cotas"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
required>
|
||||
</div>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira o total de cotas.
|
||||
Por favor, insira um valor válido para o total de cotas.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="data_relatorio" class="form-label">Data do Relatório</label>
|
||||
<input type="date" class="form-control" id="data_relatorio" name="data_relatorio" required>
|
||||
<input type="date"
|
||||
class="form-control"
|
||||
id="data_relatorio"
|
||||
name="data_relatorio"
|
||||
max="{{ hoje }}"
|
||||
required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira a data do relatório.
|
||||
Por favor, insira uma data válida não futura.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between">
|
||||
<button type="submit" class="btn btn-success">Registrar</button>
|
||||
<a href="{{ url_for('listar_relatorios_cotas') }}" class="btn btn-outline-secondary">Voltar</a>
|
||||
<button type="submit" class="btn btn-success">
|
||||
<i class="fas fa-save me-2"></i>Registrar
|
||||
</button>
|
||||
<a href="{{ url_for('listar_relatorios_cotas') }}" class="btn btn-outline-secondary">
|
||||
<i class="fas fa-arrow-left me-2"></i>Voltar
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -73,20 +92,51 @@
|
||||
(function () {
|
||||
'use strict'
|
||||
|
||||
var forms = document.querySelectorAll('.needs-validation')
|
||||
const forms = document.querySelectorAll('.needs-validation');
|
||||
|
||||
Array.prototype.slice.call(forms)
|
||||
.forEach(function (form) {
|
||||
form.addEventListener('submit', function (event) {
|
||||
forms.forEach(form => {
|
||||
form.addEventListener('submit', event => {
|
||||
if (!form.checkValidity()) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
form.classList.add('was-validated')
|
||||
}, false)
|
||||
})
|
||||
})()
|
||||
// Validar valor mínimo
|
||||
const totalCotas = form.querySelector('#total_cotas');
|
||||
if (totalCotas.value <= 0) {
|
||||
totalCotas.setCustomValidity('O valor deve ser maior que zero');
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
} else {
|
||||
totalCotas.setCustomValidity('');
|
||||
}
|
||||
|
||||
// Validar data não futura
|
||||
const dataRelatorio = form.querySelector('#data_relatorio');
|
||||
const hoje = new Date();
|
||||
hoje.setHours(0, 0, 0, 0);
|
||||
const dataSelecionada = new Date(dataRelatorio.value);
|
||||
|
||||
if (dataSelecionada > hoje) {
|
||||
dataRelatorio.setCustomValidity('A data não pode ser futura');
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
} else {
|
||||
dataRelatorio.setCustomValidity('');
|
||||
}
|
||||
|
||||
form.classList.add('was-validated');
|
||||
}, false);
|
||||
|
||||
// Limpar validação ao mudar valor
|
||||
const inputs = form.querySelectorAll('input, select');
|
||||
inputs.forEach(input => {
|
||||
input.addEventListener('input', () => {
|
||||
input.setCustomValidity('');
|
||||
});
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
{% block title %}Novo Relatório de Vendas{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
<h1 class="mb-4">Novo Relatório de Vendas</h1>
|
||||
|
||||
<div class="container mt-4">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0"><i class="fas fa-file-invoice me-2"></i>Novo Relatório de Vendas</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
@@ -20,7 +21,7 @@
|
||||
<div class="mb-3">
|
||||
<label for="setor_id" class="form-label">Setor</label>
|
||||
<select class="form-select" id="setor_id" name="setor_id" required>
|
||||
<option value="">Selecione um setor</option>
|
||||
<option value="">Selecione o setor</option>
|
||||
{% for setor in setores %}
|
||||
<option value="{{ setor.id }}">{{ setor.nome }}</option>
|
||||
{% endfor %}
|
||||
@@ -33,35 +34,53 @@
|
||||
<div class="mb-3">
|
||||
<label for="comite_id" class="form-label">Comitê Central</label>
|
||||
<select class="form-select" id="comite_id" name="comite_id" required>
|
||||
<option value="">Selecione um comitê</option>
|
||||
<option value="">Selecione o comitê</option>
|
||||
{% for comite in comites %}
|
||||
<option value="{{ comite.id }}">{{ comite.nome }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, selecione o comitê central.
|
||||
Por favor, selecione o comitê.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="total_vendas" class="form-label">Total de Vendas</label>
|
||||
<input type="number" class="form-control" id="total_vendas" name="total_vendas" step="0.01" required>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text">R$</span>
|
||||
<input type="number"
|
||||
class="form-control"
|
||||
id="total_vendas"
|
||||
name="total_vendas"
|
||||
step="0.01"
|
||||
min="0.01"
|
||||
required>
|
||||
</div>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira o total de vendas.
|
||||
Por favor, insira um valor válido para o total de vendas.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="data_relatorio" class="form-label">Data do Relatório</label>
|
||||
<input type="date" class="form-control" id="data_relatorio" name="data_relatorio" required>
|
||||
<input type="date"
|
||||
class="form-control"
|
||||
id="data_relatorio"
|
||||
name="data_relatorio"
|
||||
max="{{ hoje }}"
|
||||
required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira a data do relatório.
|
||||
Por favor, insira uma data válida não futura.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between">
|
||||
<button type="submit" class="btn btn-success">Registrar</button>
|
||||
<a href="{{ url_for('listar_relatorios_vendas') }}" class="btn btn-outline-secondary">Voltar</a>
|
||||
<button type="submit" class="btn btn-success">
|
||||
<i class="fas fa-save me-2"></i>Registrar
|
||||
</button>
|
||||
<a href="{{ url_for('listar_relatorios_vendas') }}" class="btn btn-outline-secondary">
|
||||
<i class="fas fa-arrow-left me-2"></i>Voltar
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -73,19 +92,50 @@
|
||||
(function () {
|
||||
'use strict'
|
||||
|
||||
var forms = document.querySelectorAll('.needs-validation')
|
||||
const forms = document.querySelectorAll('.needs-validation');
|
||||
|
||||
Array.prototype.slice.call(forms)
|
||||
.forEach(function (form) {
|
||||
form.addEventListener('submit', function (event) {
|
||||
forms.forEach(form => {
|
||||
form.addEventListener('submit', event => {
|
||||
if (!form.checkValidity()) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
form.classList.add('was-validated')
|
||||
}, false)
|
||||
})
|
||||
})()
|
||||
// Validar valor mínimo
|
||||
const totalVendas = form.querySelector('#total_vendas');
|
||||
if (totalVendas.value <= 0) {
|
||||
totalVendas.setCustomValidity('O valor deve ser maior que zero');
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
} else {
|
||||
totalVendas.setCustomValidity('');
|
||||
}
|
||||
|
||||
// Validar data não futura
|
||||
const dataRelatorio = form.querySelector('#data_relatorio');
|
||||
const hoje = new Date();
|
||||
hoje.setHours(0, 0, 0, 0);
|
||||
const dataSelecionada = new Date(dataRelatorio.value);
|
||||
|
||||
if (dataSelecionada > hoje) {
|
||||
dataRelatorio.setCustomValidity('A data não pode ser futura');
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
} else {
|
||||
dataRelatorio.setCustomValidity('');
|
||||
}
|
||||
|
||||
form.classList.add('was-validated');
|
||||
}, false);
|
||||
|
||||
// Limpar validação ao mudar valor
|
||||
const inputs = form.querySelectorAll('input, select');
|
||||
inputs.forEach(input => {
|
||||
input.addEventListener('input', () => {
|
||||
input.setCustomValidity('');
|
||||
});
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
89
tests/test_routes.py
Normal file
89
tests/test_routes.py
Normal file
@@ -0,0 +1,89 @@
|
||||
import pytest
|
||||
from flask import url_for
|
||||
from app import create_app
|
||||
from functions.database import get_db_connection, init_database
|
||||
import os
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
app = create_app()
|
||||
app.config['TESTING'] = True
|
||||
app.config['WTF_CSRF_ENABLED'] = False
|
||||
|
||||
# Criar banco de dados temporário para testes
|
||||
with app.app_context():
|
||||
init_database()
|
||||
|
||||
yield app
|
||||
|
||||
@pytest.fixture
|
||||
def client(app):
|
||||
return app.test_client()
|
||||
|
||||
@pytest.fixture
|
||||
def runner(app):
|
||||
return app.test_cli_runner()
|
||||
|
||||
def test_home_page(client):
|
||||
response = client.get('/')
|
||||
assert response.status_code == 302 # Redireciona para login
|
||||
|
||||
def test_login_page(client):
|
||||
response = client.get('/login')
|
||||
assert response.status_code == 200
|
||||
assert b'Login' in response.data
|
||||
|
||||
def test_listar_assinaturas_jornal(client):
|
||||
# Primeiro fazer login
|
||||
client.post('/login', data={
|
||||
'username': 'admin',
|
||||
'password': 'admin123'
|
||||
})
|
||||
|
||||
response = client.get('/assinaturas/jornal')
|
||||
assert response.status_code == 200
|
||||
assert b'Assinaturas de Jornal' in response.data
|
||||
|
||||
def test_nova_assinatura_jornal(client):
|
||||
# Primeiro fazer login
|
||||
client.post('/login', data={
|
||||
'username': 'admin',
|
||||
'password': 'admin123'
|
||||
})
|
||||
|
||||
response = client.get('/assinaturas/jornal/novo')
|
||||
assert response.status_code == 200
|
||||
assert b'Registrar Nova Assinatura Anual' in response.data
|
||||
|
||||
def test_listar_militantes(client):
|
||||
# Primeiro fazer login
|
||||
client.post('/login', data={
|
||||
'username': 'admin',
|
||||
'password': 'admin123'
|
||||
})
|
||||
|
||||
response = client.get('/militantes')
|
||||
assert response.status_code == 200
|
||||
assert b'Militantes' in response.data
|
||||
|
||||
def test_listar_cotas(client):
|
||||
# Primeiro fazer login
|
||||
client.post('/login', data={
|
||||
'username': 'admin',
|
||||
'password': 'admin123'
|
||||
})
|
||||
|
||||
response = client.get('/cotas')
|
||||
assert response.status_code == 200
|
||||
assert b'Cotas' in response.data
|
||||
|
||||
def test_listar_materiais(client):
|
||||
# Primeiro fazer login
|
||||
client.post('/login', data={
|
||||
'username': 'admin',
|
||||
'password': 'admin123'
|
||||
})
|
||||
|
||||
response = client.get('/materiais')
|
||||
assert response.status_code == 200
|
||||
assert b'Materiais' in response.data
|
||||
171
utils/date_utils.py
Normal file
171
utils/date_utils.py
Normal file
@@ -0,0 +1,171 @@
|
||||
from datetime import datetime, date
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def validar_data(data_str: str, formato: str = '%Y-%m-%d') -> bool:
|
||||
"""
|
||||
Valida se uma string representa uma data válida no formato especificado.
|
||||
|
||||
Args:
|
||||
data_str: String contendo a data
|
||||
formato: Formato esperado da data (default: YYYY-MM-DD)
|
||||
|
||||
Returns:
|
||||
bool: True se a data é válida, False caso contrário
|
||||
"""
|
||||
if not data_str:
|
||||
return True
|
||||
|
||||
try:
|
||||
datetime.strptime(data_str, formato)
|
||||
return True
|
||||
except ValueError as e:
|
||||
logger.warning(f"Data inválida: {data_str} (formato esperado: {formato}). Erro: {e}")
|
||||
return False
|
||||
|
||||
def converter_data(data_str: str, formato_entrada: str = '%Y-%m-%d', formato_saida: str = None) -> date:
|
||||
"""
|
||||
Converte uma string de data para um objeto date.
|
||||
|
||||
Args:
|
||||
data_str: String contendo a data
|
||||
formato_entrada: Formato da data de entrada (default: YYYY-MM-DD)
|
||||
formato_saida: Se especificado, retorna a data como string neste formato
|
||||
|
||||
Returns:
|
||||
date: Objeto date se formato_saida=None, string formatada caso contrário
|
||||
|
||||
Raises:
|
||||
ValueError: Se a data for inválida
|
||||
"""
|
||||
if not data_str:
|
||||
return None
|
||||
|
||||
try:
|
||||
data = datetime.strptime(data_str, formato_entrada).date()
|
||||
|
||||
if formato_saida:
|
||||
return data.strftime(formato_saida)
|
||||
return data
|
||||
except ValueError as e:
|
||||
logger.error(f"Erro ao converter data '{data_str}': {e}")
|
||||
raise ValueError(f"Data inválida: {data_str}. Use o formato {formato_entrada}")
|
||||
|
||||
def validar_sequencia_datas(data_nascimento: date = None,
|
||||
data_entrada: date = None,
|
||||
data_efetivacao: date = None) -> None:
|
||||
"""
|
||||
Valida a sequência lógica entre datas.
|
||||
|
||||
Args:
|
||||
data_nascimento: Data de nascimento
|
||||
data_entrada: Data de entrada na OCI
|
||||
data_efetivacao: Data de efetivação na OCI
|
||||
|
||||
Raises:
|
||||
ValueError: Se houver inconsistência entre as datas
|
||||
"""
|
||||
hoje = date.today()
|
||||
|
||||
# Validar datas futuras
|
||||
for nome, data in [
|
||||
("Data de nascimento", data_nascimento),
|
||||
("Data de entrada", data_entrada),
|
||||
("Data de efetivação", data_efetivacao)
|
||||
]:
|
||||
if data and data > hoje:
|
||||
logger.warning(f"{nome} no futuro: {data}")
|
||||
raise ValueError(f"{nome} não pode ser no futuro")
|
||||
|
||||
# Validar sequência
|
||||
if data_nascimento and data_entrada and data_nascimento > data_entrada:
|
||||
logger.warning(f"Data de entrada ({data_entrada}) anterior à data de nascimento ({data_nascimento})")
|
||||
raise ValueError("Data de entrada na OCI não pode ser anterior à data de nascimento")
|
||||
|
||||
if data_entrada and data_efetivacao and data_entrada > data_efetivacao:
|
||||
logger.warning(f"Data de efetivação ({data_efetivacao}) anterior à data de entrada ({data_entrada})")
|
||||
raise ValueError("Data de efetivação não pode ser anterior à data de entrada")
|
||||
|
||||
def calcular_idade(data_nascimento: date) -> int:
|
||||
"""
|
||||
Calcula a idade com base na data de nascimento.
|
||||
|
||||
Args:
|
||||
data_nascimento: Data de nascimento
|
||||
|
||||
Returns:
|
||||
int: Idade em anos
|
||||
"""
|
||||
if not data_nascimento:
|
||||
return None
|
||||
|
||||
hoje = date.today()
|
||||
idade = hoje.year - data_nascimento.year
|
||||
|
||||
# Ajustar se ainda não fez aniversário este ano
|
||||
if hoje.month < data_nascimento.month or \
|
||||
(hoje.month == data_nascimento.month and hoje.day < data_nascimento.day):
|
||||
idade -= 1
|
||||
|
||||
return idade
|
||||
|
||||
def converter_data_br(data_str):
|
||||
"""Converte string de data no formato DD/MM/YYYY para objeto date"""
|
||||
if not data_str:
|
||||
return None
|
||||
try:
|
||||
dia, mes, ano = map(int, data_str.split('/'))
|
||||
return date(ano, mes, dia)
|
||||
except (ValueError, TypeError) as e:
|
||||
return None
|
||||
|
||||
def converter_data_iso(data_str):
|
||||
"""Converte string de data no formato YYYY-MM-DD para objeto date"""
|
||||
if not data_str:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(data_str, '%Y-%m-%d').date()
|
||||
except (ValueError, TypeError) as e:
|
||||
return None
|
||||
|
||||
def formatar_data_br(data):
|
||||
"""Formata objeto date para string no formato DD/MM/YYYY"""
|
||||
if not data:
|
||||
return ''
|
||||
if isinstance(data, str):
|
||||
data = converter_data_iso(data) or converter_data_br(data)
|
||||
if not data:
|
||||
return ''
|
||||
return data.strftime('%d/%m/%Y')
|
||||
|
||||
def formatar_data_iso(data):
|
||||
"""Formata objeto date para string no formato YYYY-MM-DD"""
|
||||
if not data:
|
||||
return ''
|
||||
if isinstance(data, str):
|
||||
data = converter_data_br(data) or converter_data_iso(data)
|
||||
if not data:
|
||||
return ''
|
||||
return data.strftime('%Y-%m-%d')
|
||||
|
||||
def validar_data(data, data_maxima=None, data_minima=None):
|
||||
"""Valida se a data está dentro do intervalo permitido"""
|
||||
if not data:
|
||||
return True
|
||||
|
||||
if isinstance(data, str):
|
||||
data = converter_data_br(data) or converter_data_iso(data)
|
||||
if not data:
|
||||
return False
|
||||
|
||||
hoje = date.today()
|
||||
|
||||
if data_maxima and data > data_maxima:
|
||||
return False
|
||||
if data_minima and data < data_minima:
|
||||
return False
|
||||
if data > hoje:
|
||||
return False
|
||||
|
||||
return True
|
||||
Reference in New Issue
Block a user