Fórum Projeto de Cadastro de empresas #620577
04/10/2023
0
Main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | def update_company( self ): # Verifique se algum item está selecionado na tabela selected_items = self .tab_company.selectedItems() if not selected_items or len (selected_items) < 12 : msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText( "Selecione uma empresa para atualizar." ) msg. exec () return # Obtenha os dados da linha selecionada selected_row = [selected_items[i].text() for i in range ( 12 )] # Defina o campo de tributação como vazio (ou qualquer valor padrão que desejar) selected_row.append("") # Você pode definir um valor padrão aqui try : print ( "Antes de atualizar no banco de dados" ) # ATUALIZAR DADOS NO BANCO db = Data_base() db.connect() db.update_company( tuple (selected_row)) db.close_connection() print ( "Após atualizar no banco de dados" ) msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText( "Dados atualizados com sucesso!" ) msg. exec () # Limpa a tabela completamente self .tab_company.clearContents() # Recarrega os dados da tabela self .buscar_empresas() except Exception as e: print (f "Erro ao atualizar dados no banco de dados: " ) |

Wanderlan
Curtir tópico
+ 0Posts
04/10/2023
Wanderlan
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | import sqlite3 class Data_base: def __init__( self , name = ' 'system.db' ') - > None : self .name = name def connect( self ): try : print ( "Abrindo conexão com o banco de dados..." ) self .connection = sqlite3.connect( self .name) print ( "Conexão aberta com sucesso!" ) except Exception as e: print (f "Erro ao abrir a conexão com o banco de dados: " ) def close_connection( self ): try : print ( "Fechando conexão com o banco de dados..." ) self .connection.close() print ( "Conexão fechada com sucesso!" ) except Exception as e: print (f "Erro ao fechar a conexão com o banco de dados: " ) def create_table_company( self ): cursor = self .connection.cursor() cursor.execute( """ CREATE TABLE IF NOT EXISTS Empresa ( CNPJ TEXT PRIMARY KEY, NOME TEXT, LOGRADOURO TEXT, NUMERO TEXT, COMPLEMENTO TEXT, BAIRRO TEXT, CEP TEXT, MUNICIPIO TEXT, UF TEXT, TELEFONE TEXT, EMAIL TEXT, TRIBUTACAO TEXT ) """ ) def register_company( self , fullDataSet): campos_tabela = (' 'CNPJ' ', ' 'NOME' ', ' 'LOGRADOURO' ', ' 'NUMERO' ', ' 'COMPLEMENTO' ', ' 'BAIRRO' ', ' 'CEP' ', ' 'MUNICIPIO' ', ' 'UF' ', ' 'TELEFONE' ', ' 'EMAIL' ', ' 'TRIBUTACAO' ') qntd = "?,?,?,?,?,?,?,?,?,?,?,?" cursor = self .connection.cursor() try : cursor.execute(f """INSERT INTO Empresa ({", ".join(campos_tabela)}) VALUES()""" , fullDataSet) self .connection.commit() # Certifique-se de realizar o commit após a inserção. print ( "Registro inserido com sucesso!" ) return "OK" except Exception as e: print (f "Erro ao inserir registro: " ) return "Erro" def select_all_companies( self ): try : cursor = self .connection.cursor() cursor.execute( "SELECT * FROM Empresa ORDER BY NOME" ) empresas = cursor.fetchall() print ( "Dados recuperados com sucesso!" ) return empresas except Exception as e: print (f "Erro ao recuperar dados: " ) return None def delete_company( self , id ): try : cursor = self .connection.cursor() cursor.execute(f "DELETE FROM Empresa WHERE CNPJ = '''' " ) self .connection.commit() return "Cadastro de empresa excluído com sucesso!" except : return "Erro ao excluir registro!" def update_company( self , fullDataSet): cursor = self .connection.cursor() cursor.execute(f """UPDATE Empresa SET CNPJ = ?, NOME = ?, LOGRADOURO = ?, NUMERO = ?, COMPLEMENTO = ?, BAIRRO = ?, CEP = ?, MUNICIPIO = ?, UF = ?, TELEFONE = ?, EMAIL = ?, TRIBUTACAO = ? WHERE CNPJ = ?""" , fullDataSet) self .connection.commit() |
Gostei + 0
04/10/2023
Wanderlan
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | from PySide6.QtCore import Qt, QEasingCurve, QPropertyAnimation from PySide6.QtGui import QIcon from PySide6.QtWidgets import ( QApplication, QMainWindow, QStyleFactory, QMessageBox, QTableWidgetItem ) from ui_main import Ui_MainWindow import sys from ui_funtions import consulta_cnpj from database import Data_base class MainWindow(QMainWindow, Ui_MainWindow): def __init__( self ): super (MainWindow, self ).__init__() self .setupUi( self ) self .setWindowTitle( "ATRIBUT - Sistema de cadastro" ) appIcon = QIcon() # Use QtGui.QIcon() self .setWindowIcon(appIcon) # TOGGLE BUTTON self .btn_toggle.clicked.connect( self .leftMenu) # PÁGINAS DO SISTEMA self .btn_home.clicked.connect( lambda : self .Pages.setCurrentWidget( self .pg_home)) # Botão à esquerda (navegar para a página de cadastro) self .btn_cadastrar.clicked.connect( lambda : self .Pages.setCurrentWidget( self .pg_cadastrar)) # Botão inferior (cadastrar a empresa) self .pushButton_5.clicked.connect( self .cadastrar_empresas) # Nome corrigido self .btn_alterar.clicked.connect( self .update_company) self .buscar_empresas() self .btn_sobre.clicked.connect( lambda : self .Pages.setCurrentWidget( self .pg_sobre)) self .btn_contatos.clicked.connect( lambda : self .Pages.setCurrentWidget( self .pg_contatos)) # PREENCHER AUTOMATICAMENTE OS DADOS DO CNPJ self .txt_cnpj.editingFinished.connect( self .consult_api) def leftMenu( self ): width = self .left_menu.width() if width = = 9 : newWidth = 200 else : newWidth = 9 self .animation = QPropertyAnimation( self .left_menu, b "maximumWidth" ) self .animation.setDuration( 500 ) self .animation.setStartValue(width) self .animation.setEndValue(newWidth) self .animation.setEasingCurve(QEasingCurve.InOutQuart) self .animation.start() def consult_api( self ): campos = consulta_cnpj( self .txt_cnpj.text()) # Organize os dados corretamente self .txt_cnpj.setText(campos[ 0 ]) # CNPJ self .txt_nome.setText(campos[ 1 ]) # Nome da empresa self .txt_logradouro.setText(campos[ 2 ]) # Logradouro self .txt_numero.setText(campos[ 3 ]) # Número do estabelecimento self .txt_complemento.setText(campos[ 4 ]) # Complemento do endereço self .txt_bairro.setText(campos[ 5 ]) # Bairro da empresa self .txt_municipio.setText(campos[ 6 ]) # Município self .txt_uf.setText(campos[ 7 ]) # UF self .txt_cep.setText(campos[ 8 ].replace( '.' , ' ').replace(' - ', ' ')) # CEP self .txt_telefone.setText(campos[ 9 ].replace( '(' , ' ').replace(' - ', ' ').replace(' ) ', ' ')) # Telefone self .txt_email.setText(campos[ 10 ]) # Email self .txt_tributacao.setText("") # Deixe o campo de Tributação em branco def cadastrar_empresas( self ): db = Data_base() db.connect() # Verifique se o campo de tributação foi preenchido corretamente tributacao = self .txt_tributacao.text().strip().lower() # Converte para minúsculas tributacao_valida = tributacao in [ "mei" , "simples nacional" , "imune" , "isenta" , "lucro presumido" , "lucro real" ] if not tributacao_valida: msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle( "Erro de Tributação" ) msg.setText( "Informe o regime de tributação!\\nOpções válidas: MEI, SIMPLES NACIONAL, IMUNE, ISENTA, LUCRO PRESUMIDO, LUCRO REAL" ) msg. exec () db.close_connection() return # Organize os dados na ordem correta das colunas fullDataSet = ( self .txt_cnpj.text(), self .txt_nome.text(), self .txt_logradouro.text(), self .txt_numero.text(), self .txt_complemento.text(), self .txt_bairro.text(), self .txt_cep.text(), self .txt_municipio.text(), self .txt_uf.text(), self .txt_telefone.text().strip(), self .txt_email.text(), tributacao, # Use a tributação validada aqui ) # CADASTRAR NO BANCO DE DADOS resp = db.register_company(fullDataSet) self .buscar_empresas() if resp = = "OK" : msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle( "Cadastro realizado" ) msg.setText( "Cadastro realizado com sucesso" ) msg. exec () db.close_connection() return else : msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setWindowTitle( "Erro" ) msg.setText( "Erro ao cadastrar, verifique se as informações foram preenchidas corretamente!" ) msg. exec () db.close_connection() return def buscar_empresas( self ): db = Data_base() db.connect() result = db.select_all_companies() self .tab_company.clearContents() self .tab_company.setRowCount( len (result)) for row, text in enumerate (result): for column, data in enumerate (text): self .tab_company.setItem(row, column, QTableWidgetItem( str (data))) db.close_connection() def update_company( self ): # Verifique se algum item está selecionado na tabela selected_items = self .tab_company.selectedItems() if not selected_items or len (selected_items) < 12 : msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText( "Selecione uma empresa para atualizar." ) msg. exec () return # Obtenha os dados da linha selecionada selected_row = [selected_items[i].text() for i in range ( 12 )] # Defina o campo de tributação como vazio (ou qualquer valor padrão que desejar) selected_row.append("") # Você pode definir um valor padrão aqui try : print ( "Antes de atualizar no banco de dados" ) # ATUALIZAR DADOS NO BANCO db = Data_base() db.connect() db.update_company( tuple (selected_row)) db.close_connection() print ( "Após atualizar no banco de dados" ) msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText( "Dados atualizados com sucesso!" ) msg. exec () # Limpa a tabela completamente self .tab_company.clearContents() # Recarrega os dados da tabela self .buscar_empresas() except Exception as e: print (f "Erro ao atualizar dados no banco de dados: " ) if __name__ = = "__main__" : db = Data_base() db.connect() db.create_table_company() db.close_connection() app = QApplication(sys.argv) app.setStyle(QStyleFactory.create( "WindowsVista" )) window = MainWindow() window.show() sys.exit(app. exec ()) |
Gostei + 0
04/10/2023
Wanderlan
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import requests import json def consulta_cnpj(cnpj): querystring = { "token" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" , "cnpj" : cnpj, "plugin" : "RF" } response = requests.get(url, params = querystring) if response.status_code = = 200 : resp = json.loads(response.text) # Mapeie os dados da API para os campos corretos return ( resp.get( 'cnpj' , ''), resp.get( 'nome' , ''), resp.get( 'logradouro' , ''), resp.get( 'numero' , ''), resp.get( 'complemento' , ''), resp.get( 'bairro' , ''), resp.get( 'municipio' , ''), resp.get( 'uf' , ''), resp.get( 'cep' , ' ').replace(' . ', ' ').replace(' - ', ' '), resp.get( 'telefone' , ' ').replace(' ( ', ' ').replace(' - ', ' ').replace(' ) ', ' '), resp.get( 'email' , ''), "" ) else : print (f "Erro ao consultar CNPJ: Código de status {response.status_code}" ) return None |
Gostei + 0
05/10/2023
Nomad
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)