This repository was archived by the owner on Feb 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
1990 lines (1524 loc) · 74.9 KB
/
Copy pathapplication.py
File metadata and controls
1990 lines (1524 loc) · 74.9 KB
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 difflib import restore
import os
import requests
# import urllib.parse
import time
import datetime
import csv
import shopify
import json
import psycopg2
import psycopg2.extras
from psycopg2 import pool
from flask import Flask, redirect, render_template, request, session, \
url_for, flash, send_from_directory, Markup, g
from flask_session import Session
from tempfile import mkdtemp
from functools import wraps
# from termcolor import colored
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.utils import secure_filename
from helpers import allowed_file, parse_sku, build_production, build_totals, \
generate_item, generate_sku
from database import migrate_users, migrate_events, restore_event, fetchDict, gather_templates, \
drop_tables, initialize_database, setup_loterias, restore_items, restore_parts
from dotenv import load_dotenv
load_dotenv()
###### DEFINITIONS ######
# item: fully assembled woodcut item
# part: constituent piece that comprises an item, usually one of two or three
# loteria: woodcut loteria pieces
# cycle: a single event or series of events, used for creating projections
# event: renamed cycles for clarity
###### CONFIGURATION ######
# Initialize Flask App Ojbect
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Ensure responses aren't cached
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['UPLOAD_FOLDER'] = os.getenv('PWD') + "/static/uploads"
app.config['BACKUPS'] = os.getenv('PWD') + "/static/backups"
Session(app)
# Import Authorized User List
authusers = []
authusers.append(os.getenv('USERA'))
authusers.append(os.getenv('USERB'))
authusers.append(os.getenv('USERC'))
###### DATABASE ######
# Setup PostgreSQL database connection
conn = None
db = os.getenv('HEROKU_POSTGRESQL_BLUE_URL')
# og = os.getenv('DATABASE_URL')
# dev = os.getenv('HEROKU_POSTGRESQL_PURPLE_URL')
# prod = os.getenv('HEROKU_POSTGRESQL_BLUE_URL')
# # Testing
# if os.getenv('FLASK_ENV') == 'development':
# print("Starting in DEBUG. Connecting to DEVELOPMENT database...", end="")
# db = dev
# # Production
# else:
# print("Connecting to PRODUCTION database...", end="")
# db = prod
# # Cold Start Initialization # TODO test that cold start works since refactor
# if int(os.getenv('COLD_START')) == 1:
# with psycopg2.connect(db) as conn:
# with conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) as cur:
# print("Dropping Tables and Initializing Database...", end="")
# drop_tables(conn)
# initialize_database(conn)
# print("done.")
###### APP FUNCTIONS ######
def login_required(f):
"""
Decorate routes to require login.
http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
###### MAIN ROUTES ######
@app.route('/', methods=['GET'])
@login_required
def dashboard():
# https://www.psycopg.org/docs/usage.html
# Note: this could be done with decorators
# https://pythonise.com/series/learning-flask/custom-flask-decorators
with psycopg2.connect(db) as conn:
with conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) as cur:
if request.method == 'GET':
print("--- / ---")
# cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
# Identify current cycle and retrieve data
cur.execute("SELECT * FROM nail_cycles WHERE current='TRUE'")
cycle = fetchDict(cur)
if not cycle:
# set default as active
try:
cur.execute("UPDATE nail_cycles SET current='TRUE' WHERE id=1 RETURNING *")
cycle = fetchDict(cur)
conn.commit()
except Exception as e:
print(f"Default Event exception: {e}")
data = cur.execute("SELECT * FROM nail_cycles")
data = fetchDict(cur)
if not data:
# Seed table with Default Event
time = datetime.datetime.utcnow().isoformat()
cur.execute("INSERT INTO nail_cycles (id, name, created_on, current) \
VALUES ('Default Event', %s, 'TRUE')", (time,))
cur.execute("UPDATE nail_cycles SET current='TRUE' WHERE id=1")
conn.commit()
else:
cur.execute("UPDATE nail_cycles SET current='TRUE' WHERE id=1")
conn.commit()
# Query for relevant data
cur.execute("SELECT username from nail_users WHERE id=%s", (session["user_id"],))
user = fetchDict(cur)
templates = gather_templates(conn)
progress = build_production(conn, templates)
cur.execute("SELECT * FROM nail_queueParts \
ORDER BY size DESC, name DESC, color DESC")
production = fetchDict(cur)
data = build_totals(production, templates)
print(f"data:{data}")
totals = data['totals']
grand_total = data['grand_total']
cur.execute("SELECT sum(qty) FROM nail_boxprod")
boxprod = fetchDict(cur)
if boxprod[0]['sum'] != 0: # recently change from "is not None"
grand_total += boxprod[0]['sum']
totals[0].append(boxprod[0]['sum'])
else:
# Append zero when none
totals[0].append(0)
print(f"totals:{totals}")
cur.execute("SELECT sum(qty) FROM nail_projections \
WHERE cycle=(SELECT id FROM nail_cycles WHERE current='TRUE')")
projection_totals = fetchDict(cur)
cur.execute("SELECT sum(qty) FROM nail_items")
item_totals = fetchDict(cur)
cur.execute("SELECT sum(qty) FROM nail_parts")
part_totals = fetchDict(cur)
cur.execute("SELECT sum(qty) FROM nail_queueParts")
production_totals = fetchDict(cur)
time = datetime.datetime.utcnow().isoformat()
cur.close()
return render_template('index.html',
templates=templates,
production=production,
user=user,
item_totals=item_totals,
part_totals=part_totals,
projection_totals = projection_totals,
production_totals = production_totals,
totals=totals,
cycle=cycle,
time=time,
progress=progress,
grand_total=grand_total)
else:
return redirect("/")
@app.route('/parts/<part>', methods=['GET', 'POST'])
@login_required
def parts(part):
# https://www.psycopg.org/docs/usage.html
with psycopg2.connect(db) as conn:
with conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) as cur:
if request.method == 'GET':
# cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
templates = gather_templates(conn)
build_production(conn, templates)
# Determine if color
is_color = False
for color in templates['colors']:
if color['name'] == part:
cur_color = color
is_color = True
if is_color == True:
#TODO eliminate like?
part_like = cur_color['name']
part_like = '%' + part # TODO is this wrong
# part_like = part
cur.execute("SELECT * FROM nail_queueParts WHERE color LIKE %s \
ORDER BY qty DESC", (part_like,))
productions = fetchDict(cur)
print(cur_color)
cur.execute("SELECT * FROM nail_parts WHERE color LIKE %s \
ORDER BY size DESC, qty DESC", (part_like,))
inventory = fetchDict(cur)
if not 'recent_part' in session :
session['recent_part'] = 'None'
print(session)
cur.close()
return render_template('parts.html',
cur_color=cur_color,
templates=templates,
productions=productions,
inventory=inventory,
recent=session['recent_part'])
if part == 'backs':
cur_color = {
'name': 'backs',
'emoji': '🍑'
}
cur.execute("SELECT * FROM nail_queueParts \
WHERE name LIKE '%Backs' ORDER BY qty DESC")
productions = fetchDict(cur)
cur.execute("SELECT * FROM nail_parts \
WHERE name LIKE '%Backs' ORDER BY size DESC, qty DESC")
inventory = fetchDict(cur)
print("part is a back...")
print(f"productions:{productions}")
if not 'recent_part' in session :
session['recent_part'] = 'None'
cur.close()
return render_template('parts.html',
cur_color=cur_color,
templates=templates,
part=part,
productions=productions,
inventory=inventory,
recent=session['recent_part'])
if part == 'boxes':
# Box Production Total
cur.execute("SELECT SUM(qty) FROM nail_boxprod")
box_prod_total = fetchDict(cur)
box_prod_total = box_prod_total[0]['sum']
# Box Inventory & Production
cur.execute("SELECT * FROM nail_boxes ORDER BY qty DESC")
boxes = fetchDict(cur)
cur.execute("SELECT * FROM nail_boxprod ORDER BY qty DESC")
boxprod = fetchDict(cur)
cur.execute("SELECT * FROM nail_boxused ORDER BY qty DESC")
boxused = fetchDict(cur)
cur.close()
cur_color = {
'name': 'boxes',
'emoji': '📦'
}
return render_template('boxes.html',
cur_color=cur_color,
templates=templates,
boxes=boxes,
boxprod=boxprod,
boxused=boxused,
box_prod_total=box_prod_total)
else:
flash("Invalid part descriptor")
cur.close()
return redirect("/")
# Upon POSTing form submission
else:
part = request.form.get("part")
size = request.form.get("size")
color = request.form.get("color")
qty = int(request.form.get("qty"))
print(f"POST TO '/' with: {part}, {size}, {color}, {qty}")
session['recent_part'] = {
'part': part,
'size': size,
'color': color,
'qty': qty
}
print(f"Sumission: {part}, {size}, {color}, {qty}, {session['recent_part']}")
if not size:
flash('Size must be specified for part')
return redirect(f'/parts/{color}')
# Determine if part with color, or backs
cur.execute("SELECT backs FROM nail_loterias WHERE backs=%s", (part,))
backs_onhand = fetchDict(cur)
# BACKS
if backs_onhand:
print(f"Backs on hand: {backs_onhand}")
# What quantity of this part already exists?
cur.execute("SELECT qty FROM nail_parts WHERE \
name=%s AND size=%s", \
(part, size))
onhand = fetchDict(cur)
print(f"Fetching onhand backs...")
print(onhand)
# None, create new entry
if not onhand:
cur.execute("INSERT INTO nail_parts (name, size, qty) VALUES \
(%s, %s, %s)", \
(part, size, qty))
conn.commit()
print(f"New {size} {part} entry created with qty {qty}.")
# Update existing entry's quantity
else:
new_qty = onhand[0]['qty'] + qty
if new_qty < 1:
cur.execute("DELETE FROM nail_parts WHERE \
name=%s AND size=%s", (part, size))
conn.commit()
else:
cur.execute("UPDATE nail_parts SET qty=%s WHERE \
name=%s AND size=%s", (new_qty, part, size))
conn.commit()
print(f"Existing {size} {part} inventory quantity \
updated from {onhand[0]['qty']} to {new_qty}.")
# Update production queue
# Identify matching part that is already in production
cur.execute("SELECT qty FROM nail_queueParts WHERE \
name=%s AND size=%s", (part, size))
parts_inprod = fetchDict(cur)
if parts_inprod:
# Subtract parts being made from production queue
new_partsprod = parts_inprod[0]['qty'] - qty
# Remove entry because <0
if new_partsprod < 1:
cur.execute("DELETE FROM nail_queueParts WHERE \
name=%s AND size=%s", (part, size))
conn.commit()
# Update entry to new depleted quantity
# after accouting for newly produced parts
else:
cur.execute("UPDATE nail_queueParts SET qty=%s WHERE \
name=%s AND size=%s", (new_partsprod, part, size))
conn.commit()
# PARTS WITH COLORS
else:
# What quantity of this part already exists?
cur.execute("SELECT qty FROM nail_parts WHERE \
name=%s AND size=%s AND color=%s",
(part, size, color))
onhand = fetchDict(cur)
print(f"Fetching onhand parts...")
print(onhand)
# None, create new entry
if not onhand:
cur.execute("INSERT INTO nail_parts (name, size, color, qty) VALUES \
(%s, %s, %s, %s)", \
(part, size, color, qty))
conn.commit()
print(f"New {size} {color} {part} entry created with qty {qty}.")
# Update existing entry's quantity
else:
new_qty = onhand[0]['qty'] + qty
if new_qty < 1:
cur.execute("DELETE FROM nail_parts WHERE \
name=%s AND size=%s AND color=%s",
(part, size, color))
conn.commit()
else:
cur.execute("UPDATE nail_parts SET qty=%s WHERE \
name=%s AND size=%s AND color=%s",
(new_qty, part, size, color))
conn.commit()
print(f"Existing {size} {color} {part} inventory quantity updated from \
{onhand[0]['qty']} to {new_qty}.")
# Update production queue
# Identify matching part that is already in production
cur.execute("SELECT qty FROM nail_queueParts WHERE \
name=%s AND size=%s AND color=%s", (part, size, color))
parts_inprod = fetchDict(cur)
if parts_inprod:
# Subtract parts being made from production queue
new_partsprod = parts_inprod[0]['qty'] - qty
# Remove entry because <0
if new_partsprod < 1:
cur.execute("DELETE FROM nail_queueParts WHERE \
name=%s AND size=%s AND color=%s",
(part, size, color))
conn.commit()
# Update entry to new depleted quantity
# after accouting for newly produced parts
else:
cur.execute("UPDATE nail_queueParts SET qty=%s WHERE \
name=%s AND size=%s AND color=%s",
(new_partsprod, part, size, color))
conn.commit()
cur.close()
templates = gather_templates(conn)
build_production(conn, templates)
flash(f"Sucessfully created {qty} {size} {color} {part}")
return redirect(f'/parts/{color}')
@app.route('/items', methods=['GET', 'POST'])
@login_required
def items():
# https://www.psycopg.org/docs/usage.html
with psycopg2.connect(db) as conn:
with conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) as cur:
if request.method == 'GET':
templates = gather_templates(conn)
results = build_production(conn, templates)
print(f"progress results:{results}")
# cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
cur.execute("SELECT * FROM nail_queueItems \
ORDER BY size DESC, name ASC, qty DESC")
queue = fetchDict(cur)
cur.execute("SELECT * FROM nail_items \
ORDER BY size DESC, name ASC, qty DESC")
items = fetchDict(cur)
cur.close()
print("queue")
print(queue)
print("items")
print(items)
if not 'recent_item' in session :
session['recent_item'] = 'None'
print("session['recent_item'] = 'None'")
print(f"loading items{session}")
return render_template('items.html',
templates=templates,
items=items,
queue=queue,
recent=session['recent_item'])
# Upon POSTing form submission
else:
item = request.form.get("item")
size = request.form.get("size")
a = request.form.get("color_a")
b = request.form.get("color_b")
c = request.form.get("color_c")
if c == None:
c = ''
print("*" * 80)
print(f"c:{c}")
qty = int(request.form.get("qty"))
deplete = request.form.get("deplete")
# cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
# Force boolean state
if deplete != 'true':
deplete = 'false'
session['recent_item'] = {
'item': item,
'size': size,
'a': a,
'b': b,
'c': c,
'qty': qty,
'deplete': deplete
}
print(f"session['recent_item']:{session}")
print(f"deplete:{deplete}")
print("POST form with values:")
print(qty, item, size, a, b, c, deplete)
## Validation ##
# Return error if missing basic entries
if size is None:
flash("Invalid entry. Size required.")
return redirect("/items")
if a is None:
flash("Invalid entry. A color required.")
return redirect("/items")
if b is None:
flash("Invalid entry. B color required.")
return redirect("/items")
# Test for appropriateness of c_color presence
cur.execute("SELECT c FROM nail_loterias WHERE nombre=%s", (item,))
ctest = fetchDict(cur)
# No c is given
if not c:
# But there should be a c
if ctest[0]['c'] != '':
flash('Invalid entry. Color C required for this item.')
return redirect('/items')
# Superfulous c value is given
else:
if ctest[0]['c'] == '':
session['recent_item']['c'] = 'None'
flash('Invalid entry. Color C not required for this item.')
return redirect('/items')
# Validation complete. Now remove from parts and add to items.
if deplete == "true":
print(f"deplete == {deplete}")
# Deplete parts inventory
# Find parts names using item name
cur.execute("SELECT * FROM nail_loterias WHERE nombre=%s", (item,))
names = fetchDict(cur)
# Deplete backs
# Update inventory
cur.execute("SELECT qty FROM nail_parts WHERE name=%s AND size=%s",
(names[0]['backs'], size))
backs_onhand = fetchDict(cur)
if backs_onhand:
print(f'backs_onhand:{backs_onhand}')
new_qty = backs_onhand[0]['qty'] - qty
# Remove entry if update would be cause qty to be less than 1
if new_qty < 1:
cur.execute("DELETE FROM nail_parts WHERE name=%s AND size=%s",
(names[0]['backs'], size))
conn.commit()
# Update existing entry
else:
cur.execute("UPDATE nail_parts SET qty=%s WHERE name=%s AND size=%s",
(new_qty, names[0]['backs'], size))
conn.commit()
# Deplete a
# Update inventory
cur.execute("SELECT qty FROM nail_parts \
WHERE name=%s AND size=%s AND color=%s",
(names[0]['a'], size, a))
a_onhand = fetchDict(cur)
if a_onhand:
new_qty = a_onhand[0]['qty'] - qty
# Remove entry if update would be cause qty to be less than 1
if new_qty < 1:
cur.execute("DELETE FROM nail_parts \
WHERE name=%s AND size=%s AND color=%s",
(names[0]['a'], size, a))
conn.commit()
# Update existing entry
else:
cur.execute("UPDATE nail_parts SET qty=%s \
WHERE name=%s AND size=%s AND color=%s",
(new_qty, names[0]['a'], size, a))
conn.commit()
# Deplete b
# Update inventory
cur.execute("SELECT qty FROM nail_parts \
WHERE name=%s AND size=%s AND color=%s",
(names[0]['b'], size, b))
b_onhand = fetchDict(cur)
if b_onhand:
new_qty = b_onhand[0]['qty'] - qty
# Remove entry if update would be cause qty to be less than 1
if new_qty < 1:
cur.execute("DELETE FROM nail_parts \
WHERE name=%s AND size=%s AND color=%s",
(names[0]['b'], size, b))
conn.commit()
# Update existing entry
else:
cur.execute("UPDATE nail_parts SET qty=%s \
WHERE name=%s AND size=%s AND color=%s",
(new_qty, names[0]['b'], size, b))
conn.commit()
# Deplete c
if c:
# Update inventory
cur.execute("SELECT qty FROM nail_parts \
WHERE name=%s AND size=%s AND color=%s",
(names[0]['c'], size, c))
c_onhand = fetchDict(cur)
if c_onhand:
new_qty = c_onhand[0]['qty'] - qty
# Remove entry if update would be cause qty to be less than 1
if new_qty < 1:
cur.execute("DELETE FROM nail_parts \
WHERE name=%s AND size=%s AND color=%s",
(names[0]['c'], size, c))
conn.commit()
# Update existing entry
else:
cur.execute("UPDATE nail_parts SET qty=%s \
WHERE name=%s AND size=%s AND color=%s",
(new_qty, names[0]['c'], size, c))
conn.commit()
# How many items are already on hand?
# When c part exists, identify how many items exist in inventory
if c:
cur.execute("SELECT qty FROM nail_items \
WHERE name=%s AND size=%s AND a_color=%s AND b_color=%s AND c_color=%s",
(item, size, a, b, c))
items_onhand = fetchDict(cur)
# When no c part exists, identify number of items already onhand
else:
cur.execute("SELECT qty FROM nail_items \
WHERE name=%s AND size=%s AND a_color=%s AND b_color=%s",
(item, size, a, b))
items_onhand = fetchDict(cur)
print(f"items on hand: {items_onhand}")
# Make new item(s)
if not items_onhand and qty > 0:
cur.execute("INSERT INTO nail_items \
(name, size, a_color, b_color, c_color, qty) \
VALUES (%s, %s, %s, %s, %s, %s)",
(item, size, a, b, c, qty))
conn.commit()
# Update existing item quantity, deleting if new_qty == 0
else:
if items_onhand:
items_onhand = items_onhand[0]['qty']
else:
items_onhand = 0
new_qty = items_onhand + qty
if not c:
if new_qty <= 0:
cur.execute("DELETE FROM nail_items \
WHERE name=%s AND size=%s AND a_color=%s AND b_color=%s",
(item, size, a, b))
conn.commit()
else:
cur.execute("UPDATE nail_items SET qty=%s \
WHERE name=%s AND size=%s AND a_color=%s AND b_color=%s",
(new_qty, item, size, a, b))
conn.commit()
else:
if new_qty <= 0:
cur.execute("DELETE FROM nail_items \
WHERE name=%s AND size=%s AND \
a_color=%s AND b_color=%s AND c_color=%s",
(item, size, a, b, c))
conn.commit()
else:
cur.execute("UPDATE nail_items SET qty=%s \
WHERE name=%s AND size=%s AND \
a_color=%s AND b_color=%s AND c_color=%s", \
(new_qty, item, size, a, b, c))
conn.commit()
templates = gather_templates(conn)
build_production(conn, templates)
flash(f"Added to items inventory: {qty} {size} {item} ({a}, {b}, {c})")
cur.close()
return redirect('/items')
# TODO ensure negative values work as well here as in /items
@app.route('/projections', methods=['GET', 'POST'])
@login_required
def projections():
# https://www.psycopg.org/docs/usage.html
with psycopg2.connect(db) as conn:
with conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) as cur:
if request.method == 'GET':
# cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
# Check for "current" cycle
cur.execute("SELECT id, name, created_on FROM nail_cycles WHERE current='TRUE'")
active = fetchDict(cur)
current = active
print(f"current:{current}")
# Set newest cycle as "current" when there is none
if not active:
cur.execute("SELECT id FROM nail_cycles ORDER BY id DESC LIMIT 1")
newest = fetchDict(cur)
cur.execute("UPDATE nail_cycles SET current='true' \
WHERE id=%", (newest[0]['id'],))
conn.commit()
# Capture id of active "current" cycle
else:
active = active[0]['id']
print(f"active:{active}")
# List all available non-current cycles
cur.execute("SELECT id, name, created_on FROM nail_cycles WHERE current='FALSE'")
cycles = fetchDict(cur)
cur.execute("SELECT * FROM nail_projections")
all_projections = fetchDict(cur)
# Sum total for inactive cycles
for cycle in cycles:
cycle['total'] = 0
for projection in all_projections:
if projection['cycle'] == cycle['id']:
cycle['total'] += projection['qty']
# TODO fix active cycle summation above
# # Sum total for active cycle
# for projection in all_projections:
# if projection['cycle'] == current[0]['id']:
# current[0]['total'] += projection['qty']
print(f"cycles:{cycles}")
cur.execute("SELECT sum(qty) FROM nail_projections where cycle=%s", (active,))
total = fetchDict(cur)
templates = gather_templates(conn)
if not 'recent_projection' in session :
session['recent_projection'] = 'None'
# Select projections from current cycle only
cur.execute("SELECT * FROM nail_projections \
WHERE cycle=%s ORDER BY size DESC, name DESC, qty DESC", (active,))
projections = fetchDict(cur)
cur.close()
return render_template('projections.html',
templates=templates,
projections=projections,
current=current,
cycles=cycles,
total=total,
recent=session['recent_projection'])
# Upon POSTing form submission
else:
# cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
item = request.form.get("item")
size = request.form.get("size")
a = request.form.get("color_a")
b = request.form.get("color_b")
c = request.form.get("color_c")
qty = int(request.form.get("qty"))
print("input")
print(item, size, a, b, c, qty)
## Validation
# Return error if missing basic entries
if size == None:
flash("Invalid entry. Size required.")
return redirect('/projections')
if a == None:
flash("Invalid entry. Color A required.")
return redirect('/projections')
if b == None:
flash("Invalid entry. Color B required.")
return redirect('/projections')
# Test for presence of c_color
cur.execute("SELECT c FROM nail_loterias WHERE nombre=%s", (item,))
ctest = fetchDict(cur)
# No c is given
if not c:
# But there should be a c
if ctest[0]['c'] != '':
flash("Invalid entry. Color C required.")
return redirect('/projections')
# Superfulous c value is given
else:
if ctest[0]['c'] == '':
flash("Invalid entry. No C color for this item.")
return redirect('/projections')
session['recent_projection'] = {
'item': item,
'size': size,
'a': a,
'b': b,
'c': c,
'qty': qty,
}
itemdata = {
'name': item,
'size': size,
'a_color': a,
'b_color': b,
'c_color': c,
'qty': qty,
}
templates = gather_templates(conn)
sku = generate_sku(templates, itemdata)
print(f"sku:{sku}")
# Identify current cycle
cur.execute("SELECT id, name, created_on FROM nail_cycles WHERE current='TRUE'")
active = fetchDict(cur)
print(f"active cycle:{active}")
cycle = active[0]['id']
# What quantity of this item is already in projections?
if not c:
cur.execute("SELECT qty FROM nail_projections WHERE \
name=%s AND size=%s AND a_color=%s AND b_color=%s AND cycle=%s",
(item, size, a, b, cycle))
projected = fetchDict(cur)
else:
cur.execute("SELECT qty FROM nail_projections WHERE \
name=%s AND size=%s AND \
a_color=%s AND b_color=%s AND c_color=%s AND cycle=%s",
(item, size, a, b, c, cycle))
projected = fetchDict(cur)
print(f"Fetching projected ...")
print(projected)
# None, create new entry
if not projected:
cur.execute("INSERT INTO nail_projections \
(name, size, a_color, b_color, c_color, qty, cycle, sku) VALUES \
(%s, %s, %s, %s, %s, %s, %s, %s)",
(item, size, a, b, c, qty, cycle, sku))
conn.commit()
flash(f"Added to projections: {qty} {size} {item} ({a}, {b}, {c}) [{sku}]")
# Update existing entry's quantity
else:
updated = projected[0]['qty'] + qty
if not c:
if updated < 1:
cur.execute("DELETE FROM nail_projections WHERE \
name=%s AND size=%s AND a_color=%s AND b_color=%s AND cycle=%s",
(item, size, a, b, cycle))
conn.commit()
else:
cur.execute("UPDATE nail_projections SET qty=%s WHERE \
name=%s AND size=%s AND a_color=%s AND b_color=%s AND cycle=%s",
(updated, item, size, a, b, cycle))
conn.commit()
flash(f"Added to projections: {qty} {size} {item} ({a}, {b})")
else:
if updated < 1:
cur.execute("DELETE FROM nail_projections WHERE \
name=%s AND size=%s AND \
a_color=%s AND b_color=%s AND c_color=%s AND \
cycle=%s",
(item, size, a, b, c, cycle))
conn.commit()
else:
cur.execute("UPDATE nail_projections SET qty=%s WHERE \
name=%s AND size=%s AND a_color=%s AND b_color=%s AND c_color=%s \
AND cycle=%s", \
(updated, item, size, a, b, c, cycle))
conn.commit()
flash(f"Added to projections: {qty} {size} {item} ({a}, {b}, {c})")
print("Existing projection updated.")
cur.close()
build_production(conn, templates)
return redirect('/projections')
@app.route('/production', methods=['GET'])
@login_required
def production():
# https://www.psycopg.org/docs/usage.html
with psycopg2.connect(db) as conn:
# (RE)BUILD PRODUCTION TABLE
# Query for current cycle's projections
templates = gather_templates(conn)
build_production(conn, templates)