-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
1963 lines (1776 loc) · 103 KB
/
functions.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
# interface libs =================================
from largeVariables import *
from tkinter import messagebox
from customtkinter import *
from tkinter import filedialog
from tkinter import *
from tkinter import TclError
from tkinter.colorchooser import askcolor
from PIL import Image
import re
from docx import Document
from docx.shared import Pt
# functions libs ==================================
import os
import requests
from datetime import datetime
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
import shutil
class GeneralFunctions:
def backup_dataBaes(self):
# pick directory if origin =========================
origin = './resources'
destiny = os.path.join(os.path.expanduser("~"), "KonectSys/backup/resources")
# coping ================================
if os.path.exists(destiny):
shutil.rmtree(destiny)
shutil.copytree(origin, destiny)
else:
shutil.copytree(origin, destiny)
self.message_window(1, 'Concluído', messagein=f'Backup feito com sucesso')
@staticmethod
def backup_dataBaes_discret():
# pick directory if origin =========================
origin = './resources'
destiny = os.path.join(os.path.expanduser("~"), "KonectSys/backup/resources")
# coping ================================
if os.path.exists(destiny):
shutil.rmtree(destiny)
shutil.copytree(origin, destiny)
else:
shutil.copytree(origin, destiny)
def loading_database(self):
# pick directory if origin =========================
origin = os.path.join(os.path.expanduser("~"), "KonectSys/backup/resources")
destiny = './resources'
# coping ================================
if os.path.exists(origin):
shutil.rmtree(destiny)
shutil.copytree(origin, destiny)
self.message_window(1, 'Concluído', messagein=f'Carregamento do backup feito com sucesso')
def insert_treeview_informations(self, treeview, infos, line_color):
for info in infos:
if self.lineTreeviewColor[line_color] % 2 == 0:
treeview.insert('', 'end', values=info, tags='oddrow')
else:
treeview.insert('', 'end', values=info, tags='evenrow')
self.lineTreeviewColor[line_color] += 1
@staticmethod
def pick_informations_treeview(treeview):
selection = treeview.get_children()
information = []
for i in selection:
information.append(treeview.item(i, 'values'))
return information
@staticmethod
def selection_treeview(treeview):
selection = treeview.selection()
information = []
for i in selection:
information.append(treeview.item(i, 'values'))
return information
@staticmethod
def request_adrees(zip_code, informations):
# treating the cep =============================
treatedZipCode = zip_code.replace('-', '').replace(' ', '').replace('.', '')
# validating if the zip code have eight numbers =======================
if len(treatedZipCode) == 8:
try:
# making request in the site ========================
request = requests.get(f'http://viacep.com.br/ws/{treatedZipCode}/json/').json()
except Exception:
# error in request ===================
pass
else:
if len(request) > 1:
# deleting informations in the entrys =====================
for information in informations:
information.delete(0, END)
# insert informations in the entrys ========================
informations[0].insert(0, request['localidade'])
informations[1].insert(0, request['uf'])
def validation(self, infos, type_validation, index=None):
if type_validation == 1:
for info in infos[0]:
if info == '' or info == 'R$,00':
return False
elif type_validation == 2:
if not infos.replace('.', '', 1).isdigit():
return False
elif type_validation == 3:
for c in infos:
if c.isalpha() or c == '.':
return False
elif type_validation == 4:
for c in infos:
if c.isalpha() or c == '.':
return False
elif type_validation == 5:
for info in infos:
if info == '' or info == 'R$,00' or info == ':00':
return False
elif type_validation == 6:
for c in infos:
if c.isalpha() or c == '.':
return False
if len(infos) != 12:
return False
elif type_validation == 7:
for info in infos:
for c in info:
if c.isalpha():
return False
elif type_validation == 8:
for info in infos:
for c in info[2:]:
if c.isalpha() or c == '.':
return False
elif type_validation == 9:
for c in infos[2:]:
if c.isalpha() or c == '.':
return False
elif type_validation == 10:
date = re.findall(date_pattern, infos)
if not date:
return False
elif type_validation == 11:
quantity = self.dataBases['informations'].searchDatabase(f'SELECT quantidade_em_estoque FROM Produtos WHERE nome LIKE "%{infos}%"')
if quantity:
if int(quantity[0][0]) > 0:
return True
else:
self.message_window(2, 'Sem', 'Este produto está em falta no estque')
return False
return True
@staticmethod
def treating_numbers(info=None, type_treating=1, values=None, entry2=None, ide=4):
if type_treating == 1:
if ',' in info:
value = info.replace('R$', '').strip().split(',')
if value[1] == '':
return 'R$' + ','.join(value) + '00'
else:
return 'R$' + ','.join(value)
else:
value = info.replace('R$', '').strip()
return 'R$' + value + ',00'
elif type_treating == 2:
sum_value = 0
for value in values:
number = float(value[ide].replace('R$', '').replace(',', '.'))
sum_value += number
return 'R$' + f'{sum_value:.2f}'.replace('.', ',')
elif type_treating == 3:
if ':' in info:
hour = info.split(':')
if hour[1] == '':
hour[1] = '00'
if hour[0] == '':
hour[0] = '00'
if len(hour[0]) == 1:
hour[0] = '0' + hour[0]
if hour[0] and hour[1] == '':
hour[0], hour[1] = '00'
return ':'.join(hour)
else:
if len(info) == 1:
info = '0' + info
return info + ':00'
elif type_treating == 4:
sum_value = 0
for value in values:
number = float(value.replace('R$', '').replace(',', '.'))
sum_value += number
return 'R$' + f'{sum_value:.2f}'.replace('.', ',')
elif type_treating == 5:
subtraction_value = float(values[0].replace('R$', '').replace(',', '.'))
for value in values[1:]:
number = float(value.replace('R$', '').replace(',', '.'))
subtraction_value -= number
return 'R$' + f'{subtraction_value:.2f}'.replace('.', ',')
elif type_treating == 6:
sum_value = 0
for value in values:
number = float(value.replace('R$', '').replace(',', '.'))
sum_value += number
return int(sum_value)
elif type_treating == 7:
number = float(info.replace('R$', '').replace(',', '.'))
return number
elif type_treating == 8:
phone = info.get().replace(' ', '').replace('-', '').replace('(', '').replace(')', '')
phoneFormated = ''
if len(info.get()) == 9:
phoneFormated = f'(77) {phone[0:5]}-{phone[5:]}'
if len(info.get()) >= 11:
phoneFormated = f'({phone[0:2]}) {phone[2:7]}-{phone[7:]}'
info.delete(0, END)
info.insert(0, phoneFormated)
elif type_treating == 9:
phone = info.get().replace(' ', '').replace('-', '').replace('(', '').replace(')', '')
phoneFormated = ''
if len(info.get()) == 9:
phoneFormated = f'(77) {phone[0:5]}-{phone[5:]}'
if len(info.get()) >= 11:
phoneFormated = f'({phone[0:2]}) {phone[2:7]}-{phone[7:]}'
info.delete(0, END)
info.insert(0, phoneFormated)
elif type_treating == 10:
cpf = info.get().replace(' ', '').replace('-', '').replace('.', '')
cpfFormated = ''
if len(info.get()) == 11:
cpfFormated = f'{cpf[0:3]}.{cpf[3:6]}.{cpf[6:9]}-{cpf[9:]}'
else:
cpfFormated = info.get()
info.delete(0, END)
info.insert(0, cpfFormated)
elif type_treating == 11:
rg = info.get().replace(' ', '').replace('-', '').replace('.', '')
rgFormated = ''
if len(info.get()) == 9:
rgFormated = f'{rg[0:2]}.{rg[2:5]}.{rg[5:8]}-{rg[8]}'
else:
rgFormated = info.get()
info.delete(0, END)
info.insert(0, rgFormated)
def delete_informations_treeview(self, treeview, line_color):
for linhas in treeview.get_children():
treeview.delete(linhas)
self.lineTreeviewColor[line_color] = 0
def completing_payment_informations(self, type_complet='default'):
if type_complet == 'default' and self.customScheduleEntry.get() != '':
# searching plan ====================
plan = self.dataBases['informations'].searchDatabase(f'SELECT plano FROM Alunos WHERE nome = "{self.customScheduleEntry.get()}"')
# searching price of plan ==============
if plan:
price = self.dataBases['informations'].searchDatabase(f'SELECT valor FROM Planos WHERE plano = "{plan[0][0]}"')
# inserting informations ============
if price:
self.planScheduleEntry.set(plan[0][0])
self.valueScheduleEntry.delete(0, END)
self.valueScheduleEntry.insert(0, price[0][0])
else:
self.planScheduleEntry.set('')
self.valueScheduleEntry.delete(0, END)
elif self.planScheduleEntry.get() != '':
price = self.dataBases['informations'].searchDatabase(f'SELECT valor FROM Planos WHERE plano = "{self.planScheduleEntry.get()}"')
if price:
self.valueScheduleEntry.delete(0, END)
self.valueScheduleEntry.insert(0, price[0][0])
else:
self.valueScheduleEntry.delete(0, END)
def completing_sale_informations(self):
price = self.dataBases['informations'].searchDatabase(f'SELECT valor_de_venda FROM Produtos WHERE nome = "{self.productSaleEntry.get()}"')
if price:
self.valueSaleEntry.delete(0, END)
self.valueSaleEntry.insert(0, price[0][0])
else:
self.valueSaleEntry.delete(0, END)
@staticmethod
def message_window(typem=1, titlein='', messagein=''):
if typem == 1:
messagebox.showinfo(title=titlein, message=messagein)
elif typem == 2:
messagebox.showwarning(title=titlein, message=messagein)
elif typem == 3:
messagebox.showerror(title=titlein, message=messagein)
elif typem == 4:
question = messagebox.askyesno(title=titlein, message=messagein)
return question
def insert_informations_entrys(self, entrys, treeview=None, insert=True, type_insert='normal', table='', photo=None, size=(170, 200), data_base='informations'):
match type_insert:
case 'normal':
# deleting informations of entrys ===============================
for entry in entrys:
if isinstance(entry, CTkComboBox):
entry.set('')
else:
entry.delete(0, END)
# cheking if there is information in the treeview ================================
if insert:
if treeview.selection():
for index, information in enumerate(self.selection_treeview(treeview)[0][1:]):
if isinstance(entrys[index], CTkComboBox):
entrys[index].set(information)
else:
entrys[index].insert(0, information)
if entrys[index] == self.passwordEntry:
entrys[index].delete(0, END)
case 'advanced':
# deleting informations of entrys ===============================
for entry in entrys:
if isinstance(entry, CTkComboBox) or isinstance(entry, StringVar):
entry.set('')
elif isinstance(entry, CTkLabel):
self.pick_picture(entry, photo, 'unknow')
elif isinstance(entry, CTkTextbox):
entry.delete('0.0', END)
elif isinstance(entry, CTkEntry):
entry.configure(state='normal', fg_color='#ffffff')
entry.delete(0, END)
else:
entry.delete(0, END)
if insert:
# cheking if there is information in the treeview ================================
if treeview.selection():
informations = self.selection_treeview(treeview)[0]
# case informations is of cash day
if 'R$' in informations[3]:
informations = informations[0:7] + informations[11:14] + ('', '', '')
for index, information in enumerate(informations[1:]):
if isinstance(entrys[index], CTkComboBox) or isinstance(entrys[index], StringVar):
entrys[index].set(information.capitalize() if isinstance(entrys[index], StringVar) else information)
elif isinstance(entrys[index], CTkLabel):
self.pick_picture(entrys[index], photo, 'toggle', self.dataBases[data_base].searchDatabase(f'SELECT foto FROM {table} WHERE ID = {informations[0]}')[0][0], size=size)
elif isinstance(entrys[index], CTkTextbox):
entrys[index].insert('0.0', self.dataBases[data_base].searchDatabase(f'SELECT observação FROM {table} WHERE ID = {informations[0]}')[0][0])
else:
entrys[index].insert(0, information)
def delete_information(self, treeview, type_information, table):
# pick up selection for delete information =============================
if ask := self.message_window(4, 'Comfimação', 'Você tem certeza de que deseja deletar o(s) item(s) selecionado(s)'):
for selection in self.selection_treeview(treeview):
self.dataBases[type_information].crud(deleteInformation.format(table, selection[0]))
# update information of payment =================================
if treeview == self.treeviewSchedule and selection[6] == datetime.now().strftime('%m/%Y'):
self.dataBases['informations'].crud(f'UPDATE Alunos SET observação = "Mensalidade em aberto" WHERE nome = "{selection[1]}"')
if len(self.dataBases[type_information].searchDatabase(searchAll.format(table))) == 0:
self.dataBases[type_information].crud(f"DELETE FROM sqlite_sequence WHERE name='{table}'")
return ask
@staticmethod
def create_pdf(treeview, elements):
saveDirectory = filedialog.asksaveasfilename(defaultextension="*.pdf ", filetypes=[('Arquivos de pdf', "*.pdf")])
if saveDirectory != '':
# creating documents ============================================
document = SimpleDocTemplate(saveDirectory, pagesize=A4)
# insert elements in documents ==================================
content = []
for element in elements:
content.append(element)
document.build(elements)
return saveDirectory
def create_record(self, informations):
saveDirectory = filedialog.askdirectory()
if saveDirectory != '':
# pick document of origin
tokenOfStudent = Document('documents/ficha_do_aluno.docx')
if len(informations) > 0:
for information in informations:
# insert elements in references ==================================
index = 1
for key in references:
references[key] = information[index]
index += 1
# replacement itens =========================
for paragraph in tokenOfStudent.paragraphs:
for key, value in references.items():
paragraph.style.font.name = 'Arial'
paragraph.style.font.size = Pt(12)
if key in paragraph.text:
paragraph.text = paragraph.text.replace(key, value)
# saving ========================
tokenOfStudent.save(saveDirectory + f'/{information[1]}.docx')
self.message_window(1, 'Concluído', messagein=f'Os arquivos foram salvos em "{saveDirectory}"')
else:
# insert elements in references ==================================
for key in references:
if key in ['pmpmpm', 'amamam', 'pcpcpc', 'sdsdsd', 'jojojo', 'lclclc', 'sss']:
references[key] = '_' * 6
elif key in ['cicici', 'eseses']:
references[key] = '_' * 20
else:
references[key] = '_' * 47
# replacement itens =========================
for paragraph in tokenOfStudent.paragraphs:
paragraph.style.font.name = 'Arial'
paragraph.style.font.size = Pt(12)
for key, value in references.items():
if key in paragraph.text:
paragraph.text = paragraph.text.replace(key, value)
# saving ========================
tokenOfStudent.save(saveDirectory + f'/ficha_do_aluno.docx')
self.message_window(1, 'Concluído', messagein=f'Os arquivos foram salvos em "{saveDirectory}"')
def send_message_payments(self, treeview):
res = messagebox.askyesno('Enviar Mensagem?', message=f'Certeza que quer mandar as mensagens?')
if res:
messagebox.showwarning(title='Alerta', message='Não mexa no notebook até terminar. Para cancelar o envio das mensagens, leve o cursor do mouse para a parte superior esquerda da tela')
self.active_monthly_payments(treeview)
clientsSelection = self.selection_treeview(treeview)
if len(clientsSelection) > 0:
self.bot.open_whatsapp()
self.bot.pause('assets/espera.jpg')
self.bot.whatsapp(clientsSelection)
messagebox.showinfo(title='Concluido', message='Mensagens enviadas.')
else:
messagebox.showinfo(title='Erro', message='Não existe mensagens a serem enviadas.')
@staticmethod
def image(file, size):
try:
if 'icon_no_picture.png' in file or 'icon_barCode.png' in file or 'icon_product.png' in file:
size = (76, 76)
img = CTkImage(light_image=Image.open(file), dark_image=Image.open(file), size=size)
except FileNotFoundError:
img = CTkImage(light_image=Image.open('assets/corrupted.png'), dark_image=Image.open('assets/corrupted.png'), size=(76, 76))
return [img, file]
def active_monthly_payments(self, treeview):
self.search_student(treeview, type_search='all', save_seacrh=False)
# excluing selections ================
for item in treeview.selection():
treeview.selection_remove(item)
# add selections ================
for student in treeview.get_children():
last_date = re.findall(date_pattern, treeview.set(student, "observação"))
if last_date:
if datetime.today().strftime('%m/%Y') != last_date[0]:
treeview.selection_add(student)
else:
if treeview.set(student, "observação") != 'Plano sem custos':
treeview.selection_add(student)
def pick_picture(self, label, photo, type_photo='new', directory='', size=None):
# pick directory of photo ======================================
match type_photo:
case 'new':
fileName = filedialog.askopenfilename()
if fileName:
self.photosAndIcons[photo] = self.image(fileName, (170, 200))
label.configure(image=self.photosAndIcons[photo][0])
case 'toggle':
self.photosAndIcons[photo] = self.image(directory, size)
label.configure(image=self.photosAndIcons[photo][0])
case 'unknow':
if photo in ['employee', 'costumer']:
self.photosAndIcons[photo] = self.image(f'assets/icon_no_picture.png', (76, 76))
elif photo == 'barCode':
self.photosAndIcons[photo] = self.image(f'assets/icon_barCode.png', (76, 76))
elif photo in ['productUse', 'productSale', 'productUseUnusable', 'productSaleSold']:
self.photosAndIcons[photo] = self.image(f'assets/icon_product.png', (76, 76))
label.configure(image=self.photosAndIcons[photo][0])
case 'logo':
fileName = filedialog.askopenfilename()
if fileName:
if '.png' in fileName.lower():
label.configure(image=self.image(fileName, (500, 500))[0])
self.dataBases['config'].crud(f'UPDATE Logo SET arquivo="{fileName}"')
else:
self.message_window(3, 'Formato incorreto', 'Use uma imagem em formato PNG')
@staticmethod
def searching_list(first, quantity, column, insert=False, index=0, information=''):
# create list of informations ===============================
listSearch = [first]
listSearch.extend([''] * quantity)
listSearch.append(column)
if insert:
listSearch.insert(index, information)
return listSearch
def encode_for_searching(self, information):
if information == '':
return information
else:
return self.criptography.encode(information)
def decode_informations_database(self, informations):
# decoding informations ================================
informationsDecode = []
for information in informations:
informationsDecode.append(
(
information[0], self.criptography.decode(information[1][2:-1]), self.criptography.decode(information[2][2:-1]), self.criptography.decode(information[3][2:-1]),
self.criptography.decode(information[4][2:-1]), self.criptography.decode(information[5][2:-1]), self.criptography.decode(information[6][2:-1]), self.criptography.decode(information[7][2:-1]),
self.criptography.decode(information[8][2:-1]), self.criptography.decode(information[9][2:-1]), self.criptography.decode(information[10][2:-1]), self.criptography.decode(information[11][2:-1]),
information[11].upper(), information[13].upper()
)
)
return informationsDecode
class FunctionsOfSchedule(GeneralFunctions):
def register_scheduling(self, informations, treeview, entrys=None):
# analising plan ==============================
price = self.dataBases['informations'].searchDatabase(f'SELECT valor FROM Planos WHERE plano = "{informations[1]}"')[0][0] if self.dataBases['informations'].searchDatabase(f'SELECT valor FROM Planos WHERE plano = "{informations[1]}"') else '0'
price = self.treating_numbers(price, 7)
# informations of treeview ====================
if self.validation(informations[0:4], 5) and self.validation(self.treating_numbers(informations[2], 1), 9) and self.validation(informations[4], 3) and self.validation(informations[4], 10) and price != 0:
if self.message_window(4, 'Comfimação', 'Você tem certeza de que deseja finalizar o(s) agendamento(s)'):
self.dataBases['payments'].crud(
registerScheduling.format(
informations[0].title(),
informations[1],
self.treating_numbers(informations[2], 1),
informations[3],
datetime.today().strftime('%d/%m/%Y') if informations[4] == '' else informations[4],
datetime.today().strftime('%m/%Y')
))
self.search_schedule(treeview, informations, 'last', save_seacrh=False)
# anoting payment ================
self.dataBases['informations'].crud(f'UPDATE Alunos SET observação = "Mensalidade paga:\n{datetime.today().strftime("%m/%Y")}" WHERE nome = "{informations[0].title()}"')
self.message_window(1, 'Concluído', messagein=f'Agendamento(s) feito com sucesso')
else:
if price == 0 and informations[1] != '':
self.message_window(2, 'Aviso', f'"{informations[1]}" é um plano sem custos')
else:
self.message_window(3, 'Erro', 'Verifique se os campos estão preenchidos ou corretos')
def register_sale(self, informations, treeview, entrys=None):
quantity = self.dataBases['informations'].searchDatabase(f'SELECT ID, quantidade_em_estoque FROM Produtos WHERE nome LIKE "%{informations[1]}%"')
if quantity:
if int(quantity[0][1]) > 0:
# informations of treeview ====================
if self.validation(informations, 5) and self.validation(self.treating_numbers(informations[2], 1), 9) and self.validation(informations[4], 3) and self.validation(informations[4], 10):
if self.message_window(4, 'Comfimação', 'Você tem certeza de que deseja finalizar a venda?'):
self.dataBases['payments'].crud(
registerSale.format(
informations[0].title(),
informations[1],
self.treating_numbers(informations[2], 1),
informations[3],
datetime.today().strftime('%d/%m/%Y') if informations[4] == '' else informations[4],
))
# finalizing ===========================
self.dataBases['informations'].crud(f'UPDATE Produtos SET quantidade_em_estoque = "{int(quantity[0][1]) - 1}" WHERE ID = {quantity[0][0]}')
self.search_stock(self.treeviewStockControl, self.searching_list('', 10, 'nome'))
self.search_sale(treeview, informations, 'last', save_seacrh=False)
self.message_window(1, 'Concluído', messagein=f'Venda feita com sucesso')
else:
self.message_window(3, 'Erro', 'Verifique se os campos estão preenchidos ou corretos')
else:
self.message_window(2, 'Sem', 'Este produto está em falta no estoque')
else:
self.message_window(2, 'Sem', 'Este produto não está cadastrado no estoque')
def search_schedule(self, treeview=None, informations=None, type_search='new', save_seacrh=True, insert=True):
# save last search ============================================
if save_seacrh:
self.lastSearch['payments'] = searchSchedule.format(
'ID' if informations[0].isnumeric() else 'aluno',
informations[0],
informations[1],
informations[2],
informations[3],
informations[4],
informations[5],
informations[6].replace(' ', '_').lower()
)
# pick up informations =========================================
informationsDataBase = []
match type_search:
case 'new':
informationsDataBase = self.dataBases['payments'].searchDatabase(
searchSchedule.format(
'ID' if informations[0].isnumeric() else 'aluno',
informations[0],
informations[1],
informations[2],
informations[3],
informations[4],
informations[5],
informations[6].replace(' ', '_').lower()
)
)
case 'last':
informationsDataBase = self.dataBases['payments'].searchDatabase(self.lastSearch['payments'])
case 'all':
informationsDataBase = self.dataBases['payments'].searchDatabase(searchAll.format('Pagamentos'))
if insert:
# deleting and inserting informations in treeview ===============================
self.delete_informations_treeview(treeview, 'payments')
self.insert_treeview_informations(treeview, informationsDataBase, 'payments')
else:
return informationsDataBase
def search_sale(self, treeview=None, informations=None, type_search='new', save_seacrh=True, insert=True):
# save last search ============================================
if save_seacrh:
self.lastSearch['sale'] = searchSale.format(
'ID' if informations[0].isnumeric() else 'cliente',
informations[0],
informations[1],
informations[2],
informations[3],
informations[4],
informations[5].replace(' ', '_').lower()
)
# pick up informations =========================================
informationsDataBase = []
match type_search:
case 'new':
informationsDataBase = self.dataBases['payments'].searchDatabase(
searchSale.format(
'ID' if informations[0].isnumeric() else 'cliente',
informations[0],
informations[1],
informations[2],
informations[3],
informations[4],
informations[5].replace(' ', '_').lower()
)
)
case 'last':
informationsDataBase = self.dataBases['payments'].searchDatabase(self.lastSearch['sale'])
case 'all':
informationsDataBase = self.dataBases['payments'].searchDatabase(searchAll.format('Vendas'))
if insert:
# deleting and inserting informations in treeview ===============================
self.delete_informations_treeview(treeview, 'sale')
self.insert_treeview_informations(treeview, informationsDataBase, 'sale')
else:
return informationsDataBase
def update_schedule(self, treeview, informations, entrys):
# analising plan ==============================
price = self.dataBases['informations'].searchDatabase(f'SELECT valor FROM Planos WHERE plano = "{informations[1]}"')[0][0]
price = self.treating_numbers(price, 7)
# update informations =========================================
if self.validation(informations[0:4], 5) and self.validation(self.treating_numbers(informations[2], 1), 9) and self.validation(informations[4], 3) and self.validation(informations[4], 10) and price != 0:
if treeview.selection():
self.dataBases['payments'].crud(
updateSchedule.format(
informations[0].title(),
informations[1],
self.treating_numbers(informations[2], 1),
informations[3],
informations[4],
informations[5],
self.selection_treeview(treeview)[0][0]
)
)
# delete informations of treeview ==============================
self.delete_informations_treeview(treeview, 'payments')
# insert informations in treeview ===============================
self.search_schedule(treeview, informations, 'last', save_seacrh=False)
# show message of concluded
self.message_window(1, 'Concluído', messagein=f'Pagamento(s) atualizado(s) com sucesso')
else:
self.message_window(3, 'Sem seleção', 'Selecione algum item na lista para atualizar')
else:
if price == 0:
self.message_window(2, 'Aviso', f'"{informations[1]}" é um plano sem custos')
else:
self.message_window(3, 'Erro', 'Verifique se os campos estão preenchidos ou corretos')
def update_sale(self, treeview, informations, entrys):
# update informations =========================================
if self.validation(informations, 5) and self.validation(self.treating_numbers(informations[2], 1), 9) and self.validation(informations[4], 3) and self.validation(informations[4], 10):
if treeview.selection():
self.dataBases['payments'].crud(
updateSale.format(
informations[0].title(),
informations[1],
self.treating_numbers(informations[2], 1),
informations[3],
informations[4],
self.selection_treeview(treeview)[0][0]
)
)
# finalizing ===========================
quantity = self.dataBases['informations'].searchDatabase(f'SELECT ID, quantidade_em_estoque FROM Produtos WHERE nome LIKE "%{informations[1]}%"')
if quantity:
if informations[1] != self.selection_treeview(treeview)[0][2]:
self.dataBases['informations'].crud(f'UPDATE Produtos SET quantidade_em_estoque = "{int(quantity[0][1]) - 1}" WHERE ID = {quantity[0][0]}')
quantity = self.dataBases['informations'].searchDatabase(f'SELECT ID, quantidade_em_estoque FROM Produtos WHERE nome LIKE "%{self.selection_treeview(treeview)[0][2]}%"')
self.dataBases['informations'].crud(f'UPDATE Produtos SET quantidade_em_estoque = "{int(quantity[0][1]) + 1}" WHERE ID = {quantity[0][0]}')
self.search_stock(self.treeviewStockControl, self.searching_list('', 10, 'nome'))
# delete informations of treeview ==============================
self.delete_informations_treeview(treeview, 'sale')
# insert informations in treeview ===============================
self.search_sale(treeview, informations, 'last', save_seacrh=False)
# show message of concluded
self.message_window(1, 'Concluído', messagein=f'Pagamento(s) atualizado(s) com sucesso')
else:
self.message_window(3, 'Sem seleção', 'Selecione algum item na lista para atualizar')
else:
self.message_window(3, 'Erro', 'Verifique se os campos estão preenchidos ou corretos')
def delete_schedule(self, treeview):
if treeview.selection():
# deleting inforations =======================================
delete = self.delete_information(treeview, 'payments', 'Pagamentos')
if delete:
# delete informations of treeview ==============================
self.delete_informations_treeview(treeview, 'payments')
# insert informations in treeview ===============================
self.search_schedule(treeview, type_search='last', save_seacrh=False)
# shoe message of concluded
self.message_window(1, 'Concluído', messagein=f'agendamento(s) deletado(s) com sucesso')
else:
self.message_window(3, 'Sem seleção', 'Selecione algum item na lista para deletar')
def delete_sale(self, treeview):
if treeview.selection():
# deleting inforations =======================================
delete = self.delete_information(treeview, 'payments', 'Vendas')
if delete:
# delete informations of treeview ==============================
self.delete_informations_treeview(treeview, 'sale')
# insert informations in treeview ===============================
self.search_sale(treeview, type_search='last', save_seacrh=False)
# shoe message of concluded
self.message_window(1, 'Concluído', messagein=f'agendamento(s) deletado(s) com sucesso')
else:
self.message_window(3, 'Sem seleção', 'Selecione algum item na lista para deletar')
def create_pdf_schedule(self, treeview):
informationsTreeview = self.pick_informations_treeview(treeview)
if informationsTreeview:
# Collecting informations for messege===============================
amountClients = len(informationsTreeview)
sumValue = self.treating_numbers(type_treating=2, values=informationsTreeview, ide=3)
methoPay = {
'card': [row for row in informationsTreeview if row[4] in ['CARTÃO', 'CARTAO']],
'money': [row for row in informationsTreeview if row[4] in ['DINHEIRO']],
'transfer': [row for row in informationsTreeview if row[4] in ['TRANSFERÊNCIA', 'TRANSFERENCIA']],
'note': [row for row in informationsTreeview if row[4] in ['NOTA', 'FIADO', 'NOTINHA']],
'notPay': [row for row in informationsTreeview if row[4] in ['NÃO FOI PAGO', 'SEM PAGAMENTO', 'NÃO PAGO', '']],
}
sumMetohdPay = [
amountClients,
self.treating_numbers(type_treating=2, values=methoPay["card"], ide=3),
self.treating_numbers(type_treating=2, values=methoPay["money"], ide=3),
self.treating_numbers(type_treating=2, values=methoPay["transfer"], ide=3),
self.treating_numbers(type_treating=2, values=methoPay["note"], ide=3),
self.treating_numbers(type_treating=2, values=methoPay["notPay"], ide=3),
sumValue
]
# informations ============================================
if treeview == self.treeviewSchedule:
for information in informationsTreeview:
tableWithInformationsScheduleTreeview.append(information)
table1 = Table(tableWithInformationsScheduleTreeview)
table1.setStyle(TableStyle(styleTableInformationsTreeview))
else:
for information in informationsTreeview:
tableWithInformationsSaleTreeview.append(information)
table1 = Table(tableWithInformationsSaleTreeview)
table1.setStyle(TableStyle(styleTableInformationsTreeview))
tableWithInformationsComplementarySchedule.append(sumMetohdPay)
# create tables ===========================================
table2 = Table(tableWithInformationsComplementarySchedule)
table2.setStyle(TableStyle(styleTableInformationsComplementary))
# reseting tables =========================================
if treeview == self.treeviewSchedule:
del tableWithInformationsScheduleTreeview[2:]
else:
del tableWithInformationsSaleTreeview[2:]
del tableWithInformationsComplementarySchedule[2:]
# creating pdf ============================================
saveDirectory = self.create_pdf(treeview, [table1, table2])
if saveDirectory is not None:
self.message_window(1, 'Concluído', messagein=f'O arquivo foi salvo em "{saveDirectory}"')
else:
self.message_window(2, 'Sem registro', 'A tabela esta vazia')
def message_informations_schedule(self, treeview):
if informationsTreeview := self.pick_informations_treeview(treeview):
# Collecting informations for messege===============================
amountClients = len(informationsTreeview)
sumValues = self.treating_numbers(type_treating=2, values=informationsTreeview, ide=3)
methoPay = {
'card': [row for row in informationsTreeview if row[4] in ['CARTÃO', 'CARTAO']],
'money': [row for row in informationsTreeview if row[4] in ['DINHEIRO']],
'transfer': [row for row in informationsTreeview if row[4] in ['TRANSFERÊNCIA', 'TRANSFERENCIA']],
'note': [row for row in informationsTreeview if row[4] in ['NOTA', 'FIADO', 'NOTINHA']],
'notPay': [row for row in informationsTreeview if row[4] in ['NÃO FOI PAGO', 'SEM PAGAMENTO', 'NÃO PAGO', '']],
}
# shoe menssege ================================================
self.message_window(
1,
'Informações sobre a tabela',
f'Total de {"alunos" if treeview == self.treeviewSchedule else "vendas"} = {amountClients}\n'
f'Total em cartão = {self.treating_numbers(type_treating=2, values=methoPay["card"], ide=3)}\n'
f'Total em dinheiro = {self.treating_numbers(type_treating=2, values=methoPay["money"], ide=3)}\n'
f'Total em tranferència = {self.treating_numbers(type_treating=2, values=methoPay["transfer"], ide=3)}\n'
f'Total em nota = {self.treating_numbers(type_treating=2, values=methoPay["note"], ide=3)}\n'
f'Total não pago = {self.treating_numbers(type_treating=2, values=methoPay["notPay"], ide=3)}\n'
f'Total recebido = {sumValues}'
)
else:
self.message_window(2, 'Sem registro', 'A tabela esta vazia')
class FunctionsOfStudentInformations(GeneralFunctions):
def register_student(self, informations, treeview):
if self.validation(informations[0:28], 5) and self.validation([informations[1], informations[2], informations[3], informations[5], informations[6], informations[7], informations[9]], 7) and self.validation(informations[3], 10):
if self.message_window(4, 'Comfimação', f'Finalisar o cadastro de {informations[0].title()}?'):
# analising plan ==============================
price = self.dataBases['informations'].searchDatabase(f'SELECT valor FROM Planos WHERE plano = "{informations[14]}"')[0][0]
price = self.treating_numbers(price, 7)
# informations of treeview ====================
self.dataBases['informations'].crud(
registerStudent.format(
informations[0].title(),
informations[1],
informations[2],
informations[3],
informations[4].title(),
informations[5],
informations[6],
informations[7],
informations[8],
informations[9],
informations[10],
informations[11],
informations[12],
informations[13],
informations[14],
informations[15],
informations[16],
informations[17],
informations[18],
informations[19],
informations[20],
informations[21],
informations[22],
informations[23],
informations[24],
informations[25],
informations[26],
informations[27],
informations[28],
'Mensalidade em aberto' if price != 0 else "Plano sem custos"
)
)
# deleting and inserting informations in treeview ===============================
self.search_student(treeview, informations, 'all', save_seacrh=False)
# refresh =======================================================
self.refresh_combobox_student()
else:
self.message_window(3, 'Erro', 'Verifique se os campos estão preenchidos ou corretos')
def search_student(self, treeview=None, informations=None, type_search='new', save_seacrh=True, insert=True):
# save last search ============================================
if save_seacrh:
self.lastSearch['student'] = searchStudent.format(
'ID' if informations[0].isnumeric() else 'nome',
informations[0].title(),
informations[1],
informations[2],
informations[3],
informations[4].title(),
informations[5],
informations[6],
informations[7],
informations[8],
informations[9],
informations[10],
informations[11],
informations[12],
informations[13],
informations[14],
informations[15],
informations[16],
informations[17],
informations[18],
informations[19],
informations[20],
informations[21],
informations[22],
informations[23],
informations[24],
informations[25],
informations[26],
informations[27],
informations[30].replace(' ', '_')
)
# pick up informations =========================================
informationsDatabase = []
match type_search:
case 'new':
informationsDatabase = self.dataBases['informations'].searchDatabase(
searchStudent.format(
'ID' if informations[0].isnumeric() else 'nome',
informations[0].title(),
informations[1],
informations[2],
informations[3],
informations[4].title(),
informations[5],
informations[6],
informations[7],
informations[8],
informations[9],
informations[10],
informations[11],
informations[12],
informations[13],
informations[14],
informations[15],
informations[16],
informations[17],
informations[18],
informations[19],
informations[20],
informations[21],
informations[22],
informations[23],
informations[24],
informations[25],
informations[26],
informations[27],
informations[30].replace(' ', '_')
)
)
case 'last':
informationsDatabase = self.dataBases['informations'].searchDatabase(self.lastSearch['student'])
case 'all':
informationsDatabase = self.dataBases['informations'].searchDatabase(searchAll.format('Alunos'))
if insert:
# deleting and inserting informations in treeview ===============================
self.delete_informations_treeview(treeview, 'student')
self.insert_treeview_informations(treeview, informationsDatabase, 'student')
else:
return informationsDatabase
def update_student(self, treeview, informations, entrys):
# analising plan ==============================
price = self.dataBases['informations'].searchDatabase(f'SELECT valor FROM Planos WHERE plano = "{informations[14]}"')[0][0]
price = self.treating_numbers(price, 7)
# update informations =========================================
if treeview.selection():
if self.validation(informations[0:28], 5) and self.validation([informations[1], informations[2], informations[3], informations[5], informations[6], informations[7], informations[9]], 7) and self.validation(informations[3], 10):
informationsDataBase = self.dataBases['informations'].crud(
updateStudent.format(
informations[0].title(),
informations[1],
informations[2],