def opts(self, update, context): item = listUtils.searchAndGetItem(buff, update.message.from_user.username, update.message.chat.id) if (update.message.text == 'Abrir expediente'): update.message.reply_text( 'Deseja confirmar a abertura de expediente?', reply_markup=ReplyKeyboardMarkup( [['Sim, confirmar'], ['Não, finalizar']], one_time_keyboard=True)) return ENTRADA elif (update.message.text == 'Iniciar intervalo'): update.message.reply_text( 'Deseja confirmar a abertura de intervalo?', reply_markup=ReplyKeyboardMarkup( [['Sim, confirmar'], ['Não, finalizar']], one_time_keyboard=True)) return INTERVALO elif (update.message.text == 'Fechar intervalo'): update.message.reply_text( 'Deseja confirmar o fechamento de intervalo?', reply_markup=ReplyKeyboardMarkup( [['Sim, confirmar'], ['Não, finalizar']], one_time_keyboard=True)) return FIM_INTERVALO elif (update.message.text == 'Fechar expediente'): update.message.reply_text( 'Deseja confirmar o fechamento de expediente?', reply_markup=ReplyKeyboardMarkup( [['Sim, confirmar'], ['Não, finalizar']], one_time_keyboard=True)) return SAIDA elif (update.message.text == 'Reabrir expediente'): update.message.reply_text( 'Deseja confirmar a reabertura de expediente?', reply_markup=ReplyKeyboardMarkup( [['Sim, confirmar'], ['Não, finalizar']], one_time_keyboard=True)) return REABERTURA else: context.bot.send_message( chat_id=update.effective_chat.id, text='Resposta inválida, por favor, responda apenas com: ' + str(handleOpts(item)).replace('[', '').replace(']', '')) update.message.reply_text( 'Olá. Por favor, escolha a opção desejada.', reply_markup=ReplyKeyboardMarkup(handleOpts(item), one_time_keyboard=True)) return OPTS
def cancel(self, update, context): item = listUtils.searchAndGetItem(buff, update.message.from_user.username, update.message.chat.id) buff.pop(buff.index(item)) user = update.message.from_user self.logger.info("Usuario %s cancelou a conversa.", user.first_name) update.message.reply_text('Operação cancelada!', reply_markup=ReplyKeyboardRemove()) return ConversationHandler.END
def painel(self, update, context): try: file_id = update.message.photo[-1].file_id newFile = context.bot.getFile(file_id) item = listUtils.searchAndGetItem( buff, update.message.from_user.username, update.message.chat.id) newFile.download('media/' + item.media_dir + '/painel.jpg') except: update.message.reply_text( "Ocorreu um erro! Tente enviar apenas uma foto de uma vez. " + "Agora envie a foto do painel do veículo.") return PAINEL update.message.reply_text("Agora envie a foto da nota fiscal.") return NFISCAL
def fplaca(self, update, context): try: file_id = update.message.photo[-1].file_id newFile = context.bot.getFile(file_id) item = listUtils.searchAndGetItem( buff, update.message.from_user.username, update.message.chat.id) newFile.download('media/' + item.media_dir + '/placa.jpg') except: update.message.reply_text( "Ocorreu um erro! Tente enviar apenas uma foto de uma vez. " + "Agora envie a foto da placa do veículo.") return FPLACA update.message.reply_text( "Agora envie a foto da bomba após o abastecimento.") return BOMBAFIM
def nfiscal(self, update, context): try: file_id = update.message.photo[-1].file_id newFile = context.bot.getFile(file_id) item = listUtils.searchAndGetItem( buff, update.message.from_user.username, update.message.chat.id) newFile.download('media/' + item.media_dir + '/nota_fiscal.jpg') except: update.message.reply_text( "Ocorreu um erro! Tente enviar apenas uma foto de uma vez." + "Agora envie a foto da nota fiscal.") return NFISCAL try: a = float(str(item.qnt_litro).replace(',', '.')) b = float(str(item.val_litro).replace(',', '.')) item.val_total = str(round(float(a * b), 2)).replace('.', ',') update.message.reply_text(item.stringData(), parse_mode=ParseMode.MARKDOWN) reply_keyboard = [['Sim, confirmar'], ['Não, refazer'], ['Cancelar']] update.message.reply_text('O dados informados estão corretos?', reply_markup=ReplyKeyboardMarkup( reply_keyboard, one_time_keyboard=True)) return CONFIRM except Exception as e: try: context.bot.send_message(chat_id=445181781, text=str(e)) except: print('err in send') update.message.reply_text( 'Houve um erro ao tentar salvar! ' + 'O erro foi reportado, tente novamente mais tarde.', reply_markup=ReplyKeyboardRemove()) textLogger.log('Combustivel - ' + str(e)) print(e) buff.pop(buff.index(item)) return ConversationHandler.END
def confirm(self, update, context): item = listUtils.searchAndGetItem(buff, update.message.from_user.username, update.message.chat.id) if not item: update.message.reply_text( 'Houve um erro ao tentar salvar! ' + 'O erro foi reportado, tente novamente mais tarde.', reply_markup=ReplyKeyboardRemove()) buff.clear() textLogger.log('Combustivel - not item ;' + listUtils.listItens(buff)) if (update.message.text == 'Sim, confirmar'): context.bot.send_message(chat_id=update.effective_chat.id, text='Salvando dados...') try: Session = Database.Session session = Session() motorista = session.query(Motorista).filter_by( telegram_user=item.username).first() registro = Registro(motorista, item.placa, str(item.quilometragem) + ' KM', str(item.qnt_litro) + ' L', 'R$ ' + str(item.val_litro), 'R$ ' + str(item.val_total), item.tp_combustivel, item.posto, item.media_dir) session.add(registro) session.commit() session.close() except Exception as e: try: context.bot.send_message(chat_id=445181781, text=str(e)) except: print('err in send') update.message.reply_text( 'Houve um erro ao tentar salvar! ' + 'O erro foi reportado, tente novamente mais tarde.', reply_markup=ReplyKeyboardRemove()) textLogger.log('Combustivel - ' + str(e)) print(e) buff.pop(buff.index(item)) return ConversationHandler.END buff.pop(buff.index(item)) update.message.reply_text( 'Dados enviados com sucesso! Caso haja alguma inconsistência favor informar para @renanmgomes ou @igorpittol.', reply_markup=ReplyKeyboardRemove()) local_path = 'media/ABASTECIMENTO-' + datetime.now( timezone('America/Sao_Paulo')).strftime('%b-%Y') + '.xlsx' register_now = datetime.now(timezone('America/Sao_Paulo')) range_intervalo = CalendarUtils.getRangeByMonthUm( register_now.month, register_now.year) Session = Database.Session session = Session() registros = session.query(Registro).filter( Registro.created_at >= range_intervalo[0], Registro.created_at < range_intervalo[1]).order_by( Registro.id.asc()) try: workbook = xlsxwriter.Workbook(local_path) worksheet = workbook.add_worksheet() row = 0 col = 0 for registro in registros: worksheet.write(row, col + 0, registro.id) worksheet.write( row, col + 1, str( registro.created_at.astimezone( timezone('America/Sao_Paulo')).day) + '/' + str( registro.created_at.astimezone( timezone('America/Sao_Paulo')).month) + '/' + str( registro.created_at.astimezone( timezone('America/Sao_Paulo')).year)) worksheet.write( row, col + 2, registro.created_at.astimezone( timezone('America/Sao_Paulo')).strftime('%H:%M')) worksheet.write(row, col + 3, registro.posto) worksheet.write(row, col + 4, ' ') worksheet.write( row, col + 5, CalendarUtils.REV_FULL_MONTHS[ registro.created_at.month]) worksheet.write(row, col + 6, registro.placa) worksheet.write(row, col + 7, registro.quilometragem.replace(' KM', '')) worksheet.write(row, col + 8, registro.created_at.year) worksheet.write(row, col + 9, registro.qnt_litro.replace(' L', '')) worksheet.write(row, col + 10, registro.val_litro.replace('R$ ', '')) worksheet.write(row, col + 11, registro.motorista.nome) worksheet.write(row, col + 12, registro.tp_combustivel.split(' ')[0]) worksheet.write(row, col + 13, registro.tp_combustivel) worksheet.write(row, col + 14, registro.val_total.replace('R$ ', '')) row += 1 workbook.close() except Exception as e: textLogger.log('Planilha Combustivel - ' + str(e)) print(e) session.close() os.remove(local_path) return ConversationHandler.END session.close() gdrive.upload_gdrive(local_path, local_path.replace('media/', '')) os.remove(local_path) return ConversationHandler.END elif (update.message.text == 'Não, refazer'): update.message.reply_text('Ok! Vamos refazer então.', reply_markup=ReplyKeyboardMarkup( [['Continuar']], one_time_keyboard=True)) shutil.rmtree('media/' + item.media_dir, ignore_errors=True) buff.pop(buff.index(item)) return RETORNO elif (update.message.text == 'Cancelar'): context.bot.send_message(chat_id=update.effective_chat.id, text='Operação cancelada!') shutil.rmtree('media/' + item.media_dir, ignore_errors=True) buff.pop(buff.index(item)) return ConversationHandler.END else: reply_keyboard = [['Sim, confirmar'], ['Não, refazer'], ['Cancelar']] context.bot.send_message( chat_id=update.effective_chat.id, text= 'Resposta inválida, por favor, responda apenas [Sim, confirmar], [Não, refazer] ou [Cancelar]' ) update.message.reply_text(item.stringData(), parse_mode=ParseMode.MARKDOWN) update.message.reply_text('O dados informados estão corretos?', reply_markup=ReplyKeyboardMarkup( reply_keyboard, one_time_keyboard=True)) return CONFIRM return ConversationHandler.END
def reabertura(self, update, context): item = listUtils.searchAndGetItem(buff, update.message.from_user.username, update.message.chat.id) if (update.message.text == 'Sim, confirmar'): listUtils.searchAndUpdate( buff, update.message.from_user.username, update.message.chat.id, 'fim_intervalo', datetime.now(timezone('America/Sao_Paulo')).replace( second=0, microsecond=0)) context.bot.send_message(chat_id=update.effective_chat.id, text='Salvando dados...') try: Session = Database.Session session = Session() if item.role == 'motorista': motorista = session.query(Motorista).filter_by( telegram_user=item.username).first() pontoDb = session.query(PontosMotorista).filter_by( motorista_id=motorista.id).order_by( PontosMotorista.id.desc()).first() intervalo = IntervalosDePontoMotorista( pontoDb, pontoDb.saida, item.fim_intervalo) else: administrativo = session.query(Administrativo).filter_by( telegram_user=item.username).first() pontoDb = session.query(PontosAdministrativo).filter_by( administrativo_id=administrativo.id).order_by( PontosAdministrativo.id.desc()).first() intervalo = IntervalosDePontoAdministrativo( pontoDb, pontoDb.saida, item.fim_intervalo) pontoDb.saida = None session.add(intervalo) session.add(pontoDb) session.commit() if item.role == 'motorista': intervalos = session.query( IntervalosDePontoMotorista).filter_by( ponto_motorista_id=pontoDb.id) else: intervalos = session.query( IntervalosDePontoAdministrativo).filter_by( ponto_administrativo_id=pontoDb.id) item.intervalos = intervalos session.close() except Exception as e: update.message.reply_text( 'Houve um erro ao tentar salvar! ' + 'O erro foi reportado, tente novamente mais tarde.', reply_markup=ReplyKeyboardRemove()) print(e) buff.pop(buff.index(item)) return ConversationHandler.END buff.pop(buff.index(item)) item.saida = None update.message.reply_text( 'Dados enviados com sucesso! Caso haja alguma inconsistência favor informar para @renanmgomes ou @igorpittol.', reply_markup=ReplyKeyboardRemove()) context.bot.send_message(chat_id=update.effective_chat.id, text=item.stringData(), parse_mode=ParseMode.MARKDOWN) return ConversationHandler.END elif (update.message.text == 'Não, finalizar'): context.bot.send_message(chat_id=update.effective_chat.id, text='Operação cancelada!', reply_markup=ReplyKeyboardRemove()) buff.pop(buff.index(item)) return ConversationHandler.END else: context.bot.send_message( chat_id=update.effective_chat.id, text='Resposta inválida, por favor, responda apenas com: ' + '"Sim, confirmar" ou "Não, finalizar"') update.message.reply_text( 'Deseja confirmar a reabertura de expediente?', reply_markup=ReplyKeyboardMarkup( [['Sim, confirmar'], ['Não, finalizar']], one_time_keyboard=True)) return REABERTURA
def periodo_envio(self, update, context): item = listUtils.searchAndGetItem(buff, update.message.from_user.username, update.message.chat.id) if not [update.message.text] in item.periodos: context.bot.send_message( chat_id=update.effective_chat.id, text='Período inválido, por favor, informe novamente.') update.message.reply_text('Selecione o período:', reply_markup=ReplyKeyboardMarkup( item.periodos, one_time_keyboard=True)) return PERIODO_ENVIO Session = Database.Session session = Session() if item.role_send == 'administrativo': administrativo = session.query(Administrativo).filter_by( telegram_user=item.username_send).first() month, year = update.message.text.split(' ') range_intervalo = CalendarUtils.getRangeByFullMonth(month, year) adm_ponto = session.query(PontosAdministrativo).filter_by( administrativo_id=administrativo.id ).filter( PontosAdministrativo.entrada >= range_intervalo[0], PontosAdministrativo.entrada <= range_intervalo[1], PontosAdministrativo.saida != None ).order_by( PontosAdministrativo.entrada.asc() ) clock_ins = [] local_path = 'media/PONTOS-' + \ datetime.now(timezone('America/Sao_Paulo') ).strftime('%b-%Y') + '.xlsx' model_to_impress = administrativo pontos_dict = dict() for ponto in adm_ponto: item.acumulateHorasTrabalhadas(ponto.horas_trabalhadas) timetuple = timestampToTimeTuple(str(ponto.entrada)) timetuple2 = timestampToTimeTuple(str(ponto.saida)) intervalos = session.query(IntervalosDePontoAdministrativo).filter_by( ponto=ponto) pontos_dict[timetuple[0]] = (timetuple[1], timetuple2[1], ponto.horas_trabalhadas, ponto.horas_extra, datetimeArrToTimeTupleArr) clock_ins.append(item.pontoToArrayFormatted(ponto, intervalos)) try: workbook = xlsxwriter.Workbook(local_path) worksheet = workbook.add_worksheet() row = 0 col = 0 worksheet.write(0, 0, "DATA") worksheet.write(0, 1, "ENTRADA") worksheet.write(0, 2, "SAIDA") worksheet.write(0, 3, "HORAS TRABALHADAS") worksheet.write(0, 4, "HORAS EXTRA") for i in range(CalendarUtils.getLastDayMonth(month, year)): dia = str('%.2d' % (i+1) + '/' + '%.2d' % CalendarUtils.FULL_MONTHS[month] + '/' + year) worksheet.write(row + i + 1, col, dia) if dia in pontos_dict: x = pontos_dict[dia] worksheet.write(row + i + 1, 1, x[0]) worksheet.write(row + i + 1, 2, x[1]) worksheet.write(row + i + 1, 3, x[2]) worksheet.write(row + i + 1, 4, x[3]) workbook.close() except Exception as e: print(e) os.remove(local_path) elif item.role_send == 'motorista': motorista = session.query(Motorista).filter_by( telegram_user=item.username_send).first() month, year = update.message.text.split(' ') range_intervalo = CalendarUtils.getRangeByFullMonth(month, year) motorista_ponto = session.query(PontosMotorista).filter_by( motorista_id=motorista.id ).filter( PontosMotorista.entrada >= range_intervalo[0], PontosMotorista.entrada <= range_intervalo[1], PontosMotorista.saida != None ).order_by( PontosMotorista.entrada.asc() ) clock_ins = [] model_to_impress = motorista local_path = 'media/PONTOS-' + \ datetime.now(timezone('America/Sao_Paulo') ).strftime('%b-%Y') + '.xlsx' pontos_dict = dict() for ponto in motorista_ponto: item.acumulateHorasTrabalhadas(ponto.horas_trabalhadas) timetuple = timestampToTimeTuple(str(ponto.entrada)) timetuple2 = timestampToTimeTuple(str(ponto.saida)) intervalos = session.query(IntervalosDePontoMotorista).filter_by( ponto=ponto) pontos_dict[timetuple[0]] = (timetuple[1], timetuple2[1], ponto.horas_trabalhadas, ponto.horas_extra, datetimeArrToTimeTupleArr) clock_ins.append(item.pontoToArrayFormatted(ponto, intervalos)) try: workbook = xlsxwriter.Workbook(local_path) worksheet = workbook.add_worksheet() row = 0 col = 0 worksheet.write(0, 0, "DATA") worksheet.write(0, 1, "ENTRADA") worksheet.write(0, 2, "SAIDA") worksheet.write(0, 3, "HORAS TRABALHADAS") worksheet.write(0, 4, "HORAS EXTRA") for i in range(CalendarUtils.getLastDayMonth(month, year)): dia = str('%.2d' % (i+1) + '/' + '%.2d' % CalendarUtils.FULL_MONTHS[month] + '/' + year) worksheet.write(row + i + 1, col, dia) if dia in pontos_dict: x = pontos_dict[dia] worksheet.write(row + i + 1, 1, x[0]) worksheet.write(row + i + 1, 2, x[1]) worksheet.write(row + i + 1, 3, x[2]) worksheet.write(row + i + 1, 4, x[3]) workbook.close() except Exception as e: print(e) os.remove(local_path) factory = PdfFactory('media/' + item.media_dir) buff.pop(buff.index(item)) fileToSend = factory.sheetHours( month, year, model_to_impress, clock_ins, item.horas_trabalhadas_send, 'N/A') context.bot.sendDocument(chat_id=item.chat_id, document=fileToSend) administrativo = session.query(Administrativo).filter_by( telegram_user=update.message.from_user.username).first() if not (administrativo is None): planilha = open(local_path, 'rb') context.bot.sendDocument(chat_id=item.chat_id, document=planilha) os.unlink(fileToSend.name) os.remove(local_path) return ConversationHandler.END