-
Notifications
You must be signed in to change notification settings - Fork 32
/
card_db_fun.py
2857 lines (2126 loc) · 118 KB
/
card_db_fun.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
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sqlite3
import pyautogui
import os.path
import effects
import os
import re
import threading
import card_db_test
import home_db_fun
import home_db_query
import calendar
import locale
import emoji
import datetime
from frame_bank.card_frame_bank import CardFrameBank
from source_ui.categories import Texts_Erros
from PySide2.QtCore import *
from PySide2 import QtWidgets
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from datetime import datetime
from dateutil.relativedelta import relativedelta
from datetime import date
from asyncio.windows_events import NULL
from time import sleep
from random import randint
from login_pyside24 import Ui_MainWindow
from PySide2.QtCharts import QtCharts
from home_db_fun import Alerts
GLOBAL_SELECT_CARD_ADD = 0;
NUMERO_DE_CARTOES = NULL;
CARD_SELECTED = 0;
EXTRATO_ATUAL = 0;
class Thread_Add_Despesas_Xlsx(QThread):
finnish = Signal(str)
def __init__(self,table,card_id,row, label):
super().__init__()
self.table = table
self.card_id = card_id
self.row = row
self.label_gif = label
def run(self):
self.Start_Loading_Text()
for i in range(self.row):
print('------------------')
print('\n')
categoria = self.table.item(i, 0).text()
transacao = self.table.item(i, 1).text()
data = self.table.item(i, 2).text()
operacao = self.table.item(i, 3).text()
parcela = self.table.item(i, 4).text()
valor = self.table.item(i, 5).text()
# adiciona no banco de dados
# print teste dados
print('dados:')
print('\n')
print('categoria: '+str(categoria) + ' transacao: '+str(transacao)+' data: '+str(data)+' operacao: '+str(operacao)+' parcela: '+str(parcela)+' valor: '+str(valor))
# verifica parcelado
if self.table.item(i, 4).text() == 'Avista':
parcela = 1
PARCELADO = False
else:
valor_transacao = self.table.item(i, 5).text()
valor = float(valor_transacao.replace(',','.')) / int(self.table.item(i, 4).text())
PARCELADO = True
print('dados_tratados:')
print('\n')
print('parcelado: '+str(PARCELADO))
print('valor: '+str(valor))
rand_id = randint(0, 999999)
stats_payment = 'pendente'
index_parcelas = 0
# # Prepare date
data_transacao_original = funcoes_cartao._data_br_to_eng(self, self.table.item(i, 2).text())
data_transacao = funcoes_cartao._data_br_to_eng(self, self.table.item(i, 2).text())
print('data transacao: '+str(data_transacao))
print('data transacao original: '+str(data_transacao_original))
fechamento = card_db_test.Ui_db._fechamento(self.card_id)
vs_data_transacao = data_transacao_original[8:10]
print('fechamento: '+str(fechamento))
print('dia_data_transacao: ' +str(vs_data_transacao))
proximo_fat = 1
parcelado_prox_fatura = False
if vs_data_transacao >= fechamento:
proximo_fat = 2
parcelado_prox_fatura = True
else:
proximo_fat = 1
parcelado_prox_fatura = False
print('proximo_fat: '+str(proximo_fat))
print('parcelado_prox_fatura?: '+str(parcelado_prox_fatura))
# # Insert data
ind= 2
for i in range(int(parcela)):
soma_data = data_transacao
if parcelado_prox_fatura and ind == 2:
proximo_fat = ind
ind -= 1
else:
proximo_fat = 1
# Calculate the transaction date based on the statement and installment date
data_e_hora_em_texto = soma_data
format_date = datetime.strptime(data_e_hora_em_texto, '%Y-%m-%d')
date = format_date.date()
soma_mes = relativedelta(months=+proximo_fat)
ab = date + soma_mes
data_transacao = str(ab)
soma_data = str(ab)
print('soma data: '+str(soma_data))
print('data transacao: '+str(data_transacao))
# Set the payment value and installment type
if PARCELADO == False:
valor = valor
qt_parcel = 'Avista'
else:
valor = valor_transacao #resultado divido por parcela
index_parcelas += 1
qt_parcel = f"{index_parcelas}/{parcela}"
# Insert data in the database
db = 'extrato_cartao_%s'%(self.card_id)
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
cursor.execute("INSERT INTO "+db+" (categoria_transacao, nome_transacao, data_transacao, operacao, parcelas, valor_transacao, id, data_filter,status_payment) VALUES\
('"+categoria+"','"+transacao+"','"+data_transacao_original+"','"+operacao+"','"+qt_parcel+"','"+valor+"','"+str(rand_id)+"','"+data_transacao+"','"+stats_payment+"')")
banco.commit()
print('\n')
print('------------------')
self.finnish.emit('ok')
self.Stop_Loading_gif()
def Start_Loading_Text(self):
print('start loading')
self.label_gif.show()
def Stop_Loading_gif(self):
# dESTROY GIF
print('stop loading')
self.label_gif.setText('Importação Concluida')
sleep(1)
self.label_gif.setParent(None)
class funcoes_cartao(Ui_MainWindow):
def delete_card_if_bank_v(self,id_card):
veify = home_db_query.Return_Values_Conditions._return_bank_id(str(id_card))
if not veify:
funcoes_cartao.destroy_frame_card(self)
return True
else:
text = Texts_Erros.deletar_cartao_config()
home_db_fun.Alerts.Alert_all_error(self,text)
return False
def _clock_page_cards(self): #NT
current_time = QDateTime.currentDateTime()
label_time = current_time.toString('dd/MM/yyyy hh:mm:ss')
self.label_38.setText(label_time)
self.label_42.setText(label_time)
current_time = QTime.currentTime()
conditions= int(current_time.toString('hh'))
if conditions >= 0 and conditions < 4:
#page main
self.label_41.setText("Olá, Boa noite"+emoji.emojize(" :noite_estrelada:", language="pt"))
self.frame_45.setStyleSheet(u"background-image: url(:/time/night.png);background-repeat:no-repeat;background-position:center;")
#page cartao
self.label_36.setText("Olá, Boa noite"+emoji.emojize(" :noite_estrelada:", language="pt"))
self.frame_34.setStyleSheet(u"background-image: url(:/time/night.png);background-repeat:no-repeat;background-position:center;")
elif conditions > 4 and conditions < 12:
#page main:
self.label_41.setText("Olá, Bom dia"+emoji.emojize(" :praia_e_guarda-sol:", language="pt"))
self.frame_45.setStyleSheet(u"background-image: url(:/time/day.png);background-repeat:no-repeat;background-position:center;")
self.label_36.setText("Olá, Bom dia"+emoji.emojize(" :praia_e_guarda-sol:", language="pt"))
self.frame_34.setStyleSheet(u"background-image: url(:/time/day.png);background-repeat:no-repeat;background-position:center;")
elif conditions >= 12 and conditions < 18:
#page main:
self.label_41.setText("Olá, Boa tarde"+emoji.emojize(" :nuvem:", language="pt"))
self.frame_45.setStyleSheet(u"background-image: url(:/time/tarde.png);background-repeat:no-repeat;background-position:center;")
self.label_36.setText("Olá, Boa tarde"+emoji.emojize(" :nuvem:", language="pt"))
self.frame_34.setStyleSheet(u"background-image: url(:/time/tarde.png);background-repeat:no-repeat;background-position:center;")
elif conditions >= 18 and conditions < 24:
#page main:
self.label_41.setText("Olá, Boa noite"+emoji.emojize(" :noite_estrelada:", language="pt"))
self.frame_45.setStyleSheet(u"background-image: url(:/time/night.png);background-repeat:no-repeat;background-position:center;")
self.label_36.setText("Olá, Boa noite"+emoji.emojize(" :noite_estrelada:", language="pt"))
self.frame_34.setStyleSheet(u"background-image: url(:/time/night.png);background-repeat:no-repeat;background-position:center;")
def _start_values(self):
def thead():
indexdb= 0
list = []
self.frames = self.verticalLayout_3
for i in range(self.frames.count()):
a = self.frames.itemAt(i).widget().objectName()
index = re.sub('[^0-9]', '', a)
list.append(index)
indexdb = indexdb +1
# MES PARA FILTRO FATURA ATUAL:
mes = funcoes_cartao._mes(self)
for i in range(indexdb):
#CAPTURA VALOR DAS COMPRAS TOTAL
listdb= list[i]
#LIMITE UTILIZADO :
limite_utilizado = card_db_test.Return_Values_Calcs._limite_utilizado(listdb)
self.labelTitle_8.setText(QCoreApplication.translate("MainWindow", u"<html><head/><body><p><span style=\" font-size:14pt; color:#ffffff;\">Limite Utilizado:</span></p><p><span style=\" font-size:11pt; font-weight:600; color:#ffffff;\">R$"+str(limite_utilizado)+"</span></p></body></html>", None))
#LIMITE DISPONIVEL
limite_disponivel= card_db_test.Return_Values_Calcs._limite_disponivel(listdb)
self.labelTitle_10.setText(QCoreApplication.translate("MainWindow", u"<html><head/><body><p><span style=\" font-size:14pt; color:#ffffff;\">Limite Disponivel</span></p><p><span style=\" font-size:11pt; font-weight:600; color:#ffffff;\">R$"+str(limite_disponivel)+"</span></p></body></html>", None))
for val in range (2):
#SETA FATURA CARTAO E LIMITE DISPONIVEL
card_info = ['valor_faturaatual_cartao_','valor_limitedisponivel_cartao_']
fatura_atual = card_db_test.Return_Values_Calcs._fatural_atual(listdb,mes)
if float(fatura_atual) == 0:
mes2 = funcoes_cartao._mes_add_2(self)
fatura_atual = card_db_test.Return_Values_Calcs._fatural_atual(listdb,mes2)
if float(fatura_atual) == 0:
mes = funcoes_cartao._mes(self)
fatura_atual = card_db_test.Return_Values_Calcs._fatural_atual(listdb,mes)
limite_disponivel= card_db_test.Return_Values_Calcs._limite_disponivel(listdb)
text = [(QCoreApplication.translate("MainWindow", u"<html><head/><body><p align=\"justify\"><span style=\" font-size:20pt; font-weight:600; color:#ffffff\">R$"+str(fatura_atual)+"</span></p></body></html>", None)),
(QCoreApplication.translate("MainWindow", u"<html><head/><body><p align=\"justify\"><span style=\" font-weight:600; color:#ffffff;\">R$"+str(limite_disponivel)+"</span></p></body></html>", None))]
self.botoes = self.findChildren(QLabel , str(card_info[val]+list[i]))
self.botoes[0].setText(text[val])
try:
#SETA FINAL DO CARTAO
final_cartao = card_db_test.Ui_db._final_cartao(listdb)
card_info = 'txt_final_cartao_'
text_fimal = (QCoreApplication.translate("MainWindow", u"<html><head/><body><p align=\"justify\"><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">XXXX-XXXX-XXXX-"+str(final_cartao)+"</span></p></body></html>", None))
self.botoes = self.findChildren(QLabel , str(card_info+list[i]))
self.botoes[0].setText(text_fimal)
except:
pass
try:
#SETA TITULAR DO CARTAO
titular_cartao = card_db_test.Ui_db._titular(listdb)
card_info = 'txt_titular_cartao_'
text_fimal = (QCoreApplication.translate("MainWindow", u"<html><head/><body><p align=\"right\"><span style=\" font-size:11pt; font-weight:600; color:#ffffff;\">"+str(titular_cartao)+"</span></p></body></html>", None))
self.botoes = self.findChildren(QLabel , str(card_info+list[i]))
self.botoes[0].setText(text_fimal)
except:
pass
thread = threading.Thread(target=thead)
thread.start()
def _add_New_Lancamento_xlsx(self): # MOVER PARA API ISSO AQ DEUS DO CEU
id = self.id_card_xlsx_cliked.text()
table = self.tableWidget_2
errors = False
row = table.rowCount()
if row == 0:
errors = True
for i in range(row):
for j in range(6):
if table.item(i, j) is None or table.item(i, j).text() == '':
errors = True
Alerts.Alert_all_error(self,'Preencha todos os campos da linha '+str(i+1))
break
elif funcoes_cartao._validador_data(self,table.item(i, 2).text()) == False:
errors = True
print('data invalida')
Alerts.Alert_all_error(self,'Data invalida na linha '+str(i+1))
break
elif funcoes_cartao._validador_int(table.item(i, 5).text()) == False:
errors = True
Alerts.Alert_all_error(self,'Valor invalido na linha '+str(i+1))
break
if errors ==True:
pass
return False
PARCELADO = False
if errors ==False:
# chama thread para adicionar
label_gif_test = QLabel(self)
label_gif_test.setGeometry(795,500, 300, 50)
label_gif_test.setStyleSheet("background-color: rgb(10, 10, 10); border:1px solid rgba(255,255,255,40); color: rgb(255, 255, 255); border-radius: 10px; font-family: 'Segoe UI'; font-size: 12px;")
label_gif_test.setText('Importando Dados Por Favor aguarde...')
label_gif_test.setAlignment(Qt.AlignCenter)
#center
self.thread = Thread_Add_Despesas_Xlsx(table,id,row,label_gif_test)
self.thread.finnish.connect(funcoes_cartao.finish_import_xlsx(self))
self.thread.start()
def finish_import_xlsx(self):
# limpa tabela
self.stacked_configcartao0.setCurrentWidget(self.page_extrato)
today = datetime.today().strftime('%m%Y')
# home_db_fun.mainpage.load_extrato_filter(self)
funcoes_cartao.carrega_extrato_mes(self,str(today))
funcoes_cartao._Values_Individual(self)
funcoes_cartao.icontable_extrato(self)
Main_page_Cards._top_main_values_update(self)
Main_page_Cards._middle_main_values_update(self)
funcoes_cartao.group_main(self)
try:
self.grafico_categoria.setParent(None)
except:
pass
def _addRow(self): #TODO ADICIONA NOVA LINHA NO EXTRATO CARTAO #NTS
def thead(self):
global EXTRATO_ATUAL
card = EXTRATO_ATUAL
label_0 = self.lineEdit.text() # nome str
label_2 = self.lineEdit_2.text() # data str
label_3_ui = self.lineEdit_3.text() #valor int
#VALIDADOR DE CARACTERES
if (label_0== '') and (label_2== '') and (label_3_ui== '') :
pyautogui.confirm(text='Não foi preenchido os campos: \nNome, Valor e Data de transação ', title='Lançamento incorreto!', buttons=['OK', 'Cancel'])
elif (label_0== '') or (label_2== '') or (label_3_ui== '') :
pyautogui.confirm(text='Esta faltando campos: \nNome, Valor ou Data esta em branco! ', title='Lançamento incorreto!', buttons=['OK', 'Cancel'])
elif funcoes_cartao._validador_int(label_3_ui) == False:
pyautogui.confirm(text='Valor invalido', title='Invalido!', buttons=['OK', 'Cancel'])
elif funcoes_cartao._validador_data(self,label_2) == False:
pyautogui.confirm(text='Data invalida', title='Invalido!', buttons=['OK', 'Cancel'])
else:
PARCELADO = False
parcelas = str(self.comboBox_3.currentText())
label_3 = funcoes_cartao._brl_to_usd(label_3_ui)
#PARCELADO:
if parcelas == "Avista":
PARCELADO = False
parcelas = 1
else:
valor_transacao = float(label_3)/float(parcelas)
resultado_float=("{:.2f}".format(float(valor_transacao)))
PARCELADO = True
#DATA:
data_transacao = self.lineEdit_2.text() # para soma e filtro
data_transacao_original = self.lineEdit_2.text() # para ui
bug_fix = 0
index_parcelas = 0
data_transacao_original = funcoes_cartao._data_br_to_eng(self,data_transacao_original)
data_transacao = funcoes_cartao._data_br_to_eng(self,data_transacao)
fechamento = card_db_test.Ui_db._fechamento(card)
vs_data_transacao = data_transacao_original[8:10]
proximo_fat = 1
parcelado_prox_fatura = False
#FECHAMENTO AQ
if vs_data_transacao >= fechamento:
proximo_fat = 2 # lança no proximo fat
parcelado_prox_fatura = True
else:
proximo_fat = 1 #lança normalmente fatura ainda nao fechada
parcelado_prox_fatura = False
rand_id = randint(0, 999999) # ID DA COMPRA
ind= 2
for i in range(int(parcelas)):
soma_data = data_transacao
if parcelado_prox_fatura == True and ind == 2:
proximo_fat = ind
ind = ind -1
else:
proximo_fat = 1
data_e_hora_em_texto = soma_data
format_date = datetime.strptime(data_e_hora_em_texto, '%Y-%m-%d')
date = format_date.date()
soma_mes = relativedelta(months=+proximo_fat)
ab= date + soma_mes
data_transacao = str(ab)
soma_data =str(ab)
rowPosition = self.extrato_cartao_0.rowCount()
self.extrato_cartao_0.insertRow(rowPosition)
#TODO CAPTURA NOVO LANÇAMENTO E SETA NOVA LINHA
categoria_transacao = str(self.comboBox_2.currentText())
nome_transacao = self.lineEdit.text()
operacao = str(self.comboBox_4.currentText())
parcelas = str(self.comboBox_3.currentText())
stats_payment = 'pendente'
if PARCELADO == False:
valor = label_3
qt_parcel = 'Avista'
else:
valor =resultado_float
index_parcelas = index_parcelas +1
qt_parcel = str("%s/%s"%(index_parcelas,parcelas))
self.extrato_cartao_0.setItem(rowPosition , 1, QtWidgets.QTableWidgetItem(categoria_transacao))
self.extrato_cartao_0.setItem(rowPosition , 2, QtWidgets.QTableWidgetItem(nome_transacao))
self.extrato_cartao_0.setItem(rowPosition , 3, QtWidgets.QTableWidgetItem(data_transacao_original)) # data original para ui dia da compra
self.extrato_cartao_0.setItem(rowPosition , 4, QtWidgets.QTableWidgetItem(operacao))
self.extrato_cartao_0.setItem(rowPosition , 5, QtWidgets.QTableWidgetItem(str(qt_parcel)))
self.extrato_cartao_0.setItem(rowPosition , 6, QtWidgets.QTableWidgetItem(str(valor)))
self.extrato_cartao_0.setItem(rowPosition , 7, QtWidgets.QTableWidgetItem(str(rand_id)))
self.extrato_cartao_0.setItem(rowPosition , 8, QtWidgets.QTableWidgetItem(soma_data)) # data somada para filtros dia que cai na fatura
self.extrato_cartao_0.setItem(rowPosition , 9, QtWidgets.QTableWidgetItem(stats_payment))
# TODO COPIA DE FUNÇÃO SALVA EXTRATO
iddb = 'extrato_cartao_%s (id)'%(card)
db = 'extrato_cartao_%s'%(card)
idexdb = 'ids_transation_%s'%(card)
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
#finaliza busca
rowPosition = self.extrato_cartao_0.rowCount()
# cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS "+idexdb+" ON "+iddb+"")
rowPosition2 = self.extrato_cartao_0.rowCount()
rowPosition2 = rowPosition2-1
list= []
# colunasdb =['categoria_transacao','nome_transacao','data_transacao','operacao','parcelas','valor_transacao']
for col in range(9):
fix = col+1
captura_valroes_linha = self.extrato_cartao_0.item(rowPosition2,fix).text()
list.append(captura_valroes_linha)
# cursor.execute("UPDATE "+db+" SET '"+str(colunasdb[col])+"' = '"+str(captura_valroes_linha)+"' WHERE id = '"+str(sla)+"'")
cursor.execute("INSERT INTO "+db+" (categoria_transacao, nome_transacao, data_transacao, operacao, parcelas, valor_transacao, id, data_filter,status_payment) VALUES ('"+str(list[0])+"','"+str(list[1])+"','"+str(list[2])+"','"+str(list[3])+"','"+str(list[4])+"','"+str(list[5])+"','"+str(list[6])+"','"+str(list[7])+"','"+str(list[8])+"')")
banco.commit()
self.stacked_configcartao0.setCurrentWidget(self.page_extrato)
today = datetime.today().strftime('%m%Y')
funcoes_cartao.carrega_extrato_mes(self,str(today))
funcoes_cartao._Values_Individual(self)
funcoes_cartao.icontable_extrato(self)
Main_page_Cards._top_main_values_update(self)
Main_page_Cards._middle_main_values_update(self)
funcoes_cartao.group_main(self)
try:
self.grafico_categoria.setParent(None)
except:
pass
thread = threading.Thread(target=thead(self))
thread.start()
def _update_cards_config(self):
li =self.adclimite.text()
ti =self.adctitular.text()
fi= self.adcfinal.text()
ve =self.adcvencimento.text()
fe = self.adcfechamento.text()
linha = self.table_active_cards.currentRow()
id = self.table_active_cards.item(linha,6).text()
card_db_test.update_values.update_cards_config(id,ti,li,fi,ve,fe)
def icontable_extrato(self): # TODO MUDA ICONES QTABLEWIDGET
def theard():
print('icones table')
try:
rowPosition = self.extrato_cartao_0.rowCount()
#TODO 16 CATEGORIAS
list = ["delivery","appstrans","comida","mercado","lazer","icons8-casa-96","inuteis","servicos","streaming","urgencia","gatos","dogs","medico","viagem","eletronico","domesticos"]
icones=["Delivery",
"Apps Transporte",
"Comida",
"Mercado",
"Lazer",
"Casa",
"Coisas Inuteis",
"Serviços",
"Streaming",
"Urgencia",
"Gatos",
"Dogs",
"Medico",
"Viagem",
"Eletronicos",
"Domesticos"]
for row in range (rowPosition):
for seticon in range (16):
if self.extrato_cartao_0.item(row,1).text() == icones[seticon]:
icone = QIcon()
icone.addFile(u":/icons-cards/src-page-cartoes/"+list[seticon]+".png", QSize(), QIcon.Normal, QIcon.Off)
__qtablewidgetitem7900 = QtWidgets.QTableWidgetItem()
__qtablewidgetitem7900.setIcon(icone)
self.extrato_cartao_0.setItem(row, 0, QtWidgets.QTableWidgetItem(__qtablewidgetitem7900))
except Exception as e:
print(e)
pass
thread = threading.Thread(target=theard)
thread.start()
def hide_show_container(self):
def thead(self):
list = []
self.frames = self.verticalLayout_3
for i in range(self.frames.count()):
a = self.frames.itemAt(i).widget().objectName()
list.append(a)
count = len(list)
if count ==0:
self.CONTAINER_geral.hide()
else:
self.CONTAINER_geral.show()
thread = threading.Thread(target=thead(self))
thread.start()
def hide_show_logoff(self): #T
def thead(self):
list = []
self.frames = self.verticalLayout_3
for i in range(self.frames.count()):
a = self.frames.itemAt(i).widget().objectName()
list.append(a)
count = len(list)
if count ==0:
funcoes_cartao.inicia_cartoes_oculto_se_nao_existir(self)
else:
pass
thread = threading.Thread(target=thead(self))
thread.start()
def inicia_cartoes_oculto_se_nao_existir(self): #T
def thead(self):
#todo Ao iniciar pegar o id do db
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
#TODO PEGA NOME
cursor = banco.cursor()
cursor.execute("SELECT nome_cartao FROM card_active")
dadoslidos = cursor.fetchall()
lista = []
id_list = []
index: int = 0
for i in dadoslidos:
lista.append(dadoslidos[index][0])
index = index +1
index3: int = 0
cursor = banco.cursor()
cursor.execute("SELECT * FROM card_active")
dadoslidos3 = cursor.fetchall()
funcoes_cartao.hide_show_container(self)
for i in dadoslidos:
id_list.append(dadoslidos3[index3])
index3 = index3 +1
cartoes = lista
index2: int = NULL
for card in cartoes:
if card in lista:
global GLOBAL_SELECT_CARD_ADD
GLOBAL_SELECT_CARD_ADD = card
funcoes_cartao.creat_new_widget(self,id_list[index2][0])
else:
pass
index2 = index2 +1
funcoes_cartao.hide_show_container(self)
#TODO SUBFUNÇÃO CARREGA DADOS PARA PAGINA 2
try:
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
cursor.execute("SELECT id FROM card_active")
dadoslidos = cursor.fetchall()
nome_col = ["nome_cartao","titular","limite","final","vencimento","fechamento","id"]
index = 0
for linha in dadoslidos:
rowPosition = self.table_active_cards.rowCount()
self.table_active_cards.insertRow(rowPosition)
for col in range(7):
cursor = banco.cursor()
cursor.execute("SELECT "+str(nome_col[col])+" FROM card_active WHERE id = "+str(linha[0]))
dadoslidos2 = cursor.fetchall()
self.table_active_cards.setItem(index, col, QtWidgets.QTableWidgetItem(str(dadoslidos2[0][0])))
index +=1
except:
pass
thread = threading.Thread(target=thead(self))
thread.start()
def _update_table_config(self):
def thead():
try:
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
cursor.execute("SELECT id FROM card_active")
dadoslidos = cursor.fetchall()
nome_col = ["nome_cartao","titular","limite","final","vencimento","fechamento","id"]
index = 0
for linha in dadoslidos:
for col in range(7):
cursor = banco.cursor()
cursor.execute("SELECT "+str(nome_col[col])+" FROM card_active WHERE id = "+str(linha[0]))
dadoslidos2 = cursor.fetchall()
self.table_active_cards.setItem(index, col, QtWidgets.QTableWidgetItem(str(dadoslidos2[0][0])))
index +=1
except:
pass
thread = threading.Thread(target=thead())
thread.start()
def _delete_all_frame_cards(self):
def thead():
for i in reversed(range(self.verticalLayout_3.count())):
self.verticalLayout_3.itemAt(i).widget().setParent(None)
thread = threading.Thread(target=thead())
thread.start()
def destroy_frame_card(self): #NA PAG2 de config, ao remover um card, REMOVE DO DB, E REMOVE FRAME PAG 1 #T
def thead(self):
linha_selecionada = self.table_active_cards.currentRow()
if linha_selecionada >=0:
alert = pyautogui.confirm(text='Tem certeza que deseja remover este cartão?\nAo remover, todos os dados serão perdidos\nDeseja prossegur?', title='Importante!', buttons=['OK', 'Cancel'])
#try
if alert == "OK":
self.table_active_cards.removeRow(linha_selecionada)
lista_ids_active = []
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
cursor.execute("SELECT * FROM card_active")
dadoslidos = cursor.fetchall()
inde = 0
for i in dadoslidos:
lista_ids_active.append(dadoslidos[inde])
inde = inde +1
rowcount = self.table_active_cards.rowCount()
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
cursor.execute("DELETE FROM card_active WHERE id = "+str(lista_ids_active[linha_selecionada][0])+"")
card_delet = lista_ids_active[linha_selecionada][0]
#PEGAR O ID DA LINHA SELECIONADA AQUI NOVA FUNÇAO
iddb = 'extrato_cartao_%s'%(card_delet)
idexdb = 'ids_transation_%s'%(card_delet)
idex2 = 'index_cartao_%s'%(card_delet)
cursor.execute("DROP TABLE IF EXISTS "+str(iddb)+"")
cursor.execute("DROP INDEX IF EXISTS "+str(idexdb)+"")
cursor.execute("DROP INDEX IF EXISTS "+str(idex2)+"")
#apaga extrato e tudo do db
#apagar widget
list = []
self.frames = self.verticalLayout_3
for i in range(self.frames.count()):
a = self.frames.itemAt(i).widget().objectName()
list.append(a)
self.frame_remove = self.findChildren(QStackedWidget , str(list[linha_selecionada]))
self.frame_remove[0].deleteLater()
list.pop(linha_selecionada)
banco.commit()
banco.close()
global NUMERO_DE_CARTOES
NUMERO_DE_CARTOES = NUMERO_DE_CARTOES -1
else:
pass
else:
pyautogui.confirm(text='Nenhum cartão localizado ou Selecionado', title='Alerta', buttons=['OK'])
pass
try:
funcoes_cartao.group_main(self)
except:
pass
thread = threading.Thread(target=thead(self))
thread.start()
def mudaicondespesa(self): #NT
list = ["nulsmal","delivery","appstrans","comida","mercado","lazer","icons8-casa-96","inuteis","servicos","streaming","urgencia","gatos","dogs","medico","viagem","eletronico","domesticos"]
contents = self.comboBox_2.currentIndex()
self.frame_68.setStyleSheet(u"border-image: url(:/icons-cards/src-page-cartoes/"+list[contents]+".png);\n"
"\n"
"\n"
"background-position: center;\n"
"\n"
"background-repeat:no-repeat;")
def adicionar_cartao(self): #T
def thead(self):
#TODO INICIO 0.4
#todo vai chamar a funcao cartao ativos
label_0 = self.lineEdit.text() # nome str
label_2 = self.lineEdit_2.text() # data str
label_3_ui = self.lineEdit_3.text() #valor int
#VALIDADOR DE CARACTERES
titular = self.adctitular.text()
limite = self.adclimite.text()
final = self.adcfinal.text()
vencimento = self.adcvencimento.text()
fehcamento = self.adcfechamento.text()
if (titular== '') and (limite== '') and (final== '') and (vencimento== ''):
pyautogui.confirm(text='Não foi preenchido os campos: Titular, Limite, Final do cartao e Vencimento ', title='Lançamento incorreto!', buttons=['OK', 'Cancel'])
elif (titular== '') or (limite== '') or (final== '') or (vencimento== '') :
pyautogui.confirm(text='Esta faltando campos: \nTitular, Limite, Final do cartao ou Vencimento esta em branco! ', title='Lançamento incorreto!', buttons=['OK', 'Cancel'])
elif bool(re.search(r'\d', str(limite))) == False:
pyautogui.confirm(text='Valor de limite invalido', title='Invalido!', buttons=['OK', 'Cancel'])
elif bool(re.search(r'\d', str(final))) == False:
pyautogui.confirm(text='Final de cartao invalido', title='Invalido!', buttons=['OK', 'Cancel'])
elif bool(re.search(r'\d', str(vencimento))) == False:
pyautogui.confirm(text='Vencimento de cartao invalido', title='Invalido!', buttons=['OK', 'Cancel'])
elif int(vencimento) > 31 :
pyautogui.confirm(text='Vencimento de cartao invalido data acima de 31', title='Invalido!', buttons=['OK', 'Cancel'])
elif int(vencimento) < 0 :
pyautogui.confirm(text='Vencimento de cartao invalido data invalida', title='Invalido!', buttons=['OK', 'Cancel'])
else:
rowPosition = self.table_active_cards.rowCount()
self.table_active_cards.insertRow(rowPosition)
colunas = self.table_active_cards.columnCount()
cartao_selected = self.select_card.currentText()
rand_id = randint(0, 999999)
for i in range(colunas):
labels = [self.select_card.currentText(),self.adctitular.text(),self.adclimite.text(),self.adcfinal.text(),self.adcvencimento.text(),self.adcfechamento.text(),str(rand_id)]
self.table_active_cards.setItem(rowPosition , i, QtWidgets.QTableWidgetItem(labels[i]))
#TODO AGORA VAI SALVAR NO DB
# try:
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
#finaliza busca
rowPosition = self.table_active_cards.rowCount()-1
cursor.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_card_active ON card_active(id)")
#AQUI CRIA O ID DE ACORDO COM A QUANTIDADE DE CARTOES
#TODO aqui agr vai criar um id aletaorio de 4 digitos
cursor.execute("INSERT INTO card_active (id) VALUES ('"+str(rand_id)+"')")
colunas = self.table_active_cards.columnCount()
for i in range(colunas):
nome_col = ["nome_cartao", "titular", "limite","final","vencimento","fechamento","id"]
cardsrow= self.table_active_cards.item(rowPosition,i).text()
# cursor.execute("UPDATE card_active SET nome_cartao = '"+str()+"' WHERE id = '"+str(sla)+"'")
cursor.execute("UPDATE card_active SET "+str(nome_col[i])+" = '"+str(cardsrow)+"' WHERE id = '"+str(rand_id)+"'")
banco.commit()
#TODO INICIO 0.3
rowPosition = self.table_active_cards.rowCount()
try:
a = (os.path.dirname(os.path.realpath(__file__)))
banco = sqlite3.connect(''+a+'/bando_de_valores.db')
cursor = banco.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS extrato_cartao_"+str(rand_id)+" (nome_cartao text, categoria_transacao text, nome_transacao text, data_transacao date, operacao text, parcelas text, valor_transacao text, id text,data_filter text,status_payment)")
except:
pass
variaveasdsa = 0
id = rand_id
global GLOBAL_SELECT_CARD_ADD
GLOBAL_SELECT_CARD_ADD = cartao_selected
global NUMERO_DE_CARTOES
NUMERO_DE_CARTOES = NUMERO_DE_CARTOES +1
#TODO NOVAS ADICOES DE LOOP
funcoes_cartao.creat_new_widget(self,id)
funcoes_cartao.hide_show_container(self)
try:
cursor.execute("SELECT final FROM card_active WHERE id = "+str(rand_id)+"")
final_card = cursor.fetchall()
card_info = 'txt_final_cartao_'
text_fimal = (QCoreApplication.translate("MainWindow", u"<html><head/><body><p align=\"justify\"><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">XXXX-XXXX-XXXX-"+str(final_card[0][0])+"</span></p></body></html>", None))
self.botoes = self.findChildren(QLabel , str(card_info+str(rand_id)))
self.botoes[0].setText(text_fimal)
except:
pass
try:
#SETA TITULAR DO CARTAO
cursor.execute("SELECT titular FROM card_active WHERE id = "+str(rand_id)+"")
final_card = cursor.fetchall()