-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
2940 lines (2443 loc) · 106 KB
/
main.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
import sys
import jwt
import httpx
import os
import json
import subprocess
import shutil
from typing import List
from pathlib import Path
import random
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta, date
from dotenv import load_dotenv
load_dotenv(override=True)
# The following three lines allow for dropping embed() in to block and present an IPython shell
from IPython import embed
import nest_asyncio
nest_asyncio.apply()
import difflib
def get_clean_timestamp():
return datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
os.makedirs("logs", exist_ok=True)
import logging
from logging.handlers import RotatingFileHandler
def setup_logging():
# uvicorn to capture logs from all libs
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Define the log file name with a timestamp
log_filename = f"logs/bloomui_{get_clean_timestamp()}.log"
# Stream handler (to console)
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.INFO)
# File handler (to file, with rotation)
f_handler = RotatingFileHandler(log_filename, maxBytes=10485760, backupCount=5)
f_handler.setLevel(logging.INFO)
# Common log format
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(pathname)s:%(lineno)d"
)
c_handler.setFormatter(formatter)
f_handler.setFormatter(formatter)
# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)
setup_logging()
from fastapi import (
FastAPI,
Depends,
HTTPException,
status,
Request,
Response,
Form,
Query,
File,
UploadFile,
BackgroundTasks,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import APIKeyCookie
from fastapi.responses import HTMLResponse, RedirectResponse, FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.responses import JSONResponse
from starlette.middleware.sessions import SessionMiddleware
from sqlalchemy.orm.attributes import flag_modified
from sqlalchemy import func, text
from jinja2 import Environment, FileSystemLoader
from collections import defaultdict
from datetime import datetime, timedelta
from bloom_lims.db import BLOOMdb3
from bloom_lims.bobjs import (
BloomObj,
BloomWorkflow,
BloomWorkflowStep,
BloomFile,
BloomFileSet,
BloomFileReference
)
from bloom_lims.bvars import BloomVars
BVARS = BloomVars()
from auth.supabase.connection import create_supabase_client
# local udata prefernces
UDAT_FILE = "./etc/udat.json"
# Create if not exists
os.makedirs(os.path.dirname(UDAT_FILE), exist_ok=True)
if not os.path.exists(UDAT_FILE):
with open(UDAT_FILE, "w") as f:
json.dump({}, f)
# Initialize Jinja2 environment
templates = Environment(loader=FileSystemLoader("templates"))
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/templates", StaticFiles(directory="templates"), name="templates")
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
app.mount("/tmp", StaticFiles(directory="tmp"), name="tmp")
# Setup CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(SessionMiddleware, secret_key="your-secret-key")
# Serve static files
cookie_scheme = APIKeyCookie(name="session")
SKIP_AUTH = False if len(sys.argv) < 3 else True
class AuthenticationRequiredException(HTTPException):
def __init__(self, detail: str = "Authentication required"):
super().__init__(status_code=401, detail=detail)
class MissingSupabaseEnvVarsException(HTTPException):
def __init__(self, message="The Supabase environment variables are not found."):
super().__init__(status_code=401, detail=message)
def proc_udat(email):
with open(UDAT_FILE, "r+") as f:
user_data = json.load(f)
if email not in user_data:
user_data[email] = {"style_css": "static/skins/bloom.css", "email": email}
f.seek(0)
json.dump(user_data, f, indent=4)
f.truncate()
return user_data[email]
async def DELis_instance(value, type_name):
return isinstance(value, eval(type_name))
def get_well_color(quant_value):
# Transition from purple to white
if quant_value <= 0.5:
r = int(128 + 127 * (quant_value / 0.5)) # From 128 to 255
g = int(0 + 255 * (quant_value / 0.5)) # From 0 to 255
b = int(128 + 127 * (quant_value / 0.5)) # From 128 to 255
# Transition from white to green
else:
r = int(255 - 255 * ((quant_value - 0.5) / 0.5)) # From 255 to 0
g = 255
b = int(255 - 255 * ((quant_value - 0.5) / 0.5)) # From 255 to 0
return f"rgb({r}, {g}, {b})"
def highlight_json_changes(old_json_str, new_json_str):
try:
old_json = json.loads(old_json_str)
new_json = json.loads(new_json_str)
except json.JSONDecodeError:
return old_json_str, new_json_str
old_json_formatted = json.dumps(old_json, indent=2)
new_json_formatted = json.dumps(new_json, indent=2)
diff = difflib.ndiff(old_json_formatted.splitlines(), new_json_formatted.splitlines())
old_json_highlighted = []
new_json_highlighted = []
for line in diff:
if line.startswith("- "):
old_json_highlighted.append(f'<span class="deleted">{line[2:]}</span>')
elif line.startswith("+ "):
new_json_highlighted.append(f'<span class="added">{line[2:]}</span>')
elif line.startswith(" "):
old_json_highlighted.append(line[2:])
new_json_highlighted.append(line[2:])
return '\n'.join(old_json_highlighted), '\n'.join(new_json_highlighted)
async def get_relationship_data(obj):
relationship_data = {}
for relationship in obj.__mapper__.relationships:
if relationship.uselist: # If it's a list of items
relationship_data[relationship.key] = [
{
"child_instance_euid": (
rel_obj.child_instance.euid
if hasattr(rel_obj, "child_instance")
else []
),
"parent_instance_euid": (
rel_obj.parent_instance.euid
if hasattr(rel_obj, "parent_instance")
else []
),
"euid": rel_obj.euid,
"uuid": rel_obj.uuid,
"polymorphic_discriminator": rel_obj.polymorphic_discriminator,
"super_type": rel_obj.super_type,
"btype": rel_obj.btype,
"b_sub_type": rel_obj.b_sub_type,
"version": rel_obj.version,
}
for rel_obj in getattr(obj, relationship.key)
]
else: # If it's a single item
rel_obj = getattr(obj, relationship.key)
relationship_data[relationship.key] = [
(
{
"child_instance_euid": (
rel_obj.child_instance.euid
if hasattr(rel_obj, "child_instance")
else []
),
"parent_instance_euid": (
rel_obj.parent_instance.euid
if hasattr(rel_obj, "parent_instance")
else []
),
"euid": rel_obj.euid,
"uuid": rel_obj.uuid,
"polymorphic_discriminator": rel_obj.polymorphic_discriminator,
"super_type": rel_obj.super_type,
"btype": rel_obj.btype,
"b_sub_type": rel_obj.b_sub_type,
"version": rel_obj.version,
}
if rel_obj
else {}
)
]
return relationship_data
class RequireAuthException(HTTPException):
def __init__(self, detail: str):
super().__init__(status_code=403, detail=detail)
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
file_path = os.path.join("static", "favicon.ico")
return FileResponse(file_path)
@app.exception_handler(AuthenticationRequiredException)
async def authentication_required_exception_handler(
request: Request, exc: AuthenticationRequiredException
):
return RedirectResponse(url="/login")
async def require_auth(request: Request):
if (
os.environ.get("SUPABASE_URL", "NA") == "NA"
and os.environ.get("SUPABASE_KEY", "NA") == "NA"
):
msg = "SUPABASE_* env variables not not set. Is your .env file missing?"
logging.error(msg)
raise MissingSupabaseEnvVarsException(msg)
if "user_data" not in request.session:
raise AuthenticationRequiredException()
return request.session["user_data"]
@app.exception_handler(RequireAuthException)
async def auth_exception_handler(_request: Request, _exc: RequireAuthException):
# Redirect the user to the login page
return RedirectResponse(url="/login")
#
# The following are the mainpage / index and auth routes for the application
#
@app.get("/", response_class=HTMLResponse)
async def read_root(
request: Request,
):
count = request.session.get("count", 0)
count += 1
request.session["count"] = count
template = templates.get_template("index.html")
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
context = {"request": request, "style": style, "udat": user_data}
return HTMLResponse(content=template.render(context), status_code=200)
@app.get("/login", include_in_schema=False)
async def get_login_page(request: Request):
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
# Ensure you have this function defined, and it returns the expected style information
template = templates.get_template("login.html")
# Pass the 'style' variable in the context
context = {"request": request, "style": style, "udat": user_data, "supabase_url": os.getenv("SUPABASE_URL", "SUPABASE-URL-NOT-SET") }
return HTMLResponse(content=template.render(context))
@app.post("/oauth_callback")
async def oauth_callback(request: Request):
body = await request.json()
access_token = body.get("accessToken")
if not access_token:
return "No access token provided."
# Attempt to decode the JWT to get email
try:
decoded_token = jwt.decode(access_token, options={"verify_signature": False})
primary_email = decoded_token.get("email")
except jwt.DecodeError:
primary_email = None
# Fetch user email from GitHub if not present in decoded token
if not primary_email:
async with httpx.AsyncClient() as client:
headers = {"Authorization": f"Bearer {access_token}"}
response = await client.get(
"https://api.github.com/user/emails", headers=headers
)
if response.status_code == 200:
emails = response.json()
primary_email = next(
(email["email"] for email in emails if email.get("primary")), None
)
else:
raise HTTPException(
status_code=400, detail="Failed to retrieve user email from GitHub"
)
# Check if the email domain is allowed
whitelist_domains = os.getenv("SUPABASE_WHITELIST_DOMAINS", "all")
if len(whitelist_domains) == 0:
whitelist_domains = "all"
if whitelist_domains.lower() != "all":
allowed_domains = [domain.strip() for domain in whitelist_domains.split(",")]
user_domain = primary_email.split("@")[1]
if user_domain not in allowed_domains:
raise HTTPException(status_code=400, detail="Email domain not allowed")
request.session["user_data"] = proc_udat(
primary_email
) # {"email": primary_email, "style_css": "static/skins/bloom.css"}
# Redirect to home page or dashboard
return RedirectResponse(url="/", status_code=303)
@app.post("/login", include_in_schema=False)
async def login(request: Request, response: Response, email: str = Form(...)):
# Use a static password for simplicity (not recommended for production)
password = "notapplicable"
# Initialize the Supabase client
supabase = create_supabase_client()
if not email:
return JSONResponse(
content={"message": "Email is required"},
status_code=status.HTTP_400_BAD_REQUEST,
)
with open(UDAT_FILE, "r+") as f:
user_data = json.load(f)
if email not in user_data:
# The email is not in udat.json, attempt to sign up the user
auth_response = supabase.auth.sign_up(
{"email": email, "password": password}
)
if "error" in auth_response and auth_response["error"]:
# Handle signup error
return JSONResponse(
content={"message": auth_response["error"]["message"]},
status_code=status.HTTP_400_BAD_REQUEST,
)
else:
pass # set below via proc_udat
else:
# The email exists in udat.json, attempt to sign in the user
auth_response = supabase.auth.sign_in_with_password(
{"email": email, "password": password}
)
if "error" in auth_response and auth_response["error"]:
# Handle sign-in error
return JSONResponse(
content={"message": auth_response["error"]["message"]},
status_code=status.HTTP_400_BAD_REQUEST,
)
# Set session cookie after successful authentication, with a 60-minute expiration
response.set_cookie(
key="session", value="user_session_token", httponly=True, max_age=3600, path="/"
)
request.session["user_data"] = proc_udat(email)
# Redirect to the root path ("/") after successful login/signup
return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
# Add this line at the end of the /login endpoint
@app.get(
"/logout"
) # Using a GET request for simplicity, but POST is more secure for logout operations
async def logout(request: Request, response: Response):
try:
logging.warning(f"Logging out user: Clearing session data: {request.session}")
# Initialize the Supabase client
supabase = create_supabase_client()
# Get the user's access token
access_token = request.session.get("user_data", {}).get("access_token")
if access_token:
# Call the Supabase sign-out endpoint
headers = {"Authorization": f"Bearer {access_token}"}
async with httpx.AsyncClient() as client:
logging.debug(f"Logging out user: Calling Supabase logout endpoint")
response = await client.post(
os.environ.get("SUPABASE_URL", "NA") + "/auth/v1/logout",
headers=headers,
)
logging.debug(f"Logging out user: Supabase logout response: {response}")
if response.status_code != 204:
logging.error("Failed to log out from Supabase")
# Clear the session data
request.session.clear()
# Debug the session to ensure it's cleared
logging.warning(f"Session after clearing: {request.session}")
# Optionally, clear the session cookie.
# Note: This might not be necessary if your session middleware automatically handles it upon session.clear().
response.delete_cookie(key="session", path="/")
except Exception as e:
logging.error(f"Error during logout: {e}")
return JSONResponse(
content={"message": "An error occurred during logout: " + str(e)},
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
# Redirect to the homepage
return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
#
# The following are the main routes for the application
#
@app.get("/lims", response_class=HTMLResponse)
async def lims(request: Request, _=Depends(require_auth)):
count = request.session.get("count", 0)
count += 1
request.session["count"] = count
template = templates.get_template("lims_main.html")
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
context = {"request": request, "style": style, "udat": user_data}
return HTMLResponse(content=template.render(context), status_code=200)
@app.get("/assays", response_class=HTMLResponse)
async def assays(request: Request, show_type: str = "all", _auth=Depends(require_auth)):
# Check if user is logged in
if (
"user_data" not in request.session
or "email" not in request.session["user_data"]
):
# If not logged in, redirect to the login page
return RedirectResponse(url="/login")
user_email = request.session["user_data"]["email"]
user_data = request.session.get("user_data", {})
# Initialize your database object with the user's email
bobdb = BloomObj(BLOOMdb3(app_username=user_email))
ay_ds = {}
print("\n\n\nAAAAAAAA\n\n\n")
for i in (
bobdb.session.query(bobdb.Base.classes.workflow_instance)
.filter_by(is_deleted=False, is_singleton=True)
.all()
):
if show_type == "all" or i.json_addl.get("assay_type", "all") == show_type:
ay_ds[i.euid] = i
print("\n\n\n\n\nBBBBBB\n\n\n\n")
assays = []
ay_dss = {}
atype = {}
if show_type == "assay":
atype["type"] = "Assays"
elif show_type == "accessioning":
atype["type"] = "Accessioning"
else:
atype["type"] = "All Assays, etc"
for i in sorted(ay_ds.keys()):
assays.append(ay_ds[i])
ay_dss[i] = {
"Instantaneous COGS": 0
} # round(bobdb.get_cost_of_euid_children(i),2)}
ay_dss[i]["tot"] = 0
ay_dss[i]["tit_s"] = 0
ay_dss[i]["tot_fx"] = 0
for q in ay_ds[i].parent_of_lineages:
if show_type == "accessioning":
for fex_tup in bobdb.query_all_fedex_transit_times_by_ay_euid(
q.child_instance.euid
):
try:
ay_dss[i]["tit_s"] += float(fex_tup[1])
ay_dss[i]["tot_fx"] += 1
except Exception as e:
print(e)
wset = ""
n = q.child_instance.json_addl["properties"]["name"]
if n.startswith("In"):
wset = "inprog"
elif n.startswith("Comple"):
wset = "complete"
elif n.startswith("Exception"):
wset = "exception"
elif n.startswith("Ready"):
wset = "avail"
lins = q.child_instance.parent_of_lineages.all()
ay_dss[i][wset] = len(lins)
lctr = 0
lctr_max = 150
for llin in lins:
if lctr > lctr_max:
break
else:
ay_dss[i]["Instantaneous COGS"] += round(
bobdb.get_cost_of_euid_children(llin.child_instance.euid), 2
)
ay_dss[i]["tot"] += 1
lctr += 1
try:
ay_dss[i]["avg_d_fx"] = round(
float(ay_dss[i]["tit_s"])
/ 60.0
/ 60.0
/ 24.0
/ float(ay_dss[i]["tot_fx"]),
2,
)
except Exception as e:
ay_dss[i]["avg_d_fx"] = "na"
ay_dss[i]["conv"] = (
round(
float(ay_dss[i]["complete"])
/ float(ay_dss[i]["complete"] + ay_dss[i]["exception"]),
2,
)
if ay_dss[i]["complete"] + ay_dss[i]["exception"] > 0
else "na"
)
ay_dss[i]["wsetp"] = (
round(float(ay_dss[i]["Instantaneous COGS"]) / float(ay_dss[i]["tot"]), 2)
if ay_dss[i]["tot"] > 0
else "na"
)
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
# Rendering the template with the dynamic content
content = templates.get_template("assay.html").render(
style=style,
user_logged_in=True,
assays_data=ay_ds,
atype=atype,
workflow_instances=assays, # Assuming this is needed based on your template logic
ay_stats=ay_dss, # Assuming this is needed based on your template logic
udat=user_data,
)
return HTMLResponse(content=content)
@app.get("/calculate_cogs_children")
async def Acalculate_cogs_children(euid, request: Request, _auth=Depends(require_auth)):
try:
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
cogs_value = round(bobdb.get_cost_of_euid_children(euid), 2)
return json.dumps({"success": True, "cogs_value": cogs_value})
except Exception as e:
return json.dumps({"success": False, "message": str(e)})
@app.post("/query_by_euids", response_class=HTMLResponse)
async def query_by_euids(request: Request, file_euids: str = Form(...)):
try:
bfi = BloomFile(BLOOMdb3(app_username=request.session["user_data"]["email"]))
euid_list = [euid.strip() for euid in file_euids.split("\n") if euid.strip()]
detailed_results = [bfi.get_by_euid(euid) for euid in euid_list if euid]
# Create a list of columns for the table
columns = ["EUID", "Date Created", "Status"]
if detailed_results and detailed_results[0].json_addl.get("properties"):
columns += list(detailed_results[0].json_addl["properties"].keys())
# Prepare the data for the template
table_data = []
for result in detailed_results:
row = {
"EUID": result.euid,
"Date Created": result.created_dt.strftime("%Y-%m-%d %H:%M:%S"),
"Status": result.bstatus,
}
for key in columns[3:]:
row[key] = result.json_addl["properties"].get(key, "N/A")
table_data.append(row)
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
content = templates.get_template("search_results.html").render(
request=request,
columns=columns,
table_data=table_data,
style=style,
udat=user_data,
)
return HTMLResponse(content=content)
except Exception as e:
logging.error(f"Error querying files: {e}", exc_info=True)
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
content = templates.get_template("search_error.html").render(
request=request,
error=f"An error occurred: {e}",
style=style,
udat=user_data,
)
return HTMLResponse(content=content)
async def calculate_cogs_parents(euid, request: Request, _auth=Depends(require_auth)):
try:
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]))
cogs_value = round(bobdb.get_cogs_to_produce_euid(euid), 2)
return json.dumps({"success": True, "cogs_value": cogs_value})
except Exception as e:
return json.dumps({"success": False, "message": str(e)})
@app.get("/set_filter")
async def set_filter(request: Request, _auth=Depends(require_auth), curr_val="off"):
if curr_val == "off":
request.session["user_data"]["wf_filter"] = "on"
else:
request.session["user_data"]["wf_filter"] = "off"
@app.get("/admin", response_class=HTMLResponse)
async def admin(request: Request, _auth=Depends(require_auth), dest="na"):
os.makedirs(os.path.dirname(UDAT_FILE), exist_ok=True)
if not os.path.exists(UDAT_FILE):
with open(UDAT_FILE, "w") as f:
json.dump({}, f)
dest_section = {"section": dest}
user_data = request.session.get("user_data", {})
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]), cfg_printers=True,cfg_fedex=True)
# Mock or real printer_info data
if "print_lab" in user_data:
bobdb.get_lab_printers(user_data["print_lab"])
csss = []
for css in sorted(os.popen("ls -1 static/skins/*css").readlines()):
csss.append(css.rstrip())
printer_info = {
"print_lab": bobdb.printer_labs,
"printer_name": bobdb.site_printers,
"label_zpl_style": bobdb.zpl_label_styles,
"style_css": csss,
}
csss = [
"static/skins/" + os.path.basename(css) for css in csss
] # Get just the file names
printer_info["style_css"] = csss
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
# Rendering the template with the dynamic content
content = templates.get_template("admin.html").render(
style=style,
user_logged_in=True,
user_data=user_data,
printer_info=printer_info,
dest_section=dest_section,
udat=request.session["user_data"],
)
return HTMLResponse(content=content)
# Take a look at this later
@app.post("/update_preference")
async def update_preference(request: Request, auth: dict = Depends(require_auth)):
# Early return if auth is None or doesn't contain 'email'
if not auth or "email" not in auth:
return {
"status": "error",
"message": "Authentication failed or user data missing",
}
data = await request.json()
key = data.get("key")
value = data.get("value")
if not os.path.exists(UDAT_FILE):
return {"status": "error", "message": "User data file not found"}
with open(UDAT_FILE, "r") as f:
user_data = json.load(f)
email = request.session.get("user_data", {}).get("email")
if email in user_data:
user_data[email][key] = value
with open(UDAT_FILE, "w") as f:
json.dump(user_data, f)
request.session["user_data"][key] = value
return {"status": "success", "message": "User preference updated"}
else:
return {"status": "error", "message": "User not found in user data"}
@app.get("/queue_details", response_class=HTMLResponse)
async def queue_details(
request: Request, queue_euid, page=1, _auth=Depends(require_auth)
):
page = int(page)
if page < 1:
page = 1
per_page = 500 # Items per page
user_logged_in = True if "user_data" in request.session else False
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
queue = bobdb.get_by_euid(queue_euid)
qm = []
for i in queue.parent_of_lineages:
qm.append(i.child_instance)
queue_details = queue.sort_by_euid(qm)
queue_details = queue_details[(page - 1) * per_page : page * per_page]
pagination = {"next": page + 1, "prev": page - 1, "euid": queue_euid}
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
content = templates.get_template("queue_details.html").render(
style=style,
queue=queue,
queue_details=queue_details,
pagination=pagination,
user_logged_in=user_logged_in,
udat=request.session["user_data"],
)
return HTMLResponse(content=content)
@app.post("/generic_templates")
async def generic_templates(request: Request, _auth=Depends(require_auth)):
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
the_templates = (
bobdb.session.query(bobdb.Base.classes.generic_template)
.filter_by(is_deleted=False)
.all()
)
# Group templates by super_type
grouped_templates = {}
for temp in the_templates:
if temp.super_type not in grouped_templates:
grouped_templates[temp.super_type] = []
grouped_templates[temp.super_type].append(temp)
return HTMLResponse(grouped_templates)
@app.get("/workflow_summary", response_class=HTMLResponse)
async def workflow_summary(request: Request, _auth=Depends(require_auth)):
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
workflows = (
bobdb.session.query(bobdb.Base.classes.workflow_instance)
.filter_by(is_deleted=False)
.all()
)
workflow_statistics = defaultdict(
lambda: {
"status_counts": defaultdict(int),
"oldest": datetime.max.date(),
"newest": datetime.min.date(),
}
)
for wf in workflows:
wf_type = wf.btype
wf_status = wf.bstatus
wf_created_dt = wf.created_dt.date()
stats = workflow_statistics[wf_type]
stats["status_counts"][wf_status] += 1
stats["oldest"] = min(stats["oldest"], wf_created_dt)
stats["newest"] = max(stats["newest"], wf_created_dt)
workflow_statistics = {k: dict(v) for k, v in workflow_statistics.items()}
unique_workflow_types = list(workflow_statistics.keys())
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
content = templates.get_template("workflow_summary.html").render(
style=style,
workflows=workflows,
workflow_statistics=workflow_statistics,
unique_workflow_types=unique_workflow_types,
udat=request.session["user_data"],
)
return HTMLResponse(content=content)
@app.get("/update_object_name", response_class=HTMLResponse)
async def update_object_name(request: Request, euid, name, _auth=Depends(require_auth)):
referer = request.headers.get("Referer", "/")
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
obj = bobdb.get_by_euid(euid)
if obj:
obj.name = name # Update the name
flag_modified(obj, "name") # Explicitly mark the object as modified
bobdb.session.commit() # Commit the changes to the database
# Return a RedirectResponse to redirect the user
return RedirectResponse(url=referer, status_code=303)
@app.get("/equipment_overview", response_class=HTMLResponse)
async def equipment_overview(request: Request, _auth=Depends(require_auth)):
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
# Fetch equipment instances and templates
equipment_instances = (
bobdb.session.query(bobdb.Base.classes.equipment_instance)
.filter_by(is_deleted=False)
.all()
)
equipment_templates = (
bobdb.session.query(bobdb.Base.classes.equipment_template)
.filter_by(is_deleted=False)
.all()
)
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
content = templates.get_template("equipment_overview.html").render(
style=style,
equipment_list=equipment_instances,
template_list=equipment_templates,
udat=request.session["user_data"],
)
return HTMLResponse(content=content)
async def get_print_labs(_request: Request, _auth=Depends(require_auth)):
# Replace the following line with the actual logic to retrieve your data
options = [
{"value": "option1", "text": "Option 1"},
{"value": "option2", "text": "Option 2"},
{"value": "option3", "text": "Option 3"},
# Add more options as needed
]
return options
@app.get("/reagent_overview", response_class=HTMLResponse)
async def reagent_overview(request: Request, _auth=Depends(require_auth)):
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
# Fetch equipment instances and templates
reagent_instances = (
bobdb.session.query(bobdb.Base.classes.content_instance)
.filter_by(is_deleted=False, btype="reagent")
.all()
)
reagent_templates = (
bobdb.session.query(bobdb.Base.classes.content_template)
.filter_by(is_deleted=False, btype="reagent")
.all()
)
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
content = templates.get_template("reagent_overview.html").render(
style=style,
instance_list=reagent_instances,
template_list=reagent_templates,
udat=request.session["user_data"],
)
return HTMLResponse(content=content)
@app.get("/control_overview", response_class=HTMLResponse)
async def control_overview(request: Request, _auth=Depends(require_auth)):
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
# Fetch equipment instances and templates
control_instances = (
bobdb.session.query(bobdb.Base.classes.content_instance)
.filter_by(is_deleted=False, btype="control")
.all()
)
control_templates = (
bobdb.session.query(bobdb.Base.classes.content_template)
.filter_by(is_deleted=False, btype="control")
.all()
)
user_data = request.session.get("user_data", {})
style = {"skin_css": user_data.get("style_css", "static/skins/bloom.css")}
content = templates.get_template("control_overview.html").render(
style=style,
instance_list=control_instances,
template_list=control_templates,
udat=request.session["user_data"],
)
return HTMLResponse(content=content)
@app.post("/create_from_template", response_class=HTMLResponse)
@app.get("/create_from_template", response_class=HTMLResponse)
async def create_from_template(
request: Request, euid: str = None, _auth=Depends(require_auth)
):
bobdb = BloomObj(BLOOMdb3(app_username=request.session["user_data"]["email"]))
template = bobdb.create_instances(euid)
if template:
return RedirectResponse(