-
Notifications
You must be signed in to change notification settings - Fork 0
/
JARS_4-3-0
10533 lines (10199 loc) · 624 KB
/
JARS_4-3-0
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 packages
from tkinter import ttk
import sqlite3
import configparser
import glob
import pyperclip as pc
import re
import sys
import time
import numpy as np
import random
import os
import warnings
import tkinter as tk
import pandas as pd
import xlsxwriter
import shutil
import math
from subprocess import call
import ctypes
import datetime
from os import path, sep, remove
from time import sleep
from random import randint
from tkinter.ttk import *
from plotnine import *
from tkinter import *
from pathlib import Path
from functools import reduce
from statistics import mean
from tkinter import Tk
from PIL import Image
from shutil import move, rmtree
from tkinter import filedialog
# import ttkthemes
from warnings import filterwarnings
from tkinter.filedialog import askopenfilename
import statsmodels.tsa.statespace._filters
import statsmodels.tsa.statespace._filters._conventional
import statsmodels.tsa.statespace._filters._univariate
import statsmodels.tsa.statespace._filters._univariate_diffuse
import statsmodels.tsa.statespace._filters._inversions
import statsmodels.tsa.statespace._smoothers
import statsmodels.tsa.statespace._smoothers._conventional
import statsmodels.tsa.statespace._smoothers._univariate
import statsmodels.tsa.statespace._smoothers._univariate_diffuse
import statsmodels.tsa.statespace._smoothers._classical
import statsmodels.tsa.statespace._smoothers._alternative
# pyinstaller --onefile --add-data "mc_icon.ico;." --add-data "jalogo_tall.png;." --add-data "jalogo_long.png;." --add-data "jars_logo_blue_1000f.png;." --add-data "jars_logo_oran_1000f.png;." --add-data "C:\Users\JSVAR\PycharmProjects\Language\venv\Lib\site-packages\pandas\io\formats\templates\html.tpl;." JARS_3-0-1.py
# pyinstaller --add-data "mc_icon.ico;." --add-data "jalogo_tall.png;." --add-data "jalogo_long.png;." --add-data "jars_logo_blue_1000f.png;." --add-data "jars_logo_oran_1000f.png;." --add-data "C:\Users\JSVAR\PycharmProjects\Language\venv\Lib\site-packages\pandas\io\formats\templates\html.tpl;." JARS_3-0-1.py
# pyinstaller JARS_4-2-3.spec
jars_apptitle = "Joseph Arnson's Reporting Suite v4.3.0"
apptitle = 'Distributor Scorecard v2.5.0'
datasearch_apptitle = 'DataSearch v1.6.6'
"""Utility Functions"""
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
def os_split_fixer(string: str):
"""Separate and rejoin selected file path with correct operating system separator"""
delimiters = '/', '\\'
maxsplit = 0
regexPattern = '|'.join(map(re.escape, delimiters))
splits = re.split(regexPattern, string, maxsplit)
splitlist = []
for split in splits:
splitlist.append(split + os.sep)
fspath = ''.join(splitlist)
splitpath = fspath[:-1]
return splitpath
def uniq_dir_maker(directoryname: str) -> list:
"""Create a unique directory at destination"""
# file destination select dialogue
Tk().withdraw() # prevent root window
# open file explorer folder select window
dirspath = filedialog.askdirectory(title='Select the output file save destination')
if not dirspath:
ctypes.windll.user32.MessageBoxW(0, 'Folder select cancelled.', 'Process Cancelled', 0)
return
# correct directory file path
dirsavepath = os_split_fixer(dirspath + os.sep + directoryname)
# try to create directory
try:
# create directory at destination without overwriting
Path(dirsavepath).mkdir(parents=True, exist_ok=False)
# if directory already exists add incremental integers until unique
except FileExistsError:
# create incrementing variable
i = 1
# determine incremented filename
while os.path.exists(f"{dirsavepath} ({str(i)})"):
i += 1
# update directory path with incremented variable
dirsavepath = dirsavepath + ' (' + str(i) + ')'
# create now unique directory
Path(dirsavepath).mkdir(parents=True, exist_ok=False)
# add os separator to new directory for saving
savepath = dirsavepath + os.sep
return [savepath, dirsavepath]
def conf_uniq_dir_maker(directoryname: str) -> list:
"""Create a unique directory at destination"""
# file destination select dialogue
Tk().withdraw() # prevent root window
# open file explorer folder select window
dirspath = filedialog.askdirectory(title='Select the output file save destination')
if not dirspath:
ctypes.windll.user32.MessageBoxW(0, 'Folder select cancelled.', 'Process Cancelled', 0)
return
# correct directory file path
dirsavepath = os_split_fixer(dirspath + os.sep + directoryname)
# try to create directory
try:
# create directory at destination without overwriting
Path(dirsavepath).mkdir(parents=True, exist_ok=False)
# if directory already exists add incremental integers until unique
except FileExistsError:
# create incrementing variable
i = 1
# determine incremented filename
while os.path.exists(f"{dirsavepath} ({str(i)})"):
i += 1
# update directory path with incremented variable
dirsavepath = dirsavepath + ' (' + str(i) + ')'
# create now unique directory
Path(dirsavepath).mkdir(parents=True, exist_ok=False)
# add os separator to new directory for saving
savepath = dirsavepath + os.sep
return [savepath, dirsavepath, dirspath]
def uniq_file_maker(file: str) -> str:
"""Create a unique file path"""
# get file name and extension
filename, filext = os.path.splitext(os.path.basename(file))
# get file directory path
directory = os.path.dirname(file)
# get file without extension only
filexx = os_split_fixer(directory + os.sep + filename)
# check if file exists
if Path(file).exists():
# create incrementing variable
i = 1
# determine incremented filename
while os.path.exists(f"{filexx} ({str(i)}){filext}"):
# update the incrementing variable
i += 1
# update file name with incremented variable
filename = directory + os.sep + filename + ' (' + str(i) + ')' + filext
# correct file path os separators
filename = os_split_fixer(filename)
else:
# pass original name if already unique
filename = file
return filename
def format_excel(writer, df: pd.DataFrame, sheet_name: str, table_name: str,
table_style: str = 'Table Style Medium 2', auto_filter: bool = True, total_row: bool = False):
"""Dynamically formats an Excel worksheet as a table using xlsxwriter"""
# reference the worksheet we need to update
worksheet = writer.sheets[sheet_name]
# collect the columns of the passed DataFrame
column_settings = [{'header': column} for column in df.columns]
# collect the shape of the passed DataFrame
max_row, max_col = df.shape
# apply table formatting to the shape of the DataFrame on the sheet
worksheet.add_table(0, 0, max_row, max_col - 1, {'name': table_name,
'style': table_style,
'autofilter': auto_filter,
'total_row': total_row,
'columns': column_settings})
# loop over the columns and change the width
for i, col in enumerate(df.columns):
# calculate column width for autosizing based on longest str in column
column_len = max(df[col].astype(str).str.len().max() + 2, len(col) + 2)
# format worksheet column
worksheet.set_column(i, i, column_len)
return
def get_timestamps() -> list:
"""Gets series of timestamps as well as week number and full date"""
# get timestamps
now = datetime.datetime.now()
week = datetime.datetime.today().isocalendar()[1]
hour = now.hour
tdate1 = now.today().strftime('%m-%d-%Y') # mm-dd-yyyy
tdate2 = now.today().strftime('%m/%d/%Y') # mm/dd/yyyy
# convert hour to AM or PM
if hour == 0:
hour = '12AM'
elif hour == 12:
hour = '12PM'
elif hour >= 13:
# subtract 12 hours to convert from 24H to 12H
hour -= 12
hour = str(hour) + 'PM'
else:
hour = str(hour) + 'AM'
# create full timestamp
full = f"{now.year}-{str(now.month).zfill(2)}-{str(now.day).zfill(2)}-{str(now.hour).zfill(2)}-" \
f"{str(now.minute).zfill(2)}-{str(now.second).zfill(2)}"
return [now.year, now.month, week, now.day, hour, now.minute, now.second, tdate1, tdate2, full]
def get_past_timestamps(time_obj: datetime) -> list:
"""Gets timestamps based on past historical date"""
# get timestamps
week = time_obj.isocalendar()[1]
hour = time_obj.hour
tdate1 = time_obj.today().strftime('%m-%d-%Y') # mm-dd-yyyy
tdate2 = time_obj.today().strftime('%m/%d/%Y') # mm/dd/yyyy
# convert hour to AM or PM
if hour == 0:
hour = '12AM'
elif hour == 12:
hour = '12PM'
elif hour >= 13:
# subtract 12 hours to convert from 24H to 12H
hour -= 12
hour = str(hour) + 'PM'
else:
hour = str(hour) + 'AM'
return [time_obj.year, time_obj.month, week, time_obj.day, hour, time_obj.minute, time_obj.second, tdate1, tdate2]
"""Picture Functions"""
def get_concat_v_resize(im1, im2, resample=Image.BICUBIC, resize_big_image=True):
if im1.width == im2.width:
_im1 = im1
_im2 = im2
elif (((im1.width > im2.width) and resize_big_image) or
((im1.width < im2.width) and not resize_big_image)):
_im1 = im1.resize((im2.width, int(im1.height * im2.width / im1.width)), resample=resample)
_im2 = im2
else:
_im1 = im1
_im2 = im2.resize((im1.width, int(im2.height * im1.width / im2.width)), resample=resample)
dst = Image.new('RGB', (_im1.width, _im1.height + _im2.height))
dst.paste(_im1, (0, 0))
dst.paste(_im2, (0, _im1.height))
return dst
def get_concat_h_resize(im1, im2, resample=Image.BICUBIC, resize_big_image=True):
if im1.height == im2.height:
_im1 = im1
_im2 = im2
elif (((im1.height > im2.height) and resize_big_image) or
((im1.height < im2.height) and not resize_big_image)):
_im1 = im1.resize((int(im1.width * im2.height / im1.height), im2.height), resample=resample)
_im2 = im2
else:
_im1 = im1
_im2 = im2.resize((int(im2.width * im1.height / im2.height), im1.height), resample=resample)
dst = Image.new('RGB', (_im1.width + _im2.width, _im1.height))
dst.paste(_im1, (0, 0))
dst.paste(_im2, (_im1.width, 0))
return dst
def get_concat_v_blank(im1, im2, color=(255, 255, 255)):
"""Concatenate two images vertically with a white margin"""
dst = Image.new('RGB', (max(im1.width, im2.width), im1.height + im2.height), color)
dst.paste(im1, (0, 0))
dst.paste(im2, (0, im1.height))
return dst
def get_concat_h_blank(im1, im2, color=(255, 255, 255)):
"""Concatenate two images horizontally with a white margin"""
dst = Image.new('RGB', (im1.width + im2.width, max(im1.height, im2.height)), color)
dst.paste(im1, (0, 0))
dst.paste(im2, (im1.width, 0))
return dst
"""DataSearch Functions"""
def uniq_ds_dir_maker(directoryname: str) -> list:
"""Create a unique directory at destination"""
# try to create directory
try:
# create directory at destination without overwriting
Path(directoryname).mkdir(parents=True, exist_ok=False)
# if directory already exists add incremental integers until unique
except FileExistsError:
# create incrementing variable
i = 1
# determine incremented filename
while os.path.exists(f"{directoryname} ({str(i)})"):
i += 1
# update directory path with incremented variable
directoryname = directoryname + ' (' + str(i) + ')'
# create now unique directory
Path(directoryname).mkdir(parents=True, exist_ok=False)
# add os separator to new directory for saving
savepath = directoryname + os.sep
return [savepath, directoryname]
def uniq_ds_file_maker(file: str) -> str:
"""Create a unique file path"""
# get file name and extension
filename, filext = os.path.splitext(os.path.basename(file))
# get file directory path
directory = os.path.dirname(file)
# get file without extension only
filexx = os_split_fixer(directory + os.sep + filename)
# check if file exists
if Path(file).exists():
# create incrementing variable
i = 1
# determine incremented filename
while os.path.exists(f"{filexx} ({str(i)}){filext}"):
# update the incrementing variable
i += 1
# update file name with incremented variable
filename = directory + os.sep + filename + ' (' + str(i) + ')' + filext
# correct file path os separators
filename = os_split_fixer(filename)
else:
# pass original name if already unique
filename = file
return filename
def ds_get_timestamps() -> list:
"""Gets series of timestamps as well as week number and full date"""
# get timestamps
now = datetime.datetime.now()
week = datetime.datetime.today().isocalendar()[1]
hour = now.hour
tdate1 = now.today().strftime('%m-%d-%Y') # mm-dd-yyyy
tdate2 = now.today().strftime('%m/%d/%Y') # mm/dd/yyyy
# convert hour to AM or PM
if hour == 0:
hour = '12AM'
elif hour == 12:
hour = '12PM'
elif hour >= 13:
# subtract 12 hours to convert from 24H to 12H
hour -= 12
hour = str(hour) + 'PM'
else:
hour = str(hour) + 'AM'
# create full timestamp
full = f"{now.year}-{now.month}-{now.day}-{str(now.hour).zfill(2)}-" \
f"{str(now.minute).zfill(2)}-{str(now.second).zfill(2)}"
return [now.year, now.month, week, now.day, hour, now.minute, now.second, tdate1, tdate2, full]
def ds_get_past_timestamps(time_obj: datetime) -> list:
"""Gets timestamps based on past historical date"""
# get timestamps
week = time_obj.isocalendar()[1]
hour = time_obj.hour
tdate1 = time_obj.today().strftime('%m-%d-%Y') # mm-dd-yyyy
tdate2 = time_obj.today().strftime('%m/%d/%Y') # mm/dd/yyyy
# weekdays as a tuple
weekdays_list = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
weekday = weekdays_list[time_obj.weekday()]
# convert hour to AM or PM
if hour == 0:
hour = '12AM'
elif hour == 12:
hour = '12PM'
elif hour >= 13:
# subtract 12 hours to convert from 24H to 12H
hour -= 12
hour = str(hour) + 'PM'
else:
hour = str(hour) + 'AM'
return [time_obj.year, time_obj.month, week, time_obj.day, hour,
time_obj.minute, time_obj.second, tdate1, tdate2, weekday]
def ds_format_excel(df: pd.DataFrame, sheet_name: str, table_name: str, table_style: str, auto_filter: bool, writer):
"""Dynamically formats an excel worksheet as a table using xlsxwriter"""
# reference the worksheet we need to update
worksheet = writer.sheets[sheet_name]
# collect the columns and shape of the passed DataFrame
column_settings = [{'header': column} for column in df.columns]
max_row, max_col = df.shape
# apply table formatting to the shape of the DataFrame on the sheet
worksheet.add_table(0, 0, max_row, max_col - 1, {'name': table_name, 'style': table_style,
'autofilter': auto_filter, 'columns': column_settings})
# loop over the columns and change the width
for i, col in enumerate(df.columns):
column_len = max(df[col].astype(str).str.len().max(), len(col) + 2)
worksheet.set_column(i, i, column_len)
return
def write_datasearch_ini():
"""Create INI configuration file to initialize DataSearch settings"""
if not os.path.isdir('DataSearch'):
# notify user that an error has occurred
ctypes.windll.user32.MessageBoxW(0,
'DataSearch has encountered a fatal error. Source files were either moved or deleted and cannot be found. Please restart DataSearch to continue.',
'Fatal Error Encountered', 0)
# close DataSearch
sys.exit(0)
# initialize configparser object
write_config = configparser.ConfigParser()
# add section
write_config.add_section('Products_Settings')
# set values for app settings
write_config.set('Products_Settings', 'plant', '1')
write_config.set('Products_Settings', 'osku', '1')
write_config.set('Products_Settings', 'msku', '1')
write_config.set('Products_Settings', 'segment', '1')
write_config.set('Products_Settings', 'description', '1')
write_config.set('Products_Settings', 'run_freq', '1')
write_config.set('Products_Settings', 'production', '1')
write_config.set('Products_Settings', 'shelf_life', '1')
write_config.set('Products_Settings', 'ship_policy', '1')
write_config.set('Products_Settings', 'bbl_conversion', '1')
write_config.set('Products_Settings', 'units_p_pallet', '1')
write_config.set('Products_Settings', 'search_stacking', '0')
write_config.set('Products_Settings', 'search_exact', '0')
# add section
write_config.add_section('Customers_Settings')
# set values for app settings
write_config.set('Customers_Settings', 'shipto', '1')
write_config.set('Customers_Settings', 'shipto_name', '1')
write_config.set('Customers_Settings', 'csa', '1')
write_config.set('Customers_Settings', 'state', '1')
write_config.set('Customers_Settings', 'state_code', '1')
write_config.set('Customers_Settings', 'district', '1')
write_config.set('Customers_Settings', 'city', '1')
write_config.set('Customers_Settings', 'postal_code', '1')
write_config.set('Customers_Settings', 'search_stacking', '0')
write_config.set('Customers_Settings', 'search_exact', '0')
# add section
write_config.add_section('Plants_Settings')
# set values for app settings
write_config.set('Plants_Settings', 'plant', '1')
write_config.set('Plants_Settings', 'plant_name', '1')
write_config.set('Plants_Settings', 'plant_address', '1')
write_config.set('Plants_Settings', 'plant_city', '1')
write_config.set('Plants_Settings', 'plant_type', '1')
write_config.set('Plants_Settings', 'search_stacking', '0')
write_config.set('Plants_Settings', 'search_exact', '0')
# add section
write_config.add_section('Copy_Settings')
# set values for app settings
write_config.set('Copy_Settings', 'delimiter', 'Space')
# create ini file object
cfgfile = open('DataSearch\\DataSearch.ini', 'w')
# write ini file
write_config.write(cfgfile)
# save and close ini file
cfgfile.close()
return
def get_datasearch_ini() -> list:
"""Get DataSearch INI configuration file settings details"""
# check file dependencies
datasearch_source_checker()
# initialize configparser object
read_config = configparser.ConfigParser()
# read ini file values
read_config.read('DataSearch\\DataSearch.ini')
# get values from config file
plant = read_config.get('Products_Settings', 'plant')
osku = read_config.get('Products_Settings', 'osku')
msku = read_config.get('Products_Settings', 'msku')
segment = read_config.get('Products_Settings', 'segment')
description = read_config.get('Products_Settings', 'description')
run_freq = read_config.get('Products_Settings', 'run_freq')
production = read_config.get('Products_Settings', 'production')
shelf_life = read_config.get('Products_Settings', 'shelf_life')
ship_policy = read_config.get('Products_Settings', 'ship_policy')
bbl_conversion = read_config.get('Products_Settings', 'bbl_conversion')
units_p_pallet = read_config.get('Products_Settings', 'units_p_pallet')
p_search_stacking = read_config.get('Products_Settings', 'search_stacking')
p_search_exact = read_config.get('Products_Settings', 'search_exact')
shipto = read_config.get('Customers_Settings', 'shipto')
shipto_name = read_config.get('Customers_Settings', 'shipto_name')
csa = read_config.get('Customers_Settings', 'csa')
state = read_config.get('Customers_Settings', 'state')
state_code = read_config.get('Customers_Settings', 'state_code')
district = read_config.get('Customers_Settings', 'district')
city = read_config.get('Customers_Settings', 'city')
postal_code = read_config.get('Customers_Settings', 'postal_code')
c_search_stacking = read_config.get('Customers_Settings', 'search_stacking')
c_search_exact = read_config.get('Customers_Settings', 'search_exact')
lplant = read_config.get('Plants_Settings', 'plant')
plant_name = read_config.get('Plants_Settings', 'plant_name')
plant_address = read_config.get('Plants_Settings', 'plant_address')
plant_city = read_config.get('Plants_Settings', 'plant_city')
plant_type = read_config.get('Plants_Settings', 'plant_type')
l_search_stacking = read_config.get('Plants_Settings', 'search_stacking')
l_search_exact = read_config.get('Plants_Settings', 'search_exact')
delimiter = read_config.get('Copy_Settings', 'delimiter')
# create list of results
datasearch_ini_list = [plant, osku, msku, segment, description, run_freq, production, shelf_life, ship_policy,
bbl_conversion, units_p_pallet, p_search_stacking, p_search_exact, shipto, shipto_name,
csa, state, state_code, district, city, postal_code, c_search_stacking, c_search_exact,
lplant, plant_name, plant_address, plant_city, plant_type, l_search_stacking,
l_search_exact, delimiter]
return datasearch_ini_list
def loud_update_datasearch_ini():
"""Create INI configuration file to initialize DataSearch settings"""
# check file dependencies
datasearch_source_checker()
# initialize configparser object
write_config = configparser.ConfigParser()
# add section
write_config.add_section('Products_Settings')
# set values for app settings
write_config.set('Products_Settings', 'plant', str(plant_intvar.get()))
write_config.set('Products_Settings', 'osku', str(osku_intvar.get()))
write_config.set('Products_Settings', 'msku', str(msku_intvar.get()))
write_config.set('Products_Settings', 'segment', str(segment_intvar.get()))
write_config.set('Products_Settings', 'description', str(description_intvar.get()))
write_config.set('Products_Settings', 'run_freq', str(run_freq_intvar.get()))
write_config.set('Products_Settings', 'production', str(production_intvar.get()))
write_config.set('Products_Settings', 'shelf_life', str(shelf_life_intvar.get()))
write_config.set('Products_Settings', 'ship_policy', str(ship_policy_intvar.get()))
write_config.set('Products_Settings', 'bbl_conversion', str(bbl_conversion_intvar.get()))
write_config.set('Products_Settings', 'units_p_pallet', str(units_p_pallet_intvar.get()))
write_config.set('Products_Settings', 'search_stacking', str(p_search_stacking_intvar.get()))
write_config.set('Products_Settings', 'search_exact', str(p_search_exact_intvar.get()))
# add section
write_config.add_section('Customers_Settings')
# set values for app settings
write_config.set('Customers_Settings', 'shipto', str(shipto_intvar.get()))
write_config.set('Customers_Settings', 'shipto_name', str(shipto_name_intvar.get()))
write_config.set('Customers_Settings', 'csa', str(csa_intvar.get()))
write_config.set('Customers_Settings', 'state', str(state_intvar.get()))
write_config.set('Customers_Settings', 'state_code', str(state_code_intvar.get()))
write_config.set('Customers_Settings', 'district', str(region_intvar.get()))
write_config.set('Customers_Settings', 'city', str(city_intvar.get()))
write_config.set('Customers_Settings', 'postal_code', str(postal_code_intvar.get()))
write_config.set('Customers_Settings', 'search_stacking', str(c_search_stacking_intvar.get()))
write_config.set('Customers_Settings', 'search_exact', str(c_search_exact_intvar.get()))
# add section
write_config.add_section('Plants_Settings')
# set values for app settings
write_config.set('Plants_Settings', 'plant', str(lplant_intvar.get()))
write_config.set('Plants_Settings', 'plant_name', str(plant_name_intvar.get()))
write_config.set('Plants_Settings', 'plant_address', str(plant_address_intvar.get()))
write_config.set('Plants_Settings', 'plant_city', str(plant_city_intvar.get()))
write_config.set('Plants_Settings', 'plant_type', str(plant_type_intvar.get()))
write_config.set('Plants_Settings', 'search_stacking', str(l_search_stacking_intvar.get()))
write_config.set('Plants_Settings', 'search_exact', str(l_search_exact_intvar.get()))
# add section
write_config.add_section('Copy_Settings')
# set values for app settings based on combobox
write_config.set('Copy_Settings', 'delimiter', str(delimiter_var.get()))
# create ini file object
cfgfile = open('DataSearch\\DataSearch.ini', 'w')
# write ini file
write_config.write(cfgfile)
# save and close ini file
cfgfile.close()
# notify user that settings have been updated successfully
ctypes.windll.user32.MessageBoxW(0,
'Your DataSearch settings have been updated successfully.',
'Settings Updated', 0)
return
def quiet_update_datasearch_ini():
"""Update INI configuration file to initialize DataSearch settings"""
# check file dependencies
datasearch_source_checker()
# initialize configparser object
write_config = configparser.ConfigParser()
# add section
write_config.add_section('Products_Settings')
# set values for app settings
write_config.set('Products_Settings', 'plant', str(plant_intvar.get()))
write_config.set('Products_Settings', 'osku', str(osku_intvar.get()))
write_config.set('Products_Settings', 'msku', str(msku_intvar.get()))
write_config.set('Products_Settings', 'segment', str(segment_intvar.get()))
write_config.set('Products_Settings', 'description', str(description_intvar.get()))
write_config.set('Products_Settings', 'run_freq', str(run_freq_intvar.get()))
write_config.set('Products_Settings', 'production', str(production_intvar.get()))
write_config.set('Products_Settings', 'shelf_life', str(shelf_life_intvar.get()))
write_config.set('Products_Settings', 'ship_policy', str(ship_policy_intvar.get()))
write_config.set('Products_Settings', 'bbl_conversion', str(bbl_conversion_intvar.get()))
write_config.set('Products_Settings', 'units_p_pallet', str(units_p_pallet_intvar.get()))
write_config.set('Products_Settings', 'search_stacking', str(p_search_stacking_intvar.get()))
write_config.set('Products_Settings', 'search_exact', str(p_search_exact_intvar.get()))
# add section
write_config.add_section('Customers_Settings')
# set values for app settings
write_config.set('Customers_Settings', 'shipto', str(shipto_intvar.get()))
write_config.set('Customers_Settings', 'shipto_name', str(shipto_name_intvar.get()))
write_config.set('Customers_Settings', 'csa', str(csa_intvar.get()))
write_config.set('Customers_Settings', 'state', str(state_intvar.get()))
write_config.set('Customers_Settings', 'state_code', str(state_code_intvar.get()))
write_config.set('Customers_Settings', 'district', str(region_intvar.get()))
write_config.set('Customers_Settings', 'city', str(city_intvar.get()))
write_config.set('Customers_Settings', 'postal_code', str(postal_code_intvar.get()))
write_config.set('Customers_Settings', 'search_stacking', str(c_search_stacking_intvar.get()))
write_config.set('Customers_Settings', 'search_exact', str(c_search_exact_intvar.get()))
# add section
write_config.add_section('Plants_Settings')
# set values for app settings
write_config.set('Plants_Settings', 'plant', str(lplant_intvar.get()))
write_config.set('Plants_Settings', 'plant_name', str(plant_name_intvar.get()))
write_config.set('Plants_Settings', 'plant_address', str(plant_address_intvar.get()))
write_config.set('Plants_Settings', 'plant_city', str(plant_city_intvar.get()))
write_config.set('Plants_Settings', 'plant_type', str(plant_type_intvar.get()))
write_config.set('Plants_Settings', 'search_stacking', str(l_search_stacking_intvar.get()))
write_config.set('Plants_Settings', 'search_exact', str(l_search_exact_intvar.get()))
# add section
write_config.add_section('Copy_Settings')
# set values for app settings based on combobox
write_config.set('Copy_Settings', 'delimiter', str(delimiter_var.get()))
# create ini file object
cfgfile = open('DataSearch\\DataSearch.ini', 'w')
# write ini file
write_config.write(cfgfile)
# save and close ini file
cfgfile.close()
# check if products_stack should be reset
if p_search_stacking_intvar.get() == 0:
# delete products_stack.db
unstack_products()
# reset treeview
query_products()
# check if customers_stack should be reset
if c_search_stacking_intvar.get() == 0:
# delete customers_stack.db
unstack_customers()
# reset treeview
query_customers()
# check if plants_stack should be reset
if l_search_stacking_intvar.get() == 0:
# delete customers_stack.db
unstack_plants()
# reset treeview
query_plants()
return
def datasearch_source_checker():
"""Check if all dependency files exist otherwise close the application"""
if not os.path.isdir('DataSearch') \
or not os.path.exists('DataSearch\\DataSearch.ini') \
or not os.path.exists('DataSearch\\products.db') \
or not os.path.exists('DataSearch\\customers.db') \
or not os.path.exists('DataSearch\\plants.db'):
# notify user that an error has occurred
ctypes.windll.user32.MessageBoxW(0,
'DataSearch has encountered a fatal error. Source files were either moved or deleted and cannot be found. Please restart DataSearch to continue.',
'Fatal Error Encountered', 0)
# close DataSearch
try:
# check if data window exists and destroy
if data.winfo_exists():
data.destroy()
except:
pass
return
def datasearch_import():
"""Initialize datasearch source data and create dependency files where necessary"""
# check if DataSearch directory does not exist
if not os.path.isdir('DataSearch'):
# create DataSearch directory
uniq_ds_dir_maker('DataSearch')
# check if initializing configuration file exists
if not os.path.exists('DataSearch\\DataSearch.ini'):
# create initializing configuration file
write_datasearch_ini()
# check if database files exists already
if not os.path.exists('DataSearch\\customers.db') \
or not os.path.exists('DataSearch\\products.db') \
or not os.path.exists('DataSearch\\plants.db'):
# loop until a file is selected or the user exits
while True:
# file destination select dialogue
Tk().withdraw() # prevent root window
# open file explorer folder select window
dirspath = askopenfilename(title='Select a DataSearch - Data Source file',
filetypes=[('Excel files', '.xlsx')])
if not dirspath:
ctypes.windll.user32.MessageBoxW(0, 'File select cancelled. Closing the application',
'Process Cancelled', 0)
# close the application
# sys.exit(0)
# break while loop
break
# return
try:
# create dataframes
df = pd.read_excel(dirspath, sheet_name='Product').fillna(0)
cf = pd.read_excel(dirspath, sheet_name='Customer').fillna('-')
lf = pd.read_excel(dirspath, sheet_name='Plant').fillna('-')
# reindex dataframes
df = df[['Plant', 'OSKU', 'MSKU', 'Segment', 'Description', 'Run_Freq',
'Production', 'Shelf_Life', 'Ship_Policy', 'BBL_Conversion', 'Units_p_Pallet']]
cf = cf[['ShipTo', 'ShipTo_Name', 'CSA', 'State', 'State_Code', 'Region', 'City', 'Postal_Code']]
lf = lf[['Plant', 'Plant_Name', 'Plant_Address', 'Plant_City', 'Plant_Type']]
# end while loop
break
# exit script if no dataframes were created
except UnboundLocalError:
ctypes.windll.user32.MessageBoxW(0,
'The file was loaded incorrectly. Please try again.',
'File Load Error', 0)
return False
# if file is currently open
except PermissionError:
ctypes.windll.user32.MessageBoxW(0,
'The file you have selected is locked by the user. Please close the file and try again.',
'File Locked', 0)
return False
# if dataframe is wrong
except (KeyError, ValueError, TypeError):
ctypes.windll.user32.MessageBoxW(0,
'Selected file has missing or incomplete data. Please select a new file and try again.',
'Incompatible File', 0)
return False
# if the dataframe is wrong for any reason
except:
ctypes.windll.user32.MessageBoxW(0,
'The selected file has missing or incomplete data. Please select a new file and try again.',
'Incompatible File', 0)
return False
try:
# format columns
df['Plant'] = df['Plant'].astype(int)
cf['Postal_Code'] = cf['Postal_Code'].astype(str)
# identify lines that are all blanks
cf['Remove'] = np.where((cf['ShipTo_Name'] == '-') & (cf['CSA'] == '-') & (cf['State'] == '-') &
(cf['State_Code'] == '-') & (cf['Region'] == '-') & (cf['City'] == '-') &
(cf['Postal_Code'] == '-'), 1, 0)
# only keep rows that have nonzero values
cf = cf[~(cf.Remove != 0)]
# create database objects
prod_conn1 = sqlite3.connect('DataSearch\\products.db')
cust_conn1 = sqlite3.connect('DataSearch\\customers.db')
plnt_conn1 = sqlite3.connect('DataSearch\\plants.db')
# create a cursor instances
pc1 = prod_conn1.cursor()
cc1 = cust_conn1.cursor()
lc1 = plnt_conn1.cursor()
# create tables
pc1.execute("""CREATE TABLE if not exists products (
Plant INTEGER,
OSKU INTEGER,
MSKU INTEGER,
Segment TEXT,
Description TEXT,
Run_Freq TEXT,
Production TEXT,
Shelf_Life INTEGER,
Ship_Policy INTEGER,
BBL_Conversion REAL,
Units_p_Pallet INTEGER)
""")
cc1.execute("""CREATE TABLE if not exists customers (
ShipTo INTEGER,
ShipTo_Name TEXT,
CSA TEXT,
State TEXT,
State_Code TEXT,
Region TEXT,
City TEXT,
Postal_Code TEXT)
""")
lc1.execute("""CREATE TABLE if not exists plants (
Plant INTEGER,
Plant_Name TEXT,
Plant_Address TEXT,
Plant_City TEXT,
Plant_Type TEXT)
""")
# import dataframe data to sql database
df.to_sql('products', con=prod_conn1, if_exists='replace')
cf.to_sql('customers', con=cust_conn1, if_exists='replace')
lf.to_sql('plants', con=plnt_conn1, if_exists='replace')
# commit changes to database
prod_conn1.commit()
cust_conn1.commit()
plnt_conn1.commit()
# close connections
prod_conn1.close()
cust_conn1.close()
plnt_conn1.close()
return True
# if the dataframe is wrong for any reason
except:
ctypes.windll.user32.MessageBoxW(0,
'The selected file has missing or incomplete data. Please select a new file and try again.',
'Incompatible File', 0)
return False
# if source files already exist
return True
def datasearch_upload():
"""Initialize datasearch source data and create dependency files where necessary"""
# check if DataSearch directory does not exist
if not os.path.isdir('DataSearch'):
# create DataSearch directory
uniq_ds_dir_maker('DataSearch')
# check if initializing configuration file exists
if os.path.exists('DataSearch\\DataSearch.ini'):
# delete datasearch.ini
os.remove('DataSearch\\DataSearch.ini')
# create initializing configuration file
write_datasearch_ini()
# file destination select dialogue
Tk().withdraw() # prevent root window
# open file explorer folder select window
dirspath = askopenfilename(title='Select a DataSearch - Data Source file',
filetypes=[('Excel files', '.xlsx')])
if not dirspath:
ctypes.windll.user32.MessageBoxW(0, 'Update data file select cancelled.',
'Update Cancelled', 0)
return
try:
# create dataframes
df = pd.read_excel(dirspath, sheet_name='Product').fillna(0)
cf = pd.read_excel(dirspath, sheet_name='Customer').fillna('-')
lf = pd.read_excel(dirspath, sheet_name='Plant').fillna('-')
# reindex dataframes
df = df[['Plant', 'OSKU', 'MSKU', 'Segment', 'Description', 'Run_Freq',
'Production', 'Shelf_Life', 'Ship_Policy', 'BBL_Conversion', 'Units_p_Pallet']]
cf = cf[['ShipTo', 'ShipTo_Name', 'CSA', 'State', 'State_Code', 'Region', 'City', 'Postal_Code']]
lf = lf[['Plant', 'Plant_Name', 'Plant_Address', 'Plant_City', 'Plant_Type']]
# format columns
df['Plant'] = df['Plant'].astype(int)
cf['Postal_Code'] = cf['Postal_Code'].astype(str)
# identify lines that are all blanks
cf['Remove'] = np.where((cf['ShipTo_Name'] == '-') & (cf['CSA'] == '-') & (cf['State'] == '-') &
(cf['State_Code'] == '-') & (cf['Region'] == '-') & (cf['City'] == '-') &
(cf['Postal_Code'] == '-'), 1, 0)
# only keep rows that have nonzero values
cf = cf[~(cf.Remove != 0)]
# create database objects
prod_conn1 = sqlite3.connect('DataSearch\\products.db')
cust_conn1 = sqlite3.connect('DataSearch\\customers.db')
plnt_conn1 = sqlite3.connect('DataSearch\\plants.db')
# create a cursor instances
pc1 = prod_conn1.cursor()
cc1 = cust_conn1.cursor()
lc1 = plnt_conn1.cursor()
# create tables
pc1.execute("""CREATE TABLE if not exists products (
Plant INTEGER,
OSKU INTEGER,
MSKU INTEGER,
Segment TEXT,
Description TEXT,
Run_Freq TEXT,
Production TEXT,
Shelf_Life INTEGER,
Ship_Policy INTEGER,
BBL_Conversion REAL,
Units_p_Pallet INTEGER)
""")
cc1.execute("""CREATE TABLE if not exists customers (
ShipTo INTEGER,
ShipTo_Name TEXT,
CSA TEXT,
State TEXT,
State_Code TEXT,
Region TEXT,
City TEXT,
Postal_Code TEXT)
""")
lc1.execute("""CREATE TABLE if not exists plants (
Plant INTEGER,
Plant_Name TEXT,
Plant_Address TEXT,
Plant_City TEXT,
Plant_Type TEXT)
""")
# import dataframe data to sql database
df.to_sql('products', con=prod_conn1, if_exists='replace')
cf.to_sql('customers', con=cust_conn1, if_exists='replace')
lf.to_sql('plants', con=plnt_conn1, if_exists='replace')
# commit changes to database
prod_conn1.commit()
cust_conn1.commit()
plnt_conn1.commit()
# close connections
prod_conn1.close()
cust_conn1.close()
plnt_conn1.close()
# notify user that the source data has been updated successfully
ctypes.windll.user32.MessageBoxW(0,
'Your DataSearch data has been updated successfully.',
'Data Updated', 0)
# exit script if no dataframes were created
except UnboundLocalError:
ctypes.windll.user32.MessageBoxW(0,
'The file was loaded incorrectly. Please try again.',
'File Load Error', 0)
# if file is currently open
except PermissionError:
ctypes.windll.user32.MessageBoxW(0,
'The file you have selected is locked by the user. Please close the file and try again.',
'File Locked', 0)
# if dataframe is wrong
except (KeyError, ValueError, TypeError):
ctypes.windll.user32.MessageBoxW(0,
'Selected file has missing or incomplete data. Please select a new file and try again.',
'Incompatible File', 0)
# if the dataframe is wrong for any reason
except:
ctypes.windll.user32.MessageBoxW(0,
'The selected file has missing or incomplete data. Please select a new file and try again.',
'Incompatible File', 0)
return
def query_products():
"""Import product data from dataframe into database"""
# check file dependencies
datasearch_source_checker()
# check if products_stack should be reset
if p_search_stacking_intvar.get() == 0:
# delete products_stack.db
unstack_products()
# clear the treeview
for record in datatree1.get_children():
datatree1.delete(record)
# create database object
prod_conn1 = sqlite3.connect('DataSearch\\products.db')
# create a cursor instance
pc1 = prod_conn1.cursor()
# execute query
pc1.execute("SELECT * FROM products")
# get results
prod_rec = pc1.fetchall()
# add data to treeview
for prod_count1, record in enumerate(prod_rec):
# determine row count for tag formatting
if prod_count1 % 2 == 0:
# insert data from database skipping index column record[0]
datatree1.insert(parent='', index='end', iid=prod_count1, text='', values=(record[1], record[2], record[3],
record[4], record[5], record[6],
record[7], record[8], record[9],
record[10], record[11]),
tags=('everow',))
else:
datatree1.insert(parent='', index='end', iid=prod_count1, text='', values=(record[1], record[2], record[3],
record[4], record[5], record[6],
record[7], record[8], record[9],
record[10], record[11]),
tags=('oddrow',))
# commit changes to database
prod_conn1.commit()
# close connections
prod_conn1.close()
def query_customers():
"""Import customer data from dataframe into database"""
# check file dependencies
datasearch_source_checker()
# check if customers_stack should be reset
if c_search_stacking_intvar.get() == 0:
# delete customers_stack.db
unstack_customers()
# create database object
cust_conn1 = sqlite3.connect('DataSearch\\customers.db')
# create a cursor instance
cc1 = cust_conn1.cursor()
# execute query
cc1.execute("SELECT * FROM customers")
# get results
cust_rec = cc1.fetchall()
# clear the treeview
for record in datatree2.get_children():
datatree2.delete(record)
# add data to treeview
for cust_count1, record in enumerate(cust_rec):
# determine row count for tag formatting