Limapdo o repo e corrigidos bugs
This commit is contained in:
149
app.py
149
app.py
@@ -15,6 +15,8 @@ from functions.database import (
|
|||||||
Usuario,
|
Usuario,
|
||||||
get_db_connection,
|
get_db_connection,
|
||||||
ComiteRegional,
|
ComiteRegional,
|
||||||
|
Setor,
|
||||||
|
Celula,
|
||||||
)
|
)
|
||||||
from sqlalchemy import create_engine
|
from sqlalchemy import create_engine
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
@@ -27,11 +29,18 @@ from pathlib import Path
|
|||||||
from time import time
|
from time import time
|
||||||
from create_admin import generate_qr_code
|
from create_admin import generate_qr_code
|
||||||
from flask_mail import Mail, Message
|
from flask_mail import Mail, Message
|
||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.secret_key = 'sua_chave_secreta_aqui' # Necessário para sessões do Flask
|
app.secret_key = 'sua_chave_secreta_aqui' # Necessário para sessões do Flask
|
||||||
bootstrap = Bootstrap5(app)
|
bootstrap = Bootstrap5(app)
|
||||||
|
|
||||||
|
# Registrar blueprints
|
||||||
|
app.register_blueprint(cota_bp)
|
||||||
|
|
||||||
# Configuração da sessão do SQLAlchemy
|
# Configuração da sessão do SQLAlchemy
|
||||||
db_session = get_db_connection()
|
db_session = get_db_connection()
|
||||||
|
|
||||||
@@ -39,8 +48,12 @@ db_session = get_db_connection()
|
|||||||
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
|
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
|
||||||
app.config['MAIL_PORT'] = 587
|
app.config['MAIL_PORT'] = 587
|
||||||
app.config['MAIL_USE_TLS'] = True
|
app.config['MAIL_USE_TLS'] = True
|
||||||
app.config['MAIL_USERNAME'] = 'seu-email@gmail.com'
|
app.config['MAIL_USERNAME'] = 'seu-email@gmail.com' # Substituir pelo seu email
|
||||||
app.config['MAIL_PASSWORD'] = 'sua-senha'
|
app.config['MAIL_PASSWORD'] = 'sua-senha-de-app' # Substituir pela senha de app
|
||||||
|
|
||||||
|
# Se estiver usando variáveis de ambiente (recomendado):
|
||||||
|
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
|
||||||
|
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
|
||||||
|
|
||||||
mail = Mail(app)
|
mail = Mail(app)
|
||||||
|
|
||||||
@@ -132,6 +145,7 @@ def login():
|
|||||||
session['user_id'] = user.id
|
session['user_id'] = user.id
|
||||||
session['is_admin'] = user.is_admin
|
session['is_admin'] = user.is_admin
|
||||||
session['last_activity'] = time() # Inicializar timestamp
|
session['last_activity'] = time() # Inicializar timestamp
|
||||||
|
session['username'] = user.username # Armazenar apenas o username
|
||||||
|
|
||||||
# Registrar horário do login
|
# Registrar horário do login
|
||||||
user.ultimo_login = datetime.now()
|
user.ultimo_login = datetime.now()
|
||||||
@@ -179,60 +193,104 @@ def home():
|
|||||||
# Ordenar links pelo nome
|
# Ordenar links pelo nome
|
||||||
links.sort(key=lambda x: x[1])
|
links.sort(key=lambda x: x[1])
|
||||||
|
|
||||||
return render_template('home.html', links=links)
|
return render_template('home.html', links=links, current_user={'username': session.get('username')})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Erro na página inicial: {e}")
|
print(f"Erro na página inicial: {e}")
|
||||||
import traceback
|
import traceback
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
flash('Erro ao carregar a página inicial', 'error')
|
flash('Erro ao carregar a página inicial', 'error')
|
||||||
return render_template('home.html', links=[])
|
return render_template('home.html', links=[], current_user={'username': session.get('username')})
|
||||||
|
|
||||||
# Rota para criar um novo militante
|
# Rota para criar um novo militante
|
||||||
@app.route("/militantes/novo", methods=["GET", "POST"])
|
@app.route("/militantes/novo", methods=["GET", "POST"])
|
||||||
@login_required
|
@login_required
|
||||||
@session_timeout
|
@session_timeout
|
||||||
def novo_militante():
|
def novo_militante():
|
||||||
# Obter células disponíveis baseado no nível do usuário
|
|
||||||
user = db_session.query(Usuario).get(session['user_id'])
|
user = db_session.query(Usuario).get(session['user_id'])
|
||||||
celulas_disponiveis = []
|
|
||||||
|
|
||||||
if user.role.nivel == 1: # CC
|
try:
|
||||||
|
# Obter CRs e células existentes
|
||||||
|
if user.is_admin:
|
||||||
celulas_por_cr = db_session.query(ComiteRegional).all()
|
celulas_por_cr = db_session.query(ComiteRegional).all()
|
||||||
elif user.role.nivel == 2: # CR
|
crs_existentes = celulas_por_cr
|
||||||
|
elif user.cr_id:
|
||||||
celulas_por_cr = [user.cr]
|
celulas_por_cr = [user.cr]
|
||||||
elif user.role.nivel == 3: # Setor
|
crs_existentes = [user.cr]
|
||||||
celulas_por_cr = [{
|
else:
|
||||||
'nome': user.setor.cr.nome,
|
celulas_por_cr = []
|
||||||
'setores': [user.setor]
|
crs_existentes = []
|
||||||
}]
|
|
||||||
else: # Célula
|
except Exception as e:
|
||||||
celulas_por_cr = [{
|
print(f"Erro ao obter células: {e}")
|
||||||
'nome': user.celula.setor.cr.nome,
|
celulas_por_cr = []
|
||||||
'setores': [{
|
crs_existentes = []
|
||||||
'nome': user.celula.setor.nome,
|
|
||||||
'celulas': [user.celula]
|
|
||||||
}]
|
|
||||||
}]
|
|
||||||
|
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
cpf = request.form["cpf"]
|
try:
|
||||||
|
# Validar CPF
|
||||||
|
cpf = request.form.get("cpf")
|
||||||
if not validar_cpf(cpf):
|
if not validar_cpf(cpf):
|
||||||
flash('CPF inválido. Por favor, verifique o número informado.', 'error')
|
flash('CPF inválido. Por favor, verifique o número informado.', 'error')
|
||||||
return render_template("novo_militante.html",
|
return render_template("novo_militante.html",
|
||||||
dados_anteriores=request.form,
|
dados_anteriores=request.form,
|
||||||
responsabilidades=Militante.get_responsabilidades_list(),
|
responsabilidades=Militante.get_responsabilidades_list(),
|
||||||
celulas_por_cr=celulas_por_cr)
|
celulas_por_cr=celulas_por_cr,
|
||||||
|
crs_existentes=crs_existentes)
|
||||||
|
|
||||||
# Criar militante
|
celula_id = None
|
||||||
|
if request.form.get("nova_celula"):
|
||||||
|
# Criar nova estrutura organizacional se necessário
|
||||||
|
cr = None
|
||||||
|
if request.form.get("nome_cr") == "novo":
|
||||||
|
cr = ComiteRegional(nome=request.form.get("novo_cr"))
|
||||||
|
db_session.add(cr)
|
||||||
|
db_session.flush()
|
||||||
|
else:
|
||||||
|
cr_id = request.form.get("nome_cr")
|
||||||
|
cr = db_session.query(ComiteRegional).get(cr_id)
|
||||||
|
|
||||||
|
setor = None
|
||||||
|
if not request.form.get("sem_setor"):
|
||||||
|
if request.form.get("nome_setor") == "novo":
|
||||||
|
setor = Setor(nome=request.form.get("novo_setor"), cr_id=cr.id)
|
||||||
|
db_session.add(setor)
|
||||||
|
db_session.flush()
|
||||||
|
elif request.form.get("nome_setor"):
|
||||||
|
setor = db_session.query(Setor).get(request.form.get("nome_setor"))
|
||||||
|
|
||||||
|
# Criar nova célula
|
||||||
|
celula = Celula(
|
||||||
|
nome=request.form.get("nome_celula"),
|
||||||
|
cr_id=cr.id,
|
||||||
|
setor_id=setor.id if setor else None
|
||||||
|
)
|
||||||
|
db_session.add(celula)
|
||||||
|
db_session.flush()
|
||||||
|
celula_id = celula.id
|
||||||
|
else:
|
||||||
|
celula_id = request.form.get("celula_id")
|
||||||
|
|
||||||
|
# Criar militante com todos os campos
|
||||||
novo_militante = Militante(
|
novo_militante = Militante(
|
||||||
nome=request.form["nome"],
|
nome=request.form.get("nome"),
|
||||||
cpf=cpf,
|
cpf=cpf,
|
||||||
email=request.form["email"],
|
titulo_eleitoral=request.form.get("titulo_eleitoral"),
|
||||||
telefone=request.form["telefone"],
|
data_nascimento=datetime.strptime(request.form.get("data_nascimento"), "%Y-%m-%d") if request.form.get("data_nascimento") else None,
|
||||||
endereco=request.form["endereco"],
|
data_entrada_oci=datetime.strptime(request.form.get("data_entrada_oci"), "%Y-%m-%d") if request.form.get("data_entrada_oci") else None,
|
||||||
filiado=bool(request.form.get("filiado", False)),
|
data_efetivacao_oci=datetime.strptime(request.form.get("data_efetivacao_oci"), "%Y-%m-%d") if request.form.get("data_efetivacao_oci") else None,
|
||||||
celula_id=request.form["celula_id"]
|
telefone1=request.form.get("telefone1"),
|
||||||
|
telefone2=request.form.get("telefone2"),
|
||||||
|
profissao=request.form.get("profissao"),
|
||||||
|
regime_trabalho=request.form.get("regime_trabalho"),
|
||||||
|
empresa=request.form.get("empresa"),
|
||||||
|
contratante=request.form.get("contratante"),
|
||||||
|
instituicao_ensino=request.form.get("instituicao_ensino"),
|
||||||
|
tipo_instituicao=request.form.get("tipo_instituicao"),
|
||||||
|
sindicato=request.form.get("sindicato"),
|
||||||
|
cargo_sindical=request.form.get("cargo_sindical"),
|
||||||
|
dirigente_sindical=bool(request.form.get("dirigente_sindical")),
|
||||||
|
central_sindical=request.form.get("central_sindical"),
|
||||||
|
celula_id=celula_id
|
||||||
)
|
)
|
||||||
|
|
||||||
# Definir responsabilidades
|
# Definir responsabilidades
|
||||||
@@ -242,24 +300,32 @@ def novo_militante():
|
|||||||
novo_militante.set_responsabilidades(responsabilidades)
|
novo_militante.set_responsabilidades(responsabilidades)
|
||||||
|
|
||||||
db_session.add(novo_militante)
|
db_session.add(novo_militante)
|
||||||
try:
|
|
||||||
db_session.commit()
|
db_session.commit()
|
||||||
# Enviar email com QR code
|
|
||||||
|
# Tentar enviar email
|
||||||
|
try:
|
||||||
novo_militante.send_otp_email(mail)
|
novo_militante.send_otp_email(mail)
|
||||||
flash('Militante cadastrado com sucesso! Um email foi enviado com as instruções de autenticação.', 'success')
|
flash('Militante cadastrado com sucesso! Um email foi enviado com as instruções de autenticação.', 'success')
|
||||||
|
except Exception as mail_error:
|
||||||
|
print(f"Erro ao enviar email: {mail_error}")
|
||||||
|
flash('Militante cadastrado com sucesso, mas houve um erro ao enviar o email. Entre em contato com o administrador.', 'warning')
|
||||||
|
|
||||||
return redirect(url_for("listar_militantes"))
|
return redirect(url_for("listar_militantes"))
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
print(f"Erro ao cadastrar militante: {e}")
|
||||||
db_session.rollback()
|
db_session.rollback()
|
||||||
flash('Erro ao cadastrar militante.', 'error')
|
flash('Erro ao cadastrar militante.', 'error')
|
||||||
return render_template("novo_militante.html",
|
return render_template("novo_militante.html",
|
||||||
dados_anteriores=request.form,
|
dados_anteriores=request.form,
|
||||||
responsabilidades=Militante.get_responsabilidades_list(),
|
responsabilidades=Militante.get_responsabilidades_list(),
|
||||||
celulas_por_cr=celulas_por_cr)
|
celulas_por_cr=celulas_por_cr,
|
||||||
|
crs_existentes=crs_existentes)
|
||||||
|
|
||||||
return render_template("novo_militante.html",
|
return render_template("novo_militante.html",
|
||||||
responsabilidades=Militante.get_responsabilidades_list(),
|
responsabilidades=Militante.get_responsabilidades_list(),
|
||||||
celulas_por_cr=celulas_por_cr)
|
celulas_por_cr=celulas_por_cr,
|
||||||
|
crs_existentes=crs_existentes)
|
||||||
|
|
||||||
# Rota para listar militantes
|
# Rota para listar militantes
|
||||||
@app.route("/militantes")
|
@app.route("/militantes")
|
||||||
@@ -627,12 +693,19 @@ def get_qr_code(token):
|
|||||||
qr_path = generate_qr_code(militante)
|
qr_path = generate_qr_code(militante)
|
||||||
return render_template('mostrar_qr_code.html', qr_uri=militante.get_otp_uri())
|
return render_template('mostrar_qr_code.html', qr_uri=militante.get_otp_uri())
|
||||||
|
|
||||||
|
# Adicionar nova rota para API de setores
|
||||||
|
@app.route("/api/setores/<int:cr_id>")
|
||||||
|
@login_required
|
||||||
|
def get_setores(cr_id):
|
||||||
|
setores = db_session.query(Setor).filter_by(cr_id=cr_id).all()
|
||||||
|
return jsonify({
|
||||||
|
'setores': [{'id': s.id, 'nome': s.nome} for s in setores]
|
||||||
|
})
|
||||||
|
|
||||||
def create_app():
|
def create_app():
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
# ... existing code ...
|
# ... existing code ...
|
||||||
|
|
||||||
app.register_blueprint(cota_bp)
|
|
||||||
|
|
||||||
# ... existing code ...
|
# ... existing code ...
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|||||||
@@ -1,692 +0,0 @@
|
|||||||
// TODO: extract all CONTANTS TO EASILY CHANGE CELLS
|
|
||||||
|
|
||||||
const planilhaID= "13sLipAAD5LkzZK19iuzgscbCmODiS11hJDRgaNsnYvw";
|
|
||||||
|
|
||||||
// LOCAIS DE LIMPEZA \/\/\/\/
|
|
||||||
const cotas = 'B5:E40' ;
|
|
||||||
const contribuintes = 'B43:E57' ;
|
|
||||||
const brochuras = 'B60:D65';
|
|
||||||
const campanha = 'B68:D84' ;
|
|
||||||
const outras = 'B87:D94';
|
|
||||||
const assinantes = 'B97:D109';
|
|
||||||
const jornal = 'B112:D126';
|
|
||||||
const despesaCE = 'D129';
|
|
||||||
const depositos = 'B134:F251' ;
|
|
||||||
const carimbo = 'Q287' ;
|
|
||||||
// ACABOU :LOCAIS DE LIMPEZA /\/\/\/\
|
|
||||||
|
|
||||||
const contagemRF='E2';
|
|
||||||
const celulaPrincipal = 'A1' ;
|
|
||||||
|
|
||||||
const enddepositos = 'D252';
|
|
||||||
const endvendas = 'D130' ;
|
|
||||||
|
|
||||||
const celulaValorTotalCotas = 'E41';
|
|
||||||
|
|
||||||
const timeZone = Session.getScriptTimeZone();
|
|
||||||
|
|
||||||
const CRSP = "crsptesouraria@gmail.com";
|
|
||||||
const areaAProteger = 'A1:Y999' ;
|
|
||||||
|
|
||||||
function getUser(){ return Session.getEffectiveUser();}
|
|
||||||
|
|
||||||
function voltaAoTopo(){
|
|
||||||
SpreadsheetApp.getActiveSheet().setCurrentCell(SpreadsheetApp.getActiveSheet().getRange(celulaPrincipal)) ;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
function onOpen() {
|
|
||||||
var ui = SpreadsheetApp.getUi();
|
|
||||||
ui.createMenu('CR')
|
|
||||||
.addItem('Enviar RF', 'menuItem1')
|
|
||||||
.addItem('Totalizar Cotas', 'menuItem2')
|
|
||||||
.addItem('Teste - Não usar', 'menuItem3')
|
|
||||||
.addToUi();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// MENU ITEMS
|
|
||||||
function menuItem1() {
|
|
||||||
SpreadsheetApp.getUi()
|
|
||||||
{
|
|
||||||
Logger.log(getUser());
|
|
||||||
resultado = enviaCR();
|
|
||||||
Logger.log("Resultado: " + resultado + ".");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function menuItem2() {
|
|
||||||
SpreadsheetApp.getUi()
|
|
||||||
{
|
|
||||||
Logger.log(getUser());
|
|
||||||
resultado = totalizar(curName)
|
|
||||||
Logger.log("Resultado: " + resultado + ".");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function menuItem3() {
|
|
||||||
SpreadsheetApp.getUi()
|
|
||||||
{
|
|
||||||
Logger.log(getUser());
|
|
||||||
carimboValue = pegarCarimbo(SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()) ;
|
|
||||||
if(!isNaN(parseFloat(carimboValue)) ) {
|
|
||||||
var mesAtual = Utilities.formatDate(carimboValue,timeZone, "MM");
|
|
||||||
Logger.log("Carimbo lido: " + mesAtual + ".");
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
mesAtual = Utilities.formatDate(new Date(),timeZone, "MM") ;
|
|
||||||
Logger.log("Carimbo vazio, mês atual: " + mesAtual + ".");
|
|
||||||
}
|
|
||||||
|
|
||||||
voltaAoTopo();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// FUNCTIONS BELOW
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// SEND RF
|
|
||||||
function enviaCR() {
|
|
||||||
var ss = SpreadsheetApp.getActiveSpreadsheet(); // cria o objeto do arquivo da planilha
|
|
||||||
var sheet = ss.getActiveSheet(); // cria objeto da Sheet ativa agora
|
|
||||||
var curName = ss.getActiveSheet().getName() ; // pega nome da Sheet
|
|
||||||
|
|
||||||
// validar contas
|
|
||||||
if (validar(sheet))
|
|
||||||
{
|
|
||||||
// subir dados na planilha de controle
|
|
||||||
var resultadoEnvio = enviando(curName,sheet,ss);
|
|
||||||
if (resultadoEnvio == "Enviado" )
|
|
||||||
{SpreadsheetApp.getUi().alert('Relatório Enviado!');}
|
|
||||||
else
|
|
||||||
{SpreadsheetApp.getUi().alert('ERRO: ' + resultadoEnvio );}
|
|
||||||
} return resultadoEnvio;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// VALIDAR VALORES TODO: ADIOCIONAR NOVAS
|
|
||||||
function validar(sheet){
|
|
||||||
// trocar vendas por centralizado
|
|
||||||
var celulaDepositos = sheet.getRange(enddepositos);
|
|
||||||
var depositos = sheet.setCurrentCell(celulaDepositos).getValue();
|
|
||||||
var celulaVendas = sheet.getRange(endvendas);
|
|
||||||
var vendas = sheet.setCurrentCell(celulaVendas).getValue();
|
|
||||||
if ( vendas === depositos )
|
|
||||||
{ return true;}
|
|
||||||
else
|
|
||||||
{ SpreadsheetApp.getUi().alert('Centralizado ' + vendas + ' não bate com Depósitos ' + depositos ); return false ;}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function enviando(curName,sheet,ss) {
|
|
||||||
valorCotas = pegarTotalCota(curName, ss); // TOTAL das cotas
|
|
||||||
marcaCarimbos(curName, valorCotas, sheet); // SALVA TOTAL DAS COTAS ETC
|
|
||||||
novaAba = renomearAba(curName, ss); // Renomeia Aba e coloca nomero da nova aba no numero do relatorio
|
|
||||||
limpaEntradas(novaAba) ; // limpa carimbo e entradas
|
|
||||||
|
|
||||||
if (travar(curName, ss) === "Travada"){
|
|
||||||
ss.setActiveSheet(novaAba); // coloca novo em evidencia
|
|
||||||
return "Enviado";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function pegarTotalCota(curName, ss){
|
|
||||||
var sheet = ss.getSheetByName(curName);
|
|
||||||
var valorNovaAvulso = Number(sheet.setCurrentCell(sheet.getRange(celulaValorTotalCotas)).getValue());
|
|
||||||
Logger.log(" valorNovaAvulso: " + valorNovaAvulso + ".");
|
|
||||||
return valorNovaAvulso;
|
|
||||||
}
|
|
||||||
|
|
||||||
function marcaCarimbos(curName,totalCota,sheet){
|
|
||||||
var gravarTempo = Utilities.formatDate(new Date(),timeZone, "yyyyMMddHHmmssSSS");
|
|
||||||
var celulaTempo = 'D900';
|
|
||||||
var celulaTotalCotas = 'D901';
|
|
||||||
var celulaResponsavel = 'D902';
|
|
||||||
var celulaNomeContagem = 'D902';
|
|
||||||
var celulaResponsavelCel = 'H2';
|
|
||||||
var username = getUser();
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaTempo)).setValue(gravarTempo);
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaResponsavel)).setValue(username);
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaNomeContagem)).setValue(curName);
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaResponsavelCel)).setValue(username);
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaTotalCotas)).setValue(totalCota);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
function pegarCarimbo(sheet)
|
|
||||||
{
|
|
||||||
new Date(sheet.setCurrentCell(sheet.getRange(carimbo)).getValue())
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function renomearAba(curName,ss){
|
|
||||||
|
|
||||||
var newName = Number(curName) + 1 ; // cria nome da nova
|
|
||||||
ss.moveActiveSheet(ss.getNumSheets() - 1); // move a atual para a ultima posicao antes da Validacao que é escondida
|
|
||||||
ss.duplicateActiveSheet(); // duplica ativa
|
|
||||||
ss.renameActiveSheet(newName); // renomeia nova
|
|
||||||
ss.moveActiveSheet(1); // move para a primeira posicao
|
|
||||||
var sheet = ss.getSheetByName(newName); // torna a nova ativa usando nome
|
|
||||||
sheet.getRange(contagemRF).setValue(newName); //altera contagem do relatorio usando numero da aba
|
|
||||||
return sheet;
|
|
||||||
}
|
|
||||||
|
|
||||||
function limpaEntradas(sheet)
|
|
||||||
{
|
|
||||||
function limpaTudo(value){
|
|
||||||
sheet.getRange(value).clearContent();
|
|
||||||
}
|
|
||||||
var limpeza = [ cotas, contribuintes, brochuras, campanha , outras, assinantes, jornal , despesaCE, depositos, carimbo ];
|
|
||||||
limpeza.forEach(limpaTudo) ;
|
|
||||||
|
|
||||||
let range = sheet.getRange("I:Y");
|
|
||||||
sheet.hideColumn(range);
|
|
||||||
range = sheet.getRange("A258:A999");
|
|
||||||
sheet.hideRow(range);
|
|
||||||
|
|
||||||
SpreadsheetApp.getActiveSheet().setCurrentCell(SpreadsheetApp.getActiveSheet().getRange(celulaPrincipal)) ;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
function travar(curName, ss){
|
|
||||||
var sheet = ss.getSheetByName(curName);
|
|
||||||
var areaProtegida = false ;
|
|
||||||
var abaProtegida = false ;
|
|
||||||
var userName = getUser();
|
|
||||||
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
|
|
||||||
|
|
||||||
for (var i = 0; i < protections.length; i++) {
|
|
||||||
var desc = protections[i].getDescription();
|
|
||||||
Logger.log("protection desc: " + desc);
|
|
||||||
if ( desc === 'Area protegida' ){ areaProtegida = true ; }
|
|
||||||
if ( desc === 'Aba protegida') { abaProtegida = true ; }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Protege area, e remove todos da lista de editores.
|
|
||||||
var range = sheet.getRange(areaAProteger);
|
|
||||||
|
|
||||||
if (areaProtegida === false && userName != CRSP ) {
|
|
||||||
proteRange = range.protect().setDescription('Area protegida') ;
|
|
||||||
areaProtegida = true ;
|
|
||||||
proteRange.removeEditor(userName);
|
|
||||||
if (proteRange.canDomainEdit()) {
|
|
||||||
proteRange.setDomainEdit(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Logger.log(userName);
|
|
||||||
|
|
||||||
if (abaProtegida === false && userName != CRSP ) {
|
|
||||||
var proteSheet = sheet.protect().setDescription('Aba protegida');
|
|
||||||
abaProtegida = true ;
|
|
||||||
Logger.log("Removendo: " + userName);
|
|
||||||
proteSheet.removeEditor(userName);
|
|
||||||
if (proteSheet.canDomainEdit()) {
|
|
||||||
proteSheet.setDomainEdit(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
if (abaProtegida === true && areaProtegida === true ) { return "Travada" ;}
|
|
||||||
}
|
|
||||||
|
|
||||||
function efetuarRotinaMadrugada(){
|
|
||||||
travaNoturna();
|
|
||||||
totalizar();
|
|
||||||
}
|
|
||||||
|
|
||||||
function travaNoturna(){
|
|
||||||
var ss = SpreadsheetApp.openById(planilhaID);
|
|
||||||
var trava = 0 ;
|
|
||||||
console.log( getUser());
|
|
||||||
|
|
||||||
// Protects the sheet.
|
|
||||||
const sampleProtectedSheet = sheet.protect();
|
|
||||||
// Logs whether domain users have permission to edit the protected sheet to the console.
|
|
||||||
console.log(sampleProtectedSheet.canDomainEdit());
|
|
||||||
|
|
||||||
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
|
|
||||||
for (var cadaSheet = 0 ; cadaSheet < sheets.length ; cadaSheet++){
|
|
||||||
var nomeSheet = sheets[cadaSheet].getName();
|
|
||||||
Logger.log(" TravaNoturna nomeSheet: " + nomeSheet);
|
|
||||||
if (!isNaN(parseFloat(nomeSheet)) && isFinite(nomeSheet) && nomeSheet === anterior) {
|
|
||||||
SpreadsheetApp.setActiveSheet(sheets[cadaSheet]);
|
|
||||||
var protections = sheets[cadaSheet].getProtections(SpreadsheetApp.ProtectionType.SHEET);
|
|
||||||
for (var i = 0; i < protections.length; i++) {
|
|
||||||
var desc = protections[i].getDescription();
|
|
||||||
Logger.log("trava desc: " + desc);
|
|
||||||
if ( desc === 'Area protegida' || desc === 'Aba protegida' ) {
|
|
||||||
trava = trava + 1 ;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ( trava == 2 ){
|
|
||||||
const protection = sheets[cadaSheet].protect();
|
|
||||||
// Logs whether domain users have permission to edit the protected sheet to the console.
|
|
||||||
console.log(protection.canDomainEdit());
|
|
||||||
protection.removeEditors(protection.getEditors());
|
|
||||||
if (protection.canDomainEdit()) {
|
|
||||||
protection.setDomainEdit(false);
|
|
||||||
}
|
|
||||||
console.log(protection.canDomainEdit());
|
|
||||||
protection.setDescription('Trava Noturna');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaPrincipal)) ;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function totalizar(curName){
|
|
||||||
var anterior = curName ;
|
|
||||||
Logger.log("anterior: " + anterior + ".");
|
|
||||||
|
|
||||||
var ss = SpreadsheetApp.getActiveSpreadsheet() ;
|
|
||||||
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
|
|
||||||
var gravou = 0;
|
|
||||||
|
|
||||||
function enviarTotal() {
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
|
|
||||||
var brochuras = sheet.setCurrentCell(sheet.getRange('D66')).getValue() ;
|
|
||||||
var campanha = sheet.setCurrentCell(sheet.getRange('D71')).getValue();
|
|
||||||
var campanhaCCCE = sheet.setCurrentCell(sheet.getRange('D85')).getValue();
|
|
||||||
|
|
||||||
var outras = sheet.setCurrentCell(sheet.getRange('D95')).getValue();
|
|
||||||
var assinantes = sheet.setCurrentCell(sheet.getRange('D115')).getValue();
|
|
||||||
var jornal = sheet.setCurrentCell(sheet.getRange('D127')).getValue();
|
|
||||||
var carimboValue = pegarCarimbo() ;
|
|
||||||
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
|
|
||||||
// ABA TOTAL COLUNAS DE VALORES TOTALIZADOS
|
|
||||||
var cotascol = 'C'; // 0
|
|
||||||
var contribuintescol = 'E'; // 1
|
|
||||||
var brochurascol = 'H' ; // 2
|
|
||||||
var cfcol = 'J'; // 3
|
|
||||||
var outrascol = 'L'; // 4
|
|
||||||
var asscol = 'P'; // 5
|
|
||||||
var jornalcol ='R'; // 6
|
|
||||||
var varJaneiro = 3 ;
|
|
||||||
var varFevereiro = 4 ;
|
|
||||||
var varMarço = 5 ;
|
|
||||||
var varAbril = 6 ;
|
|
||||||
var varMaio = 7 ;
|
|
||||||
var varJunho = 8 ;
|
|
||||||
var varJulho = 9 ;
|
|
||||||
var varAgosto = 10 ;
|
|
||||||
var varSetembro = 11 ;
|
|
||||||
var varOutubro = 12 ;
|
|
||||||
var varNovembro = 13 ;
|
|
||||||
var varDezembro = 14 ;
|
|
||||||
var decimoTerceiro = 15 ;
|
|
||||||
var decimoQuarto = 16 ;
|
|
||||||
var decimoQuinto = 17 ;
|
|
||||||
var colunas = [ cotascol, contribuintescol , brochurascol , cfcol , outrascol , asscol , jornalcol ] ;
|
|
||||||
var linhas = [varJaneiro , varFevereiro ,varMarço ,varAbril ,varMaio ,varJunho ,varJulho ,varAgosto ,varSetembro ,varOutubro ,varNovembro ,varDezembro, decimoTerceiro, decimoQuarto, decimoQuinto] ;
|
|
||||||
// TERMINOU TABELA TOTAL /\
|
|
||||||
|
|
||||||
|
|
||||||
// PEGAR MES ATUAL
|
|
||||||
|
|
||||||
if(!isNaN(parseFloat(carimboValue)) ) {var mesAtual = Utilities.formatDate(carimboValue,timeZone, "MM");}
|
|
||||||
else { mesAtual = Utilities.formatDate(new Date(),timeZone, "MM") }
|
|
||||||
|
|
||||||
// Para cada Coluna de TOTAL executar totalização:
|
|
||||||
colunas.forEach(function(letra,coluna,tudo) {
|
|
||||||
Logger.log("letra: " + letra );
|
|
||||||
// começa com cota, checa se é o mes e coloca no switch.
|
|
||||||
switch (letra){
|
|
||||||
case cotascol:
|
|
||||||
// mes igual mes da primeira linha
|
|
||||||
for (var cadaMesdeCota = 5 ; cadaMesdeCota <=40 ; cadaMesdeCota++ ){
|
|
||||||
var celulaMilitante = 'B' + cadaMesdeCota ;
|
|
||||||
var celulaAno = 'C' + cadaMesdeCota ;
|
|
||||||
var celulaMes = 'D' + cadaMesdeCota ;
|
|
||||||
var celulaValor = 'E' + cadaMesdeCota ;
|
|
||||||
|
|
||||||
|
|
||||||
// Vai pra Anterior pra pegar cota de cadaMesdeCota ++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
|
|
||||||
valorCelula = sheet.setCurrentCell(sheet.getRange(celulaValor)).getValue() ;
|
|
||||||
|
|
||||||
// if (!isNaN(parseFloat(mesCelula)) && !isNaN(parseFloat(valorCelula)))
|
|
||||||
if (!isNaN(parseFloat(valorCelula)))
|
|
||||||
{
|
|
||||||
var mesCelula = sheet.setCurrentCell(sheet.getRange(celulaMes)).getValue();
|
|
||||||
var retornoMes = checkMonth(mesCelula);
|
|
||||||
militanteCota = sheet.setCurrentCell(sheet.getRange(celulaMilitante)).getValue();
|
|
||||||
anoCota = sheet.setCurrentCell(sheet.getRange(celulaAno)).getValue();
|
|
||||||
Logger.log( " COTA valorCelula: " + valorCelula + " militanteCota " + militanteCota + "retornoMes" + retornoMes);
|
|
||||||
|
|
||||||
if ( !isNaN(parseFloat(retornoMes)) ) {
|
|
||||||
var mesNovaCota = new Date(retornoMes) ;
|
|
||||||
var mesNCemN = Number(Utilities.formatDate(mesNovaCota,timeZone, "MM")) - 1;
|
|
||||||
var valorNovaCota = valorCelula ;
|
|
||||||
|
|
||||||
if (!isNaN(parseFloat(valorNovaCota))){
|
|
||||||
// ENVIA PARA TOTAL:
|
|
||||||
Logger.log( " COTA valorNovaCota: " + valorNovaCota + ".");
|
|
||||||
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
var celulaObjetivo = letra + linhas[mesNCemN] ;
|
|
||||||
Logger.log( " COTA celulaObjetivo: " + celulaObjetivo + ".");
|
|
||||||
|
|
||||||
|
|
||||||
var valorAntigoCota = sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).getValue() ;
|
|
||||||
if (!isNaN(parseFloat(valorAntigoCota))){
|
|
||||||
Logger.log( " COTA valorAntigoCota: " + valorAntigoCota + ".");
|
|
||||||
var gravar = valorAntigoCota + valorNovaCota ;
|
|
||||||
}
|
|
||||||
else { var gravar = valorNovaCota ; }
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).setValue(gravar);
|
|
||||||
Logger.log( " COTA Gravou: " + gravar + ".");
|
|
||||||
// ENVIOU PARA TOTAL /\
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
// segunda iteração contribuintes, checa se é o mes e coloca no switch.
|
|
||||||
case contribuintescol:
|
|
||||||
// mes igual mes da primeira linha
|
|
||||||
for (var cadaMesContrib = 43 ; cadaMesContrib <=57 ; cadaMesContrib++ ){
|
|
||||||
var celulaContribuinte = 'B' + cadaMesContrib ;
|
|
||||||
var celulaAno = 'C' + cadaMesContrib ;
|
|
||||||
var celulaMes = 'D' + cadaMesContrib ;
|
|
||||||
var celulaValor = 'E' + cadaMesContrib ;
|
|
||||||
var celulaResponsavel = 'F' + cadaMesContrib ;
|
|
||||||
|
|
||||||
// Vai pra Anterior pra pegar Contribuição de cadaMesdeCota
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
var retornoMes = sheet.setCurrentCell(sheet.getRange(celulaMes)).getValue();
|
|
||||||
|
|
||||||
if ( !isNaN(parseFloat(retornoMes)) ) {
|
|
||||||
var mesNovaContrib = new Date(checkMonth(retornoMes)) ;
|
|
||||||
var mesNCemN = Number(Utilities.formatDate(mesNovaContrib,timeZone, "MM")) - 1;
|
|
||||||
var valorNovaContr = Number(sheet.setCurrentCell(sheet.getRange(celulaValor)).getValue());
|
|
||||||
if (!isNaN(parseFloat(valorNovaContr))){
|
|
||||||
Logger.log( " CONTRIB valorNovaContr: " + valorNovaContr + ".");
|
|
||||||
var celulaObjetivo = letra + linhas[mesNCemN] ;
|
|
||||||
Logger.log( " CONTRIB celulaObjetivo: " + celulaObjetivo + ".");
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
var valorAntigoContr = sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).getValue() ;
|
|
||||||
Logger.log( " CONTRIB valorAntigoContr: " + valorAntigoContr + ".");
|
|
||||||
if (!isNaN(parseFloat(valorAntigoContr)) ){
|
|
||||||
var gravar = valorNovaContr + valorAntigoContr ; }
|
|
||||||
else {
|
|
||||||
gravar = valorNovaContr ;
|
|
||||||
}
|
|
||||||
Logger.log( " CONTRIB celulaMes: " + celulaMes + " celulaValor: " + celulaValor + ".");
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).setValue(gravar);
|
|
||||||
Logger.log( " CONTRIB Gravou: " + gravar + ".");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
// FALTA TERMINAR BROCHURAS
|
|
||||||
case brochurascol:
|
|
||||||
for (var linhaBro = 60 ; linhaBro <=65 ; linhaBro++ ){
|
|
||||||
// var celulaNome = 'B' +linhaBro ;
|
|
||||||
var celulaQuantidade = 'C' + linhaBro ;
|
|
||||||
var celulaValor = 'D' + linhaBro ;
|
|
||||||
var celulaCodigo = 'E' + linhaBro ;
|
|
||||||
// Vai pra Anterior pra pegar dados acima
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
var difLinBro = 2 ;
|
|
||||||
var quantidadeBro = sheet.setCurrentCell(sheet.getRange(celulaQuantidade)).getValue();
|
|
||||||
if ( !isNaN(parseFloat(quantidadeBro)) ) {
|
|
||||||
var valorNovaBro = Number(sheet.setCurrentCell(sheet.getRange(celulaValor)).getValue());
|
|
||||||
var codigoNovaBro = Number(sheet.setCurrentCell(sheet.getRange(celulaCodigo)).getValue()) + difLinBro ;
|
|
||||||
Logger.log(" BROCHURAS valorNovaBro: " + valorNovaBro + " codigoNovaBro: " + codigoNovaBro);
|
|
||||||
if (!isNaN(parseFloat(valorNovaBro))){
|
|
||||||
var celulaObjetivo = letra + codigoNovaBro ;
|
|
||||||
var qtdObjetivo = 'G' + codigoNovaBro ;
|
|
||||||
var qtdAntigoBro = sheet.setCurrentCell(sheet.getRange(qtdObjetivo)).getValue() ;
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
var valorAntigoBro = sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).getValue() ;
|
|
||||||
if (!isNaN(parseFloat(valorAntigoBro)) ){
|
|
||||||
var gravar = valorNovaBro + valorAntigoBro ; }
|
|
||||||
else {
|
|
||||||
gravar = valorNovaBro ;
|
|
||||||
}
|
|
||||||
Logger.log(" BROCHURAS celulaQuantidade: " + celulaQuantidade + " celulaValor: " + celulaValor + " gravar: " + gravar );
|
|
||||||
|
|
||||||
if (!isNaN(parseFloat(qtdAntigoBro)) ){
|
|
||||||
var gravarQtd = quantidadeBro + qtdAntigoBro ; }
|
|
||||||
else {
|
|
||||||
var gravarQtd = quantidadeBro ;
|
|
||||||
}
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
// Grava Valor
|
|
||||||
Logger.log(" BROCHURAS celulaValorObjetivo: " + celulaObjetivo + " gravar: " + gravar );
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).setValue(gravar);
|
|
||||||
Logger.log( " BROCHURAS Gravou Valor: " + gravar + ".");
|
|
||||||
// Grava quantidade
|
|
||||||
sheet.setCurrentCell(sheet.getRange(qtdObjetivo)).setValue(gravarQtd);
|
|
||||||
Logger.log( " BROCHURAS Gravou Qtd: " + gravarQtd + ".")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case cfcol:
|
|
||||||
for (var linhaCF = 68 ; linhaCF <=84 ; linhaCF++ ){
|
|
||||||
var celulaNome = 'B' + linhaCF ;
|
|
||||||
var celulaQuantidade = 'C' + linhaCF ;
|
|
||||||
var celulaValor = 'D' + linhaCF ;
|
|
||||||
var celulaCodigo = 'F' + linhaCF ;
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
var valorCF = sheet.setCurrentCell(sheet.getRange(celulaValor)).getValue();
|
|
||||||
if ( !isNaN(parseFloat(valorCF)) ) {
|
|
||||||
var militanteNovaCF = sheet.setCurrentCell(sheet.getRange(celulaNome)).getValue();
|
|
||||||
// VAI PRA TOTAL
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
var linhaSalvar = sheet.getRange('I3:J22').createTextFinder(militanteNovaCF).findNext();
|
|
||||||
if (linhaSalvar){
|
|
||||||
var valorAntigoCF = linhaSalvar.offset(0,1).getValue();
|
|
||||||
Logger.log(" CF linhaSalvar.getA1Notation(): " + linhaSalvar.getA1Notation() + " militanteNovaCF: " + militanteNovaCF + " valorCF: " + valorCF + " valorAntigoCF: " + valorAntigoCF );
|
|
||||||
if (!isNaN(parseFloat(valorAntigoCF)) ){ var gravar = valorCF + valorAntigoCF ; }
|
|
||||||
else { gravar = valorCF ; }
|
|
||||||
// Grava Valor
|
|
||||||
linhaSalvar.offset(0,1).setValue(gravar);
|
|
||||||
Logger.log( " CF Gravou Valor: " + gravar + ".");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case outrascol:
|
|
||||||
for (var linhaOutros = 87 ; linhaOutros <=94 ; linhaOutros++ ){
|
|
||||||
var celulaQuantidade = 'C' + linhaOutros ;
|
|
||||||
var celulaValor = 'D' + linhaOutros ;
|
|
||||||
var celulaCodigo = 'E' + linhaOutros ;
|
|
||||||
|
|
||||||
// Vai pra Anterior pra pegar dados acima
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
|
|
||||||
var quantidadeOutro = sheet.setCurrentCell(sheet.getRange(celulaQuantidade)).getValue();
|
|
||||||
if ( !isNaN(parseFloat(quantidadeOutro)) ) {
|
|
||||||
var valorNovaOutro = Number(sheet.setCurrentCell(sheet.getRange(celulaValor)).getValue());
|
|
||||||
var difLinOut = 2 ;
|
|
||||||
var codigoNovaOutro = Number(sheet.setCurrentCell(sheet.getRange(celulaCodigo)).getValue()) + difLinOut ;
|
|
||||||
if (!isNaN(parseFloat(valorNovaOutro))){
|
|
||||||
var celulaObjetivo = letra + codigoNovaOutro ;
|
|
||||||
var qtdObjetivo = 'K' + codigoNovaOutro ;
|
|
||||||
var qtdAntigoOutro = sheet.setCurrentCell(sheet.getRange(qtdObjetivo)).getValue() ;
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
var valorAntigoOutro = sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).getValue() ;
|
|
||||||
if (!isNaN(parseFloat(valorAntigoOutro)) ){
|
|
||||||
var gravar = valorNovaOutro + valorAntigoOutro ; }
|
|
||||||
else {
|
|
||||||
gravar = valorNovaOutro ;
|
|
||||||
}
|
|
||||||
Logger.log( " OUTRAS celulaQuantidade: " + celulaQuantidade + " celulaValor: " + celulaValor + " gravar: " + gravar );
|
|
||||||
|
|
||||||
if (!isNaN(parseFloat(qtdAntigoOutro)) ){
|
|
||||||
var gravarQtd = quantidadeOutro + qtdAntigoOutro ; }
|
|
||||||
else {
|
|
||||||
var gravarQtd = quantidadeOutro ;
|
|
||||||
}
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
// Grava Valor
|
|
||||||
Logger.log( " OUTRAS celulaValorObjetivo: " + celulaObjetivo + " gravar: " + gravar );
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaObjetivo)).setValue(gravar);
|
|
||||||
Logger.log( " OUTRAS Gravou Valor: " + gravar + ".");
|
|
||||||
// Grava quantidade
|
|
||||||
sheet.setCurrentCell(sheet.getRange(qtdObjetivo)).setValue(gravarQtd);
|
|
||||||
Logger.log( " OUTRAS Gravou Qtd: " + gravarQtd + ".")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case asscol:
|
|
||||||
// ARRUMAR ASSINATURAS
|
|
||||||
var linha = mesAtual - 1 ;
|
|
||||||
Logger.log(" ASSINATURA linhas[linha]: " + linhas[linha] + " linha: " + linha + " mesAtual: " + mesAtual + ".");
|
|
||||||
var celula = letra + linhas[linha] ;
|
|
||||||
|
|
||||||
// PEGAR TOTAL ATUAL
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
var totalatual = sheet.setCurrentCell(sheet.getRange(celula)).getValue() ;
|
|
||||||
if ( !isNaN(parseFloat(outras)) && assinantes > 0 ){
|
|
||||||
var gravar = totalatual + assinantes ;
|
|
||||||
// GRAVAR
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celula)).setValue(gravar);
|
|
||||||
}
|
|
||||||
break ;
|
|
||||||
case jornalcol:
|
|
||||||
for (var linhaAvulso = 112 ; linhaAvulso <=126 ; linhaAvulso++ ){
|
|
||||||
var celulaQuantidade = 'C' + linhaAvulso ;
|
|
||||||
var celulaValor = 'D' + linhaAvulso ;
|
|
||||||
var celulaEdicao = 'B' + linhaAvulso ;
|
|
||||||
|
|
||||||
// Vai pra Anterior pra pegar dados acima
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
var difLinEdicao = 11
|
|
||||||
var quantidadeAvulso = sheet.setCurrentCell(sheet.getRange(celulaQuantidade)).getValue();
|
|
||||||
if ( !isNaN(parseFloat(quantidadeAvulso)) ) {
|
|
||||||
var valorNovaAvulso = Number(sheet.setCurrentCell(sheet.getRange(celulaValor)).getValue());
|
|
||||||
var edicaoNovaAvulso = Number(sheet.setCurrentCell(sheet.getRange(celulaEdicao)).getValue()) - difLinEdicao ;
|
|
||||||
Logger.log( " JORNALA. edicaoNovaAvulso: " + edicaoNovaAvulso + "valorNovaAvulso: " + valorNovaAvulso + "Quantidade: " + quantidadeAvulso );
|
|
||||||
if (!isNaN(parseFloat(valorNovaAvulso))){
|
|
||||||
var celulaValorObjetivo = letra + edicaoNovaAvulso ;
|
|
||||||
var qtdVendido = 'T' + edicaoNovaAvulso ;
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
var valorAntigoAvulso = sheet.setCurrentCell(sheet.getRange(celulaValorObjetivo)).getValue() ;
|
|
||||||
var qtdAntigoAvulso = sheet.setCurrentCell(sheet.getRange(qtdVendido)).getValue() ;
|
|
||||||
if (!isNaN(parseFloat(valorAntigoAvulso)) ){
|
|
||||||
var gravar = valorNovaAvulso + valorAntigoAvulso ; }
|
|
||||||
else {
|
|
||||||
var gravar = valorNovaAvulso ;
|
|
||||||
}
|
|
||||||
if (!isNaN(parseFloat(qtdAntigoAvulso)) ){
|
|
||||||
var gravarQtd = quantidadeAvulso + qtdAntigoAvulso ; }
|
|
||||||
else {
|
|
||||||
var gravarQtd = quantidadeAvulso ;
|
|
||||||
}
|
|
||||||
var sheet = ss.getSheetByName("TOTAL");
|
|
||||||
// Grava Valor
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaValorObjetivo)).setValue(gravar);
|
|
||||||
Logger.log( " JORNALA. Gravou Valor: " + gravar );
|
|
||||||
// Grava quantidade
|
|
||||||
sheet.setCurrentCell(sheet.getRange(qtdVendido)).setValue(gravarQtd);
|
|
||||||
Logger.log( " JORNALA. Gravou Qtd: " + gravarQtd );
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} )
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sheets.length > 1) {
|
|
||||||
for (var cadaSheet = 0 ; cadaSheet < sheets.length ; cadaSheet++)
|
|
||||||
{
|
|
||||||
var nomeSheet = sheets[cadaSheet].getName();
|
|
||||||
Logger.log("nomeSheet: " + nomeSheet);
|
|
||||||
if (!isNaN(parseFloat(nomeSheet)) && isFinite(nomeSheet) && nomeSheet === anterior) {
|
|
||||||
SpreadsheetApp.setActiveSheet(sheets[cadaSheet]);
|
|
||||||
var protections = sheets[cadaSheet].getProtections(SpreadsheetApp.ProtectionType.SHEET);
|
|
||||||
for (var i = 0; i < protections.length; i++) {
|
|
||||||
var desc = protections[i].getDescription();
|
|
||||||
Logger.log("protection desc: " + desc);
|
|
||||||
if ( desc === 'Aba protegida') {
|
|
||||||
enviarTotal();
|
|
||||||
gravou = 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var sheet = ss.getSheetByName(anterior);
|
|
||||||
sheet.setCurrentCell(sheet.getRange(celulaPrincipal)) ;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (gravou === 1 ) { return "Totalizado";}
|
|
||||||
Logger.log("gravou: " + gravou + ".");
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function checkMonth(nomedoMes)
|
|
||||||
{
|
|
||||||
Logger.log(" checkMonth nomedoMes: " + nomedoMes + ".");
|
|
||||||
switch (nomedoMes){
|
|
||||||
case 1:
|
|
||||||
case "Janeiro" :
|
|
||||||
return "1";
|
|
||||||
break;
|
|
||||||
case 2:
|
|
||||||
case "Fevereiro":
|
|
||||||
return "2";
|
|
||||||
break;
|
|
||||||
case 3:
|
|
||||||
case "Março":
|
|
||||||
return "3";
|
|
||||||
break;
|
|
||||||
case 4:
|
|
||||||
case "Abril":
|
|
||||||
return "4";
|
|
||||||
break;
|
|
||||||
case 5:
|
|
||||||
case "Maio":
|
|
||||||
return "5";
|
|
||||||
break;
|
|
||||||
case 6:
|
|
||||||
case "Junho":
|
|
||||||
return "6";
|
|
||||||
break;
|
|
||||||
case 7:
|
|
||||||
case "Julho":
|
|
||||||
return "7";
|
|
||||||
break;
|
|
||||||
case 8:
|
|
||||||
case "Agosto":
|
|
||||||
return "8";
|
|
||||||
break;
|
|
||||||
case 9:
|
|
||||||
case "Setembro":
|
|
||||||
return "9";
|
|
||||||
break;
|
|
||||||
case 10:
|
|
||||||
case "Outubro":
|
|
||||||
return "10";
|
|
||||||
break;
|
|
||||||
case 11:
|
|
||||||
case "Novembro":
|
|
||||||
return "11";
|
|
||||||
break;
|
|
||||||
case 12:
|
|
||||||
case "Dezembro":
|
|
||||||
return "12";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
return nomedoMes;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
from PIL import Image, ImageDraw, ImageFont
|
|
||||||
import qrcode
|
|
||||||
|
|
||||||
def gerar_carteirinha(militante_id, nome):
|
|
||||||
# Criar imagem base
|
|
||||||
img = Image.new('RGB', (300, 200), color=(255, 255, 255))
|
|
||||||
d = ImageDraw.Draw(img)
|
|
||||||
|
|
||||||
# Adicionar texto
|
|
||||||
font = ImageFont.load_default()
|
|
||||||
d.text((10, 10), f"Nome: {nome}", font=font, fill=(0, 0, 0))
|
|
||||||
d.text((10, 30), f"ID: {militante_id}", font=font, fill=(0, 0, 0))
|
|
||||||
|
|
||||||
# Gerar QR code
|
|
||||||
qr = qrcode.make(f"ID: {militante_id}")
|
|
||||||
img.paste(qr, (200, 50))
|
|
||||||
|
|
||||||
# Salvar imagem
|
|
||||||
img.save(f"carteirinha_{militante_id}.png")
|
|
||||||
@@ -28,7 +28,7 @@ SessionLocal = sessionmaker(bind=engine)
|
|||||||
|
|
||||||
def get_db_connection():
|
def get_db_connection():
|
||||||
"""
|
"""
|
||||||
Retorna uma nova sessão do banco de dados
|
Retorna uma nova sessão do banco de dados SQLite
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
return SessionLocal()
|
return SessionLocal()
|
||||||
|
|||||||
@@ -11,4 +11,4 @@ flask-wtf==1.2.1
|
|||||||
email-validator==2.1.0.post1
|
email-validator==2.1.0.post1
|
||||||
Bootstrap-Flask==2.4.1
|
Bootstrap-Flask==2.4.1
|
||||||
flask-bootstrap5==0.1.dev1
|
flask-bootstrap5==0.1.dev1
|
||||||
|
flask-mail
|
||||||
|
|||||||
Reference in New Issue
Block a user