-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinventory_sqlite.py
3158 lines (2936 loc) · 139 KB
/
inventory_sqlite.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
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from tkinter import filedialog
import sqlite3
from tkcalendar import Calendar
import os
import webbrowser
from PIL import Image
from PIL import ImageTk
import re
from datetime import datetime
from datetime import date
import calendar
import math
import openpyxl
from openpyxl.styles import Font
import string
from docx import Document
from docx.shared import Pt
import collections
import pandas
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def database():
#Create inventory database if it does not exist. Update certain
#values within the database.
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS 'raw_materials'
(type TEXT, product TEXT, amount INTEGER, price REAL,total TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'production'
(date DATE, product TEXT, amount INTEGER)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'in_progress'
(date DATE, product TEXT, amount INTEGER, description INTEGER)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'bottles'
(type TEXT, product TEXT, amount INTEGER,
case_size INTEGER, price REAL, total TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'samples'
(type TEXT, product TEXT, amount INTEGER,
price REAL, total TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'grain'
(date DATE, 'order_number' TEXT, type TEXT, amount INTEGER,
price REAL, total TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'grain_log'
(arrival_date DATE, finish_date DATE, type TEXT, order_no TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'mashes'
(date DATE, mash_no TEXT, type TEXT, grains TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'barrels'
('barrel_no' TEXT, type TEXT, gallons INTEGER,
'proof_gallons' REAL, 'date_filled' DATE, age TEXT,
investor TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'empty_barrels'
('barrel_no' TEXT, type TEXT, gallons INTEGER,
'proof_gallons' REAL,'pg_remaining' REAL, 'date_filled' DATE,
'date_emptied' DATE, age TEXT, investor TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'barrel_count'
('full_amount' INTEGER,'empty_amount' INTEGER, price REAL,
total TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'estimated_cogs'
(raw_mat REAL, energy REAL, labor REAL, error REAL,
'total_per_bottle' REAL, 'bond_ins' REAL, storage REAL,
mult_fact REAL, 'total_per_pg' REAL)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'purchase_orders'
(po_date DATE, pu_date DATE, product TEXT, amount INTEGER,
unit TEXT, price REAL, total REAL, destination TEXT,
'po_number' TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'pending_po'
(po_date DATE, pu_date DATE, product TEXT, amount INTEGER,
unit TEXT, price REAL, total REAL, destination TEXT,
'po_number' TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'employee_transactions'
(date DATE, product TEXT, amount INTEGER, unit TEXT,
employee TEXT, destination TEXT)
""")
cur.execute("""CREATE TABLE IF NOT EXISTS 'monthly_reports'
(date DATE, inv_name TEXT, total REAL,
UNIQUE(date, inv_name) ON CONFLICT REPLACE)
""")
conn.commit()
conn.close()
db_update()
def db_update():
#Updates inventory database values for specific columns.
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
cur.execute("""UPDATE 'raw_materials'
SET total=PRINTF('%s%g', '$', amount*price)
""")
cur.execute("""UPDATE 'raw_materials'
SET price=PRINTF('%.2f', price)
""")
cur.execute("""UPDATE 'bottles'
SET amount=0
WHERE amount<0
""")
cur.execute("""UPDATE 'bottles'
SET total=PRINTF('%s%g', '$', amount*price)
""")
cur.execute("""UPDATE 'samples'
SET amount=0
WHERE amount<0
""")
cur.execute("""UPDATE 'samples'
SET total=PRINTF('%s%.2f', '$', amount*price)
""")
cur.execute("""UPDATE 'grain'
SET total=PRINTF('%s%g', '$', amount*price)
""")
cur.execute("""UPDATE 'barrels'
SET age=PRINTF('%d years, %d months',
((julianday('now')
- julianday(date_filled)) / 365),
(((julianday('now')
- julianday(date_filled)) % 365) / 30))
""")
cur.execute("""SELECT COUNT(*)
FROM 'barrels'
""")
barrel_count = str(cur.fetchone()[0])
cur.execute("UPDATE 'barrel_count' " +
"SET full_amount=" + barrel_count)
cur.execute("""UPDATE 'barrel_count'
SET total=printf('%s%.2f', '$',
(full_amount + empty_amount) * price)
""")
cur.execute("""UPDATE 'estimated_cogs'
SET total_per_bottle=PRINTF('%.2f',
(raw_mat + energy + labor
+ error))
""")
cur.execute("""UPDATE 'estimated_cogs'
SET total_per_pg=PRINTF('%.2f',
((total_per_bottle*mult_fact)
+ bond_ins + storage))
""")
conn.commit()
conn.close()
def monthly_reports_update():
#Update 'monthly_reports' table with current month and inventory
#values. Only select purchase orders from current month. Selects
#pending purchase orders to be fulfilled next month.
inv_tables = ['raw_materials', 'bottles', 'samples', 'pending_po', 'grain',
'purchase_orders']
monthly_totals = collections.OrderedDict()
cur_date = datetime.today().strftime('%Y-%m')
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
cur.execute("SELECT product, price FROM bottles")
prod_prices = {key:val for (key, val) in cur.fetchall()}
for table in inv_tables:
if table == 'pending_po':
cur.execute("SELECT product, amount, total " +
"FROM " + table +
" WHERE po_date " +
"LIKE \'" + cur_date + "%\'")
pending_info = cur.fetchall()
pend_sale_amts = {} #Total sale amounts by product
for (prod, amt) in [x[:2] for x in pending_info]:
if prod in pend_sale_amts:
pend_sale_amts[prod] += int(amt)
else:
pend_sale_amts[prod] = int(amt)
pend_cogs_total = 0
for prod in pend_sale_amts.keys():
pend_cogs_total += float(pend_sale_amts[prod]
* prod_prices[prod])
pend_sale_total = sum([float(x[2][1:].replace(",", "")) for x
in pending_info])
monthly_totals['pending_sales'] = pend_sale_total
monthly_totals['pending_cogs'] = -1*pend_cogs_total
elif table == 'purchase_orders':
cur.execute("SELECT product, amount, total " +
"FROM " + table +
" WHERE pu_date " +
"LIKE \'" + cur_date + "%\'")
po_info = cur.fetchall()
po_sale_amts = {} #Total sales amount by product
for (prod, amt) in [x[:2] for x in po_info]:
if prod in po_sale_amts.keys():
po_sale_amts[prod] += int(amt)
else:
po_sale_amts[prod] = int(amt)
try:
po_cogs_total = 0
for prod in po_sale_amts.keys():
po_cogs_total += float(po_sale_amts[prod]
* prod_prices[prod])
except:
po_cogs_total = 0
po_sale_total = sum([float(x[2][1:].replace(",", "")) for x
in po_info])
monthly_totals['purchase_order_sales'] = po_sale_total
monthly_totals['purchase_order_cogs'] = -1*po_cogs_total
else:
cur.execute("SELECT total " +
"FROM " + table)
total_vals = [x[0] for x in cur.fetchall()]
total = sum([float(x[1:].replace(",", "")) for x
in total_vals])
monthly_totals[table] = total
cur.execute("SELECT * " +
"FROM barrels")
barrel_vals = cur.fetchall()
cur.execute("""SELECT total_per_pg
FROM estimated_cogs
""")
est_cogs = [x[0] for x in cur.fetchall()]
whisk_cogs = float(est_cogs[0])
rum_cogs = float(est_cogs[1])
whisk_total = 0
rum_total = 0
for barrel in barrel_vals:
if barrel[1] == 'Rum':
rum_total += float(barrel[3]) * rum_cogs
else:
whisk_total += float(barrel[3]) * whisk_cogs
monthly_totals['barreled_rum'] = ("%.2f" % rum_total)
monthly_totals['barreled_whiskey'] = ("%.2f" % whisk_total)
cur.execute("""SELECT total
FROM barrel_count
""")
barr_total = cur.fetchone()[0][1:].replace(",", "")
monthly_totals['barrels'] = barr_total
for key, value in monthly_totals.items():
value = ("%.2f" % float(value))
cur.execute("INSERT INTO monthly_reports " +
"VALUES (?, ?, ?)",
(cur_date, key, value))
conn.commit()
conn.close()
def create_excel_inv():
#Populate inventory_template.xlsx with inventory values and save as
#new workbook.
#('inv table', 'total column index')
inventories = (('raw_materials', 4),
('production', None),
('in_progress', None),
('bottles', 5),
('samples', 5),
('grain', 5),
('mashes', None),
('grain_log', None),
('barrels', None),
('empty_barrels', None),
('purchase_orders', 6),
('pending_po', 6),
('employee_transactions', None))
inventories = collections.OrderedDict(inventories)
excel_file = (os.getcwd() + "/inventory_files/inventory_template.xlsx")
wb = openpyxl.load_workbook(excel_file)
sheets = wb.sheetnames
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
for sheet, (inv, tot_col) in zip(sheets, inventories.items()):
active_sheet = wb[sheet]
cur.execute("SELECT * " +
"FROM " + inv)
inv_values = cur.fetchall()
if len(inv_values) > 0:
for (indx, row) in enumerate(inv_values, 2):
try:
row = list(row)
# Strip $, remove commas
row[tot_col] = float(row[tot_col][1:].replace(",",""))
tot_col += 1 # Change index for excel column
active_sheet.append(row)
active_sheet.cell(indx, tot_col).number_format = '$#,##0.00'
except TypeError:
pass
last_row = len(inv_values) + 1
last_col = len(inv_values[0]) - 1
# Format text to justify centrally
rows = range(1, last_row + 1)
columns = string.ascii_uppercase[:last_col + 1]
last_col = string.ascii_uppercase[last_col]
for row in rows:
for col in columns:
cell = col + str(row)
active_sheet[cell].alignment = (
openpyxl.styles.Alignment(horizontal='center'))
# Format excel table
tbl_ref = "A1:" + str(last_col) + str(last_row)
tbl = openpyxl.worksheet.table.Table(displayName=inv, ref=tbl_ref)
style = openpyxl.worksheet.table.TableStyleInfo(
name="TableStyleMedium9", showFirstColumn=False,
showLastColumn=False, showRowStripes=True)
tbl.tableStyleInfo = style
active_sheet.add_table(tbl)
conn.close()
new_excel_file = (os.getcwd() + "/inventory_files/"
+ datetime.now().strftime("%Y-%m") + ".xlsx")
wb.save(new_excel_file)
os.system('start EXCEL.EXE ' + new_excel_file)
def edit_db(sql_edit, sqlite_table, gui_table, view_fr, delete=False):
#Updates the sqlite_table with the changes provided by sql_edit.
#sql_edit is a tuple of length 2*(num of cols)
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
cur.execute("SELECT * " +
"FROM " + sqlite_table)
columns = [x[0] for x
in cur.description]
str1 = "=?, ".join(columns) + "=?" # row1=?, row2=?, ...
str2 = "=? AND ".join(columns) + "=?" # row1=? AND row2=? AND ...
if delete == False:
cur.execute("UPDATE " + sqlite_table +
" SET " + str1 +
" WHERE " + str2,
sql_edit)
else:
cur.execute("DELETE FROM " + sqlite_table +
" WHERE " + str2,
sql_edit)
conn.commit()
conn.close()
try:
view_fr.columns.set("All")
view_fr.columns.event_generate("<<ComboboxSelected>>")
except:
pass
try:
view_products(sqlite_table, 'All', 'All', gui_table)
except:
pass
db_update()
if sqlite_table == 'barrels':
barr_count_fr.barr_update(first=1)
def view_widget(window, widget, location, sqlite_table, column, item,
gui_table):
#Removes current packed widgets from window frame and replaces with
#new widget chosen.
for widg in window.pack_slaves():
widg.pack_forget()
widget.pack(side=location, fill=BOTH, expand=1)
if gui_table:
view_products(sqlite_table, column, item, gui_table)
def view_products(sqlite_table, column, item, gui_table):
#Fetches info from sqlite_table based on an item filter. Returns
#information into the current gui_table. Configures even-numbered
#rows to have a grey background.
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
if column == "All":
cur.execute("SELECT * " +
"FROM " + sqlite_table)
elif column == "barrel_no":
cur.execute("SELECT * " +
"FROM " + sqlite_table +
" WHERE " + column +
" LIKE \'" + item[:2] + "%\'")
elif 'date' in column:
try:
cur.execute("SELECT * " +
"FROM " + sqlite_table +
" WHERE " + column +
" LIKE \'" + item[:4] + "%\'")
except sqlite3.OperationalError:
cur.execute("SELECT * " +
"FROM " + sqlite_table +
" WHERE po_date" +
" LIKE \'" + item[:4] + "%\'")
elif 'pick' in column:
cur.execute("SELECT * " +
"FROM " + sqlite_table +
" WHERE pu_date" +
" LIKE \'" + item[:4] + "%\'")
elif column == "age":
cur.execute("SELECT * " +
"FROM " + sqlite_table +
" WHERE " + column +
" LIKE \'" + item[0] + "%\'")
elif column == "product":
cur.execute("SELECT * " +
"FROM " + sqlite_table +
" WHERE " + column +
" LIKE \'" + item + "%\'")
else:
cur.execute("SELECT * " +
"FROM " + sqlite_table +
" WHERE " + column + "= \'" + item + "\'")
rows = cur.fetchall()
conn.close()
for item in gui_table.get_children():
gui_table.delete(item)
for index,row in enumerate(rows):
if (index % 2 == 0):
tag = 'even'
else:
tag = 'odd'
gui_table.insert("", END, values=row, tags=(tag,))
gui_table.tag_configure('even', background='#E8E8E8')
def file_view(folder):
#Displays a toplevel window populated by clickable links to
#files within the given folder.
labels_window = Toplevel(window)
files = os.listdir(os.getcwd() + "\\" + folder)
window_height = 0
for file in files:
mo = fileRegex.search(file)
file_name = mo.group(1).replace("_", " ")
file_label = Sheet_Label(
master=labels_window, text=file_name,
file_location=(os.getcwd() + "\\" + folder + "\\" + file))
file_label.pack(padx=10, pady=5, anchor='w')
window_height += 38
labels_window.title(folder.replace("_", " ").title())
labels_window.focus()
x = (screen_width/2) - (250)
y = (screen_height/2) - (250)
labels_window.geometry("%dx%d+%d+%d" % (300, window_height, x, y))
labels_window.resizable(0,0)
def selection_check(sqlite_table, gui_table, view_fr, edit=True, delete=False,
empty=False):
#Checks to see if a gui_table selection has been made and returns
#the respective action based on the gui_table.
item_values = gui_table.item(gui_table.selection())['values']
if item_values:
if delete == True:
del_ques = messagebox.askquestion(
"Delete Current Selection?",
"Are you sure you want to continue? Confirming will delete the " +
"current selection from the inventory. This information will not " +
"be able to be recovered.")
if del_ques == 'yes':
edit_db(tuple(item_values), sqlite_table, gui_table, view_fr,
delete=True)
else:
return
elif empty == True:
Empty_Barrel_View(window, item_values)
elif (gui_table == po_tbl and edit==False): # Open po excel file
po_num = item_values[8]
try:
excel_file = (os.getcwd() + "/purchase_orders/" + po_num[:4]
+ "/" + po_num + ".xlsx")
os.system('start EXCEL.EXE ' + excel_file)
except:
messagebox.showerror(
"Program Error",
"There was an error opening Excel.", parent=window)
elif gui_table == inprog_tbl: #Finish in progress production
Finish_View(window, item_values)
elif (gui_table == pending_tbl and edit==False): #fulfill po
fulfill_pending(gui_table, view_fr)
else: #edit selection
Edit_View(window, sqlite_table, gui_table, 2, view_fr)
else:
messagebox.showerror(
"Selection Error",
"Please select an inventory item.", parent=window)
def gui_table_sort(gui_table, column, reverse):
#Sorts gui tables in ascending order based on the column header
#clicked. The next click upon the header will be in reverse order.
l = [(gui_table.set(k, column), k) for k
in gui_table.get_children()]
if '$' in l[0][0]: #Check if column is 'total'
l.sort(key=lambda tup: float(tup[0][1:].replace(",", "")),
reverse=reverse)
else:
try:
l.sort(key=lambda tup: float(tup[0].replace(",","")),
reverse=reverse)
except ValueError:
l.sort(key=lambda tup: tup[0], reverse=reverse)
#Rearrange items in sorted positions.
for index, (val, k) in enumerate(l):
gui_table.move(k, '', index)
gui_table.item(k, tags=())
if index % 2 == 0:
gui_table.item(k, tags=('even',))
gui_table.tag_configure('even', background="#E8E8E8")
#Reverse sort next time.
gui_table.heading(
column, text=column,
command=lambda c=column: gui_table_sort(gui_table, c, not reverse))
def cal_button(tplvl, date_entry):
#Creates a toplevel window to provide a calendar date selection
#tool.
tplvl.top = Toplevel(window)
tplvl.cal = Calendar(tplvl.top, font="Arial 14", selectmode='day',
locale='en_US', cursor="hand2")
tplvl.cal.pack(fill="both", expand=True)
(HoverButton(tplvl.top, text="ok",
command=lambda: retrieve_date(tplvl, date_entry))
.pack())
tplvl.top.focus()
def retrieve_date(tplvl, date_entry):
#Updates the date-entry widget within the toplevel widget with
#formatted date value.
date_entry.config(state=NORMAL)
date_entry.delete(0 ,END)
date_entry.insert(END, tplvl.cal.selection_get().strftime("%Y-%m-%d"))
date_entry.config(state="readonly")
tplvl.top.destroy()
def confirm_po(view_fr, info, purchase_orders, po_num):
#Insert purchase order info into 'purchase_orders' table and create
#excel file with purchase order info.
year = datetime.now().year
wb = openpyxl.load_workbook(
'purchase_orders/blank_po.xlsx')
sheet = wb['Purchase Order']
font = Font(name='Times New Roman', size=12)
#Get shipment information entry-values into list and input them into
#corresponding cells within the 'po' excel sheet.
info_cells = ['A9', 'K9', 'A12', 'A15', 'I15']
for entry,cell in zip(info, info_cells):
sheet[cell] = entry
sheet[cell].font = font
#Get order values and input into table within purchase order excel
#file.
excel_rows = ["A","B","D","J","M"]
excel_columns = range(18, 36)
index = 0
total_po = 0
for i in excel_columns:
for j,k in zip(excel_rows, range(0,5)):
cell = j + str(i)
try:
sheet[cell] = (purchase_orders[index][k])
sheet[cell].font = font
if k == 4:
try:
total_po += float(
purchase_orders[index][k][1:].replace(',',''))
except ValueError:
pass
except IndexError:
sheet[cell] = ""
index += 1
total_po = "{0:,.2f}".format(total_po)
sheet['M36'] = ("$%s" % total_po)
#Add purchase orders to 'purchase_orders' table and update
#inventory.
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
for po_list in (x for x in purchase_orders if all(x)):
cur.execute("INSERT INTO 'purchase_orders' " +
"VALUES (?,?,?,?,?,?,?,?,?)",
(info[3], info[4], po_list[2], po_list[0], po_list[1],
po_list[3], po_list[4], info[2], po_num))
if po_list[1] == "Cases":
cur.execute("UPDATE 'bottles' " +
"SET amount=(amount - ?) " +
"WHERE product=?",
(po_list[0], po_list[2]))
else:
cur.execute("UPDATE 'samples' " +
"SET amount=(amount - ?) " +
"WHERE product=?",
(po_list[0], po_list[2]))
conn.commit()
conn.close()
excel_file = (os.getcwd() + "/purchase_orders/"
+ str(year) + "/" + po_num
+ ".xlsx")
wb.save(excel_file)
open_ques = messagebox.askquestion(
"Open the PO Excel File?",
"Would you like to open the Purchase Order file in Excel? "
+ "This will allow you to print it now.")
if open_ques == "yes":
try:
os.system('start EXCEL.EXE ' + excel_file)
except:
messagebox.showerror(
"Program Error",
"There was an error opening Excel.", parent=self)
else:
pass
db_update()
view_fr.columns.set("All")
view_fr.columns.event_generate("<<ComboboxSelected>>")
def fulfill_pending(gui_table, view_fr):
#Remove pending purchase order from 'pending_po' table and input
#into 'purchase_orders'. Create an excel file with info.
po_num = gui_table.item(gui_table.selection())['values'][8]
conn = sqlite3.Connection("inventory.db")
cur = conn.cursor()
cur.execute("SELECT * " +
"FROM 'pending_po' " +
"WHERE po_number=\'" + po_num + "\'")
po_vals = cur.fetchall()
conn.close()
po_1 = po_vals[0]
po_info = ["Montgomery", po_num, po_1[7], po_1[0], po_1[1]]
comp_pos = [[x[3] ,x[4], x[2], x[5], x[6]] for x in po_vals]
confirm_po(view_fr, po_info, comp_pos, po_num)
for po in po_vals:
edit_db(po, 'pending_po', gui_table, view_fr, delete=True)
class HoverButton(Button):
#Button widget with mouse-over color and cursor changes.
def __init__(self, master, **kw):
Button.__init__(self, master=master, cursor="hand2", **kw)
self.defaultBackground = self["background"]
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, event):
self['background'] = 'gray70'
def on_leave(self, event):
self['background'] = self.defaultBackground
class Add_View(Toplevel):
#A toplevel widget with labels corresponding to sqlite table columns
#and entry widgets to insert data into the sqlite table.
def __init__(self, master, sqlite_table, gui_table, entry_col, view_fr):
self.sqlite_table = sqlite_table
self.gui_table = gui_table
self.entry_col = entry_col
self.view_fr = view_fr
self.tplvl_title = self.sqlite_table.replace("_"," ").title()
self.x = (screen_width/2) - (width/2) + 100
self.y = ((screen_height/2) - (height/2)) + 50
Toplevel.__init__(self, master=master)
self.title_frame = Frame(self)
(Label(self.title_frame,
text="Add Product to " + self.tplvl_title + " Inventory",
font="Arial 10 bold")
.pack())
self.title_frame.grid(row=0, column=0, columnspan=2, pady=5)
#Create labels and entries based on gui_table column headers.
for index,description in enumerate(self.gui_table.columns, 1):
if (description.lower() != 'type'):
Label(self, text=description + ":").grid(row=index, column=0)
if description.lower() == 'total':
self.total_text = StringVar()
self.total_entry = Entry(self, textvariable=self.total_text)
self.total_entry.config(state="readonly")
self.total_entry.grid(row=index, column=self.entry_col)
elif (description.lower().find('age') != -1):
self.age_text = StringVar()
self.age_entry = Entry(self, textvariable=self.age_text)
self.age_entry.config(state="readonly")
self.age_entry.grid(row=index, column=self.entry_col)
else:
Entry(self).grid(row=index,column=self.entry_col)
if (description.lower().find('date') != -1):
self.date_index = index
self.date_entry = self.grid_slaves(row=self.date_index,
column=self.entry_col)[0]
self.date_entry.config(state="readonly")
self.cal_link = HoverButton(
self, image=cal_photo,
command=lambda: cal_button(self, self.date_entry))
self.cal_link.image = cal_photo
self.cal_link.grid(row=index, column=self.entry_col+1)
elif ((description.lower().find('total') != -1) or
(description.lower().find('age') != -1)):
self.labels = [x for x
in reversed(self.grid_slaves(column=0))
if (x.winfo_class() == 'Label')]
for entry in self.labels:
if entry.cget("text").lower().find("amount") != -1:
self.amount_row = entry.grid_info()['row']
self.amount_entry = self.grid_slaves(
row=self.amount_row,
column=self.entry_col)[0]
if entry.cget("text").lower().find("price") != -1:
self.price_row = entry.grid_info()['row']
self.price_entry = self.grid_slaves(
row=self.price_row,
column=self.entry_col)[0]
self.total_after()
else: #Type option entry.
Label(self, text=description + ":").grid(row=index, column=0)
self.options = ttk.Combobox(self,
values=type_options[sqlite_table])
self.options.set(type_options[sqlite_table][0])
self.options.config(width=16, background="white",
justify='center', state='readonly')
self.options.grid(row=index, column=self.entry_col)
self.grid_size = self.grid_size()[1]
self.button_frame = Frame(self)
(HoverButton(self.button_frame, text="Add Item", width=10,
command=self.add_item)
.pack(side=LEFT, padx=5, pady=5))
(HoverButton(self.button_frame, text="Cancel", width=10,
command=lambda : self.destroy())
.pack(side=LEFT, padx=5, pady=5))
self.button_frame.grid(row=self.grid_size+1, column=0, columnspan=2)
self.title("Add to " + self.tplvl_title)
self.focus()
self.geometry("+%d+%d" % (self.x, self.y))
self.resizable(0,0)
def add_item(self):
#Work through Add_View toplevel to find entry widgets and
#extract these values to be inserted into the sqlite table.
#Uses db_update() to update certain column values afterwards
#and view_products() to display the updated gui table.
self.additions = [] #list to be populated by entries
self.num_entries = 0
self.entries = [x for x
in reversed(self.grid_slaves())
if (x.winfo_class() == 'Entry'
or x.winfo_class() == 'TCombobox')]
for entry in self.entries:
if entry.winfo_class() == 'Entry' and entry.get():
#Titlecase before appending
self.additions.append(' '.join(word[0].upper() + word[1:]
for word
in entry.get().split()))
self.num_entries += 1
elif entry.winfo_class() == 'TCombobox':
self.additions.append(entry.get())
self.num_entries += 1
else:
messagebox.showerror("Input Error",
"At least one input is blank, "
+ "please try again.", parent=self)
return
self.additions = tuple(self.additions)
self.str1 = "?,"*(self.num_entries - 1) + "?)" #?,?,..,?)
self.conn = sqlite3.Connection("inventory.db")
self.cur = self.conn.cursor()
self.cur.execute("INSERT INTO " + self.sqlite_table +
" VALUES (" + self.str1,
self.additions)
self.conn.commit()
self.conn.close()
db_update()
try:
self.view_fr.columns.set("All")
self.view_fr.columns.event_generate("<<ComboboxSelected>>")
except:
view_products(self.sqlite_table, 'All', 'All', self.gui_table)
if self.sqlite_table == 'barrels':
barr_count_fr.barr_update(first=1)
self.destroy()
def total_after(self):
#Widget after-function to update total and age entry values.
#Repeats every 150ms.
def total_update():
#Tries to update total and age entry values.
#Raises:
#AttributeError: if price_entry, amount_entry, date_entry
#don't exist
#ValueError: if price_entry, amount_entry, date_entry values
#are currently empty
try: #update total entry
self.price_num = self.price_entry.get()
self.amount_num = self.amount_entry.get()
self.total_string = ("$%.2f" %
(float(self.amount_num)
*float(self.price_num)))
self.total_text.set(self.total_string)
return
except (AttributeError, ValueError):
pass
try: #Update age entry.
self.date_value = datetime.strptime(self.date_entry.get(),
'%Y-%m-%d')
self.date_diff = datetime.now() - self.date_value
self.barrel_age = ("%d years, %d months" %
(math.floor(self.date_diff.days/365.2425),
(self.date_diff.days%365.2425)/30))
self.age_text.set(self.barrel_age)
except (AttributeError, ValueError):
pass
total_update()
self.after(150, self.total_after)
class Edit_View(Add_View):
#A toplevel widget with labels corresponding to sqlite table columns
#and entry widgets to update data in sqlite table.
def __init__(self, master, sqlite_table, gui_table, entry_col, view_fr):
self.master = master
self.sqlite_table = sqlite_table
self.gui_table = gui_table
self.entry_col = entry_col #Column location for entry widgets.
self.view_fr = view_fr
self.selection = self.gui_table.selection()
self.item_values = self.gui_table.item(self.selection)['values']
self.tplvl_title = self.sqlite_table.replace("_"," ").title()
Add_View.__init__(self, master, sqlite_table, gui_table, entry_col,
view_fr)
self.title("Edit " + self.tplvl_title)
self.title_frame.destroy() #Remove add_view title frame.
self.title_frame = Frame(self)
(Label(self.title_frame,
text="Edit Product in " + self.tplvl_title + " Inventory",
font="Arial 10 bold")
.pack())
self.title_frame.grid(row=0, column=0, columnspan=3)
#Create toplevel labels.
for index,description in enumerate(self.gui_table.columns):
if (description.lower() != 'type'):
(Label(self, text=self.item_values[index], foreground='blue')
.grid(row=index+1, column=1))
else:
(Label(self, text=self.item_values[index], foreground='blue')
.grid(row=index+1, column=1))
self.button_frame.destroy()
self.button_frame = Frame(self)
(HoverButton(self.button_frame, text="Confirm", command=self.confirm)
.pack(side=LEFT, padx=5, pady=5))
(HoverButton(self.button_frame, text="Cancel",
command=lambda: self.destroy())
.pack(side=LEFT, padx=5, pady=5))
self.button_frame.grid(row=self.grid_size+1, column=0, columnspan=3)
def confirm(self):
#Work through Edit_View toplevel to find entry widgets and
#extract these values to be updated in the given sqlite table.
#Uses db_update() to update certain column values afterwards and
#view_products() to display the updated gui table.
self.changes = [] #list where updated entries will exist
self.edit_entries = [x for x
in reversed(self.grid_slaves())
if (x.winfo_class() == 'Entry'
or x.winfo_class() == 'TCombobox')]
for entry in self.edit_entries:
if entry.winfo_class() == 'Entry' and entry.get():
#Titlecase before appending.
self.changes.append(' '.join(word[0].upper() + word[1:]
for word
in entry.get().split()))
elif entry.winfo_class() == 'TCombobox':
self.changes.append(entry.get())
else:
messagebox.showerror("Input Error",
"At least one input is blank, please try "
+ "again.", parent=self)
return
self.current_values = [x.cget('text') for x
in reversed(self.grid_slaves(column=1))
if (x.winfo_class() == 'Label')]
self.changes = tuple(self.changes + self.current_values)
db_update()
edit_db(self.changes, self.sqlite_table, self.gui_table, self.view_fr)
self.destroy()
class Production_View(Toplevel):
#Toplevel used to register production. Subtracts values from raw
#materials when used. Handles unfinished products by placing in
#'in_progress' table to be finished later.
def __init__(self,master,sqlite_table,gui_table):
self.master = master
self.sqlite_table = sqlite_table
self.gui_table = gui_table
self.x = (screen_width/2) - (width/2) + 100
self.y = ((screen_height/2) - (height/2)) + 50
Toplevel.__init__(self,master=master)
self.title_frame = Frame(self)
Label(self.title_frame, text="Production", font="Arial 10 bold").pack()
self.title_frame.grid(row=0, column=0, columnspan=3, pady=5)
self.product_frame = Frame(self)
Label(self.product_frame, text="Total Bottles").grid(row=0, column=0)
Label(self.product_frame, text="Cases").grid(row=0, column=1)
Label(self.product_frame, text="Product").grid(row=0, column=2)
(Entry(self.product_frame, validate='key',
validatecommand=(self.register(valid_dig),'%S','%d'))
.grid(row=1, column=0, padx=5))
(Entry(self.product_frame, validate='key',
validatecommand=(self.register(valid_dig),'%S','%d'))
.grid(row=1, column=1, padx=5))
self.conn = sqlite3.Connection("inventory.db")
self.conn.row_factory = lambda cursor, row: row[0]
self.cur = self.conn.cursor()
self.cur.execute("SELECT product " +
"FROM 'bottles'")
self.product_rows = self.cur.fetchall()
self.products = ttk.Combobox(self.product_frame,
values=self.product_rows)
self.products.config(width=20, background="white", justify='center',
state='readonly')
self.products.set(self.product_rows[0])
self.products.grid(row=1, column=2, padx=5)
self.product_frame.grid(row=1, column=0, columnspan=3)
#Raw materials title frame.
self.materials = Frame(self)
(Label(self.materials, text="Materials Used", font="Arial 10 bold")
.pack())
self.materials.grid(row=3, column=0, columnspan=3, pady=5)
#Raw materials input frame.
Label(self, text="Type").grid(row=4, column=0, pady=2)
Label(self, text="Amount").grid(row=4, column=1, pady=2)
Label(self, text="Material").grid(row=4, column=2, pady=2)
self.type_rows = type_options['raw_materials']
#Create label, entry, option box for each type of raw material.
for index,description in enumerate(self.type_rows,5):
Label(self, text=description + ":").grid(row=index, column=0,
sticky=W)
(Entry(self, validate='key',
validatecommand=(self.register(valid_dig),'%S','%d'))
.grid(row=index, column=1))
self.cur.execute("SELECT product "
+ "FROM 'raw_materials' " +
"WHERE type=\'" + description + "\'")
self.rows = self.cur.fetchall()
self.rows.append("None")
self.opt_menu = ttk.Combobox(self, values=self.rows)
self.opt_menu.config(width=20, background="white", justify='center',
state='readonly')
self.opt_menu.set(self.rows[0])
self.opt_menu.grid(row=index, column=2, padx=5)
#Finished product checkbox.
self.grid_size = self.grid_size()[1]
self.check_var = IntVar()
self.check_var.set(1)
self.check_b = Checkbutton(
self, text="Are the products finished? (i.e. labeled)",
variable=self.check_var, command=self.cbox_check)
self.check_b.grid(row=self.grid_size+1, column=0, columnspan=3)
#Samples input frame.
self.samples_frame = Frame(self)
Label(self.samples_frame, text="Samples").grid(row=0, column=0)
self.samples_entry = Entry(
self.samples_frame, validate='key',
validatecommand=(self.register(valid_dig),'%S','%d'))
self.samples_entry.grid(row=0, column=1)
self.samples_frame.grid(row=self.grid_size+2, column=0, columnspan=3)
self.button_frame = Frame(self)
(HoverButton(self.button_frame, text="Confirm", width=10,
command=self.confirm)
.pack(side=LEFT, padx=5, pady=5))
(HoverButton(self.button_frame, text="Cancel", width=10,
command=lambda: self.destroy())
.pack(side=LEFT, padx=5, pady=5))
self.button_frame.grid(row=self.grid_size+3, column=0, columnspan=3)
self.conn.close()
self.title("Production")
self.focus()
self.geometry("+%d+%d" % (self.x, self.y))
self.resizable(0,0)