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 pathdatabase.py
More file actions
621 lines (502 loc) · 16.7 KB
/
Copy pathdatabase.py
File metadata and controls
621 lines (502 loc) · 16.7 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
"""
Handles all database setup and related database functions
"""
import os
import csv
import datetime
import psycopg2
import psycopg2.extras
from dotenv import load_dotenv
load_dotenv()
# HELPERS #
def tupleToDict(tuple_in):
"""
Converts tuple to dict for data format consistency
"""
result = []
for row in tuple_in:
result.append(dict(row._asdict()))
return result
def fetchDict(cur):
try:
result = tupleToDict(cur.fetchall())
# if os.getenv('FLASK_ENV') == "development": # Testing DB until migration
# print(f"fetchDict() returning:\n{result}")
return result
except Exception as e:
print(f"Fetch error {e}")
return None
def execDict(conn, query):
cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
if query.split[0] != "SELECT":
err = "Usage error, execDict query must be SELECT"
print(err)
return err
cur.execute(f"{query}")
result = fetchDict(cur)
print(f"execDict returning:\n{result}")
cur.close()
return result
# TEMPLATES #
def gather_templates(conn):
# Gather template data
cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
cur.execute("SELECT * FROM nail_loterias ORDER BY SKU ASC")
loterias = tupleToDict(cur.fetchall())
cur.execute("SELECT * FROM nail_shirts")
shirts = tupleToDict(cur.fetchall())
cur.execute("SELECT * FROM nail_colors")
colors = tupleToDict(cur.fetchall())
cur.execute("SELECT * FROM nail_sizes")
sizes = tupleToDict(cur.fetchall())
cur.execute("SELECT * FROM nail_types")
types = tupleToDict(cur.fetchall())
response = {
'loterias': loterias,
'shirts': shirts,
'colors': colors,
'sizes': sizes,
'types': types
}
conn.commit()
cur.close()
return response
def setup_loterias(conn):
with open('static/uploads/loterias.csv', 'r') as csvfile:
print('reading loterias.csv...', end='')
csv_reader = csv.reader(csvfile)
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS nail_loterias ( \
nombre VARCHAR (255) NOT NULL, \
a VARCHAR (255), \
b VARCHAR (255), \
c VARCHAR (255), \
backs VARCHAR (255), \
sku INTEGER \
)")
cur.execute("DELETE from nail_loterias")
next(csv_reader)
counter = 0
for row in csv_reader:
counter += 1
cur.execute("INSERT INTO nail_loterias (sku, nombre, a, b, c, backs) \
VALUES (%s, %s, %s, %s, %s, %s)",
(row[0], row[1], row[2], row[3], row[4], row[5]))
conn.commit()
cur.close()
return counter
# DATABASE #
def drop_tables(conn):
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS \
nail_colors, \
nail_sizes, \
nail_lotierias, \
nail_shirts, \
nail_types, \
nail_parts, \
nail_items, \
nail_boxes, \
nail_boxprod, \
nail_boxused, \
nail_projections, \
nail_queueParts, \
nail_queueItems, \
nail_cycles \
")
# nail_users, \
conn.commit()
cur.close
def initialize_database(conn):
print("initialize_database()...", end='')
cur = conn.cursor()
try:
setup_loterias(conn)
print("loterias setup.")
except Exception as e:
print("Error writing to database from loterias.csv. File may be missing.")
print(e)
# Users
cur.execute("CREATE TABLE IF NOT EXISTS nail_users ( \
id SERIAL NOT NULL, \
username VARCHAR ( 255 ) UNIQUE NOT NULL, \
password VARCHAR ( 255 ) NOT NULL, \
created_on TIMESTAMP, \
last_login TIMESTAMP \
)")
# Colors
cur.execute("CREATE TABLE IF NOT EXISTS nail_colors ( \
sku INTEGER, \
name VARCHAR ( 255 ), \
emoji VARCHAR ( 255 ), \
cssname VARCHAR ( 255 ) \
)")
colors = [
['black', '⬛', 'black'],
['red', '🟥', 'red'],
['TQ', '🟦', 'turquoise'],
['yellow', '🟨', 'yellow'],
['green', '🟩', 'green'],
['purple', '🟪', 'purple'],
['white', '⬜', 'white'],
['grey', '🔲', 'grey'],
['gold', '🥇', 'gold'],
['rose', '🌹', 'pink']
]
cur.execute("SELECT * FROM nail_colors")
color_data = cur.fetchall()
if not color_data:
for i in range(len(colors)):
cur.execute("INSERT INTO nail_colors (sku, name, emoji, cssname) \
VALUES (%s, %s, %s, %s)",
((i+1), colors[i][0], colors[i][1], colors[i][2]))
print("Colors setup.")
# Sizes
cur.execute("CREATE TABLE IF NOT EXISTS nail_sizes ( \
sku INTEGER NOT NULL, \
shortname VARCHAR ( 255 ), \
longname VARCHAR ( 255 ) \
)")
print("Size table setup.")
cur.execute("SELECT * FROM nail_sizes")
size_data = cur.fetchall()
if not size_data:
sizes = [['S', 'small'], ['M', 'medium'], ['L', 'large'], ['XL', 'XL'], ['2XL','2XL']]
for i in range(len(sizes)):
cur.execute("INSERT INTO nail_sizes (sku, shortname, longname) \
VALUES (%s, %s, %s)", ((i+1), sizes[i][0] , sizes[i][1]))
print("Size table populated.")
# Create table: recent
# cur.execute("CREATE TABLE IF NOT EXISTS nail_recent ( \
# user_id INTEGER, \
# projection VARCHAR ( 255 ), \
# item VARCHAR ( 255 ), \
# part VARCHAR ( 255 ), \
# PRIMARY KEY(user_id), \
# CONSTRAINT
# )")
# Parts
cur.execute("CREATE TABLE IF NOT EXISTS nail_parts ( \
name VARCHAR ( 255 ) NOT NULL, \
size VARCHAR ( 255 ) NOT NULL, \
color VARCHAR ( 255 ), \
qty INTEGER \
)")
print("Parts table setup.")
# Items
cur.execute("CREATE TABLE IF NOT EXISTS nail_items ( \
name VARCHAR ( 255 ) NOT NULL, \
size VARCHAR ( 255 ) NOT NULL, \
a_color VARCHAR ( 255 ), \
b_color VARCHAR ( 255 ), \
c_color VARCHAR ( 255 ), \
qty INTEGER \
)")
print("Items table setup.")
# Types
cur.execute("CREATE TABLE IF NOT EXISTS nail_types ( \
name VARCHAR ( 255 ), \
sku INTEGER \
)")
print("Products table setup.")
types = [
['Laser Cut', '0'],
['Tee Shirt', '1'],
['Tank Top', '2'],
['Hoodie', '3'],
['Screen Print', '10'],
['Greeting Card', '11']
]
cur.execute("SELECT * FROM nail_types")
types_data = cur.fetchall()
if not types_data:
for i in range(len(types)):
cur.execute("INSERT INTO nail_types (name, sku) VALUES (%s, %s)",
(types[i][0], types[i][1]))
print("Products table setup.")
# Shirts
# Reformat these tables to be more relational with types, depending on business needs
cur.execute("CREATE TABLE IF NOT EXISTS nail_shirts ( \
nombre VARCHAR ( 255 ) NOT NULL, \
a VARCHAR ( 255 ), \
b VARCHAR ( 255 ), \
c VARCHAR ( 255 ), \
backs VARCHAR ( 255 ), \
sku INTEGER \
)")
print("Shirts table setup.")
shirts = [
['ReSister', '55']
]
cur.execute("SELECT * FROM nail_shirts")
shirts_data = cur.fetchall()
if not shirts_data:
for i in range(len(shirts)):
cur.execute("INSERT INTO nail_shirts (nombre, sku) VALUES (%s, %s)",
(shirts[i][0], shirts[i][1]))
print("Shirts table populated.")
# Create table: boxes
cur.execute("CREATE TABLE IF NOT EXISTS nail_boxes ( \
name VARCHAR ( 255 ), \
qty INTEGER \
)")
# Create table: boxprod
cur.execute("CREATE TABLE IF NOT EXISTS nail_boxprod ( \
name VARCHAR ( 255 ), \
qty INTEGER \
)")
# Create table: boxused
cur.execute("CREATE TABLE IF NOT EXISTS nail_boxused ( \
name VARCHAR ( 255 ), \
qty INTEGER \
)")
# Create table: projections
cur.execute("CREATE TABLE IF NOT EXISTS nail_projections ( \
name VARCHAR ( 255 ) NOT NULL, \
size VARCHAR ( 255 ) NOT NULL, \
a_color VARCHAR ( 255 ), \
b_color VARCHAR ( 255 ), \
c_color VARCHAR ( 255 ), \
qty INTEGER, \
cycle INTEGER, \
sku BIGINT \
)")
# Create table: production (items)
cur.execute("CREATE TABLE IF NOT EXISTS nail_queueItems ( \
name VARCHAR ( 255 ) NOT NULL, \
size VARCHAR ( 255 ) NOT NULL, \
a_color VARCHAR ( 255 ), \
b_color VARCHAR ( 255 ), \
c_color VARCHAR ( 255 ), \
qty INTEGER, \
cycle INTEGER, \
sku BIGINT \
)")
# Create table: production (parts)
cur.execute("CREATE TABLE IF NOT EXISTS nail_queueParts ( \
name VARCHAR ( 255 ) NOT NULL, \
size VARCHAR ( 255 ) NOT NULL, \
color VARCHAR ( 255 ), \
qty INTEGER \
)")
# Create table: cycles
cur.execute("CREATE TABLE IF NOT EXISTS nail_cycles ( \
id SERIAL UNIQUE NOT NULL, \
name VARCHAR (255), \
created_on TIMESTAMP, \
current BOOL \
)")
# If empty cycles table
cur.execute("SELECT * FROM nail_cycles")
event_data = cur.fetchall()
if not event_data:
# Seed table with Default Event
time = datetime.datetime.utcnow().isoformat()
cur.execute("INSERT INTO nail_cycles (name, created_on, current) \
VALUES ('Default Event', %s, 'TRUE')", (time,))
conn.commit()
cur.close()
# MIGRATE #
def migrate_users(conn, source):
from cs50 import SQL
# Configure Heroku Postgres database
db = SQL(os.getenv('DATABASE_URL'))
# Migrates users from CS50 "db" to psycopg2 "conn"
try:
# get old users
users = db.execute("SELECT * FROM users")
users_formatted = []
i = 0
for user in users:
users_formatted.append([])
for col in user.values():
users_formatted[i].append(col)
i += 1
# add new users
cur = conn.cursor()
query = "INSERT INTO nail_users (id, username, password, created_on, last_login) VALUES %s"
psycopg2.extras.execute_values (
cur, query, users_formatted, template=None, page_size=100
)
conn.commit()
cur.close()
status = f"Migrated {i} users."
except Exception as e:
status = f"Unable to migrate. {e}"
return status
def migrate_events(conn):
cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
# get old cycles
cur.execute("SELECT name, created_on FROM nail_cycles")
cycles = fetchDict(cur)
cycles_formatted = []
i = 0
for cycle in cycles:
cycles_formatted.append([])
for col in cycle.values():
cycles_formatted[i].append(col)
i += 1
# get old projections
cur.execute("SELECT * FROM nail_projections")
projections = fetchDict(cur)
projections_formatted = []
i = 0
for projection in projections:
projections_formatted.append([])
for col in projection.values():
projections_formatted[i].append(col)
i += 1
# add new cycles
print("cycles formatted")
print(cycles_formatted)
query = "INSERT INTO nail_cycles (name, created_on) VALUES %s"
psycopg2.extras.execute_values (
cur, query, cycles_formatted, template=None, page_size=100
)
status = f"Migrated {i} cycles."
# add new projections
print("projetions formatted")
print(projections_formatted)
query = "INSERT INTO nail_projections \
(name, size, a_color, b_color, c_color, qty, cycle, sku) VALUES %s"
psycopg2.extras.execute_values (
cur, query, projections_formatted, template=None, page_size=100
)
conn.commit()
cur.close()
status = f"Migrated {i} projections."
return status
# RESTORE #
def restore_items(conn):
from helpers import parse_sku
cur = conn.cursor()
if os.getenv('FLASK_ENV') == 'development':
inventory = 'static/backups/test_items_inventory.csv'
else:
inventory = 'static/backups/items_inventory.csv'
with open(f'{inventory}', 'r') as csvfile:
csv_reader = csv.reader(csvfile)
total = 0
skipped = 0
cur.execute("DELETE FROM nail_items RETURNING *;")
deleted = len(cur.fetchall())
print(f"{deleted} items deleted.")
next(csv_reader)
for row in csv_reader:
total += 1
if row[0]:
sku = parse_sku(row[0])
print(f"Found:{sku}")
# TODO update to use SKU, not spreadsheet values
cur.execute("INSERT INTO nail_items \
(name, size, a_color, b_color, c_color, qty) VALUES (%s, %s, %s, %s, %s, %s)",
(row[1], row[2], row[3], row[4], row[5], row[7]))
else:
skipped += 1
conn.commit()
cur.close()
results = {
"deleted":deleted,
"skipped":skipped,
"total":total
}
return results
def restore_parts(conn):
from helpers import parse_skulet
cur = conn.cursor()
if os.getenv('FLASK_ENV') == 'development':
inventory = 'static/backups/test_parts_inventory.csv'
else:
inventory = 'static/backups/parts_inventory.csv'
with open(f'{inventory}', 'r') as csvfile:
csv_reader = csv.reader(csvfile)
total = 0
skipped = 0
cur.execute("DELETE FROM nail_parts RETURNING *;")
deleted = len(cur.fetchall())
print(f"{deleted} parts deleted.")
next(csv_reader)
for row in csv_reader:
total += 1
if row[0]:
sku = parse_skulet(row[0])
print(f"Found:{sku}")
# TODO update to use SKU not spreadsheet values
cur.execute("INSERT INTO nail_parts (name, size, color, qty) VALUES \
(%s, %s, %s, %s)", (row[1], row[2], row[3], row[4]))
else:
skipped += 1
conn.commit()
cur.close()
results = {
"deleted":deleted,
"skipped":skipped,
"total":total
}
return results
def restore_event(conn, event):
from helpers import parse_sku, generate_item
cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
templates = gather_templates(conn)
if os.getenv('FLASK_ENV') == 'development':
file = 'static/backups/backup_projections.csv'
else:
file = 'static/uploads/event.csv'
with open(f'{file}', 'r') as csvfile:
csv_reader = csv.reader(csvfile)
total = 0
added = 0
skipped = 0
errors = ''
err_lines = []
values = []
next(csv_reader)
for row in csv_reader:
total += 1
# SKU exists
if row[2]:
sku = parse_sku(row[2])
item = generate_item(templates, sku)
if 'error' in item.keys():
skipped += 1
err_lines.append(total + 1)
errors = f"{item['error']}"
continue
# flash(f"SKU Error: {item['error']}")
# return redirect('/admin') # harsh error handling
print(f"Item from production:{item}")
else:
skipped += 1
err_lines.append(total + 1)
values.append([])
values[added].append(item['item'])
values[added].append(item['size'])
values[added].append(item['a'])
values[added].append(item['b'])
values[added].append(item['c'])
values[added].append(row[7]) # quantity
values[added].append(event) # event cycle number
values[added].append(sku['sku'])
print(f"values:{values}")
added += 1
# values = sql_cat(values) # TODO delete this once functional with
# TODO ensure no duplicate SKUs
cur.execute("DELETE FROM nail_projections WHERE cycle=%s", (event,))
query = "INSERT INTO nail_projections \
(name, size, a_color, b_color, c_color, qty, cycle, sku) VALUES %s"
psycopg2.extras.execute_values (
cur, query, values, template=None, page_size=100
)
cur.execute("SELECT name FROM nail_cycles WHERE id=%s", (event,))
cycle_name = fetchDict(cur)
conn.commit()
cur.close()
results = {
'added':added,
'total':total,
'skipped':skipped,
'err_lines':err_lines,
'errors':errors,
'cycle_name':cycle_name
}
return results