-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathserver.py
1141 lines (955 loc) · 43 KB
/
server.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 csv
import tempfile
import jwt
from flask import render_template, Flask, request, session, send_file, url_for
import secrets
from datetime import datetime
import io
from jwt import PyJWTError
from werkzeug.exceptions import BadRequest
from werkzeug.utils import redirect
import pandas as pd
from microsetta_admin import metadata_util, upload_util
from microsetta_admin.config_manager import SERVER_CONFIG
from microsetta_admin._api import APIRequest
import importlib.resources as pkg_resources
TOKEN_KEY_NAME = 'token'
SEND_EMAIL_CHECKBOX_DEFAULT_NAME = 'send_email'
PUB_KEY = pkg_resources.read_text(
'microsetta_admin',
"authrocket.pubkey")
DUMMY_SELECT_TEXT = '-------'
RECEIVED_TYPE_DROPDOWN = \
[DUMMY_SELECT_TEXT, "Blood (skin prick)", "Saliva", "Stool",
"Sample Type Unclear (Swabs Included)"]
VALID_STATUS = "sample-is-valid"
NO_SOURCE_STATUS = "no-associated-source"
NO_ACCOUNT_STATUS = "no-registered-account"
NO_COLLECTION_INFO_STATUS = "no-collection-info"
INCONSISTENT_SAMPLE_STATUS = "sample-has-inconsistencies"
UNKNOWN_VALIDITY_STATUS = "received-unknown-validity"
STATUS_OPTIONS = [DUMMY_SELECT_TEXT, VALID_STATUS, NO_SOURCE_STATUS,
NO_ACCOUNT_STATUS, NO_COLLECTION_INFO_STATUS,
INCONSISTENT_SAMPLE_STATUS, UNKNOWN_VALIDITY_STATUS]
API_PROJECTS_URL = '/api/admin/projects'
def handle_pyjwt(pyjwt_error):
# PyJWTError (Aka, anything wrong with token) will force user to log out
# and log in again
return redirect('/logout')
def parse_jwt(token):
"""
Raises
------
jwt.PyJWTError
If the token is invalid
"""
decoded = jwt.decode(token, PUB_KEY, algorithms=['RS256'], verify=True)
return decoded
def build_login_variables():
# Anything that renders sitebase.html must pass down these variables to
# jinja2
token_info = None
if TOKEN_KEY_NAME in session:
# If user leaves the page open, the token can expire before the
# session, so if our token goes back we need to force them to login
# again.
token_info = parse_jwt(session[TOKEN_KEY_NAME])
vars = {
'endpoint': SERVER_CONFIG["endpoint"],
'ui_endpoint': SERVER_CONFIG["ui_endpoint"],
'authrocket_url': SERVER_CONFIG["authrocket_url"]
}
if token_info is not None:
vars['email'] = token_info['email']
return vars
def build_app():
# Create the application instance
app = Flask(__name__)
flask_secret = SERVER_CONFIG["FLASK_SECRET_KEY"]
if flask_secret is None:
print("WARNING: FLASK_SECRET_KEY must be set to run with gUnicorn")
flask_secret = secrets.token_urlsafe(16)
app.secret_key = flask_secret
app.config['SESSION_TYPE'] = 'memcached'
app.config['SESSION_COOKIE_NAME'] = 'session-microsetta-admin'
# Set mapping from exception type to response code
app.register_error_handler(PyJWTError, handle_pyjwt)
return app
app = build_app()
@app.context_processor
def utility_processor():
def format_timestamp(timestamp_str):
if not timestamp_str:
return "None"
datetime_obj = datetime.fromisoformat(timestamp_str)
return datetime_obj.strftime("%Y %B %d %H:%M:%S")
return dict(format_timestamp=format_timestamp)
@app.route('/')
def home():
return render_template('sitebase.html', **build_login_variables())
@app.route('/search', methods=['GET'])
def search():
return _search()
@app.route('/search/sample', methods=['GET', 'POST'])
def search_sample():
return _search('samples')
@app.route('/search/kit', methods=['GET', 'POST'])
def search_kit():
return _search('kit')
@app.route('/search/email', methods=['GET', 'POST'])
def search_email():
return _search('account')
def _search(resource=None):
if request.method == 'GET':
return render_template('search.html', **build_login_variables())
elif request.method == 'POST':
query = request.form['search_%s' % resource]
status, result = APIRequest.get(
'/api/admin/search/%s/%s' % (resource, query))
if status == 404:
result = {'error_message': "Query not found"}
return render_template('search_result.html',
**build_login_variables(),
result=result), 200
elif status == 200:
return render_template('search_result.html',
**build_login_variables(),
resource=resource,
result=result), 200
else:
return result
def _translate_nones(a_dict, do_none_to_str):
# Note: this ISN'T a deep copy. This function is NOT set up
# for recursing through a multi-layer dictionary
result = a_dict.copy()
for k, v in result.items():
if do_none_to_str and v is None:
result[k] = ""
elif not do_none_to_str and v == '':
result[k] = None
return result
def _get_projects(include_stats, is_active):
projects_uri = API_PROJECTS_URL + f"?include_stats={include_stats}"
if is_active is not None:
projects_uri += f"&is_active={is_active}"
status, projects_output = APIRequest.get(projects_uri)
if status >= 400:
result = {'error_message': f"Unable to load project list: "
f"{projects_uri}"}
else:
cleaned_projects = [_translate_nones(x, True) for x in
projects_output]
# if we're not using full project stats, sort
# alphabetically by project name
if not include_stats:
cleaned_projects = sorted(cleaned_projects,
key=lambda k: k['project_name'])
result = {'projects': cleaned_projects}
return status, result
@app.route('/manage_projects', methods=['GET', 'POST'])
def manage_projects():
result = None
is_active = request.args.get('is_active', None)
if request.method == 'POST':
model = {x: request.form[x] for x in request.form}
project_id = model.pop('project_id')
model['is_microsetta'] = model.get('is_microsetta', '') == 'true'
model['bank_samples'] = model.get('bank_samples', '') == 'true'
model = _translate_nones(model, False)
if project_id.isdigit():
# update (put) an existing project
action = "update"
status, api_output = APIRequest.put(
'{}/{}'.format(API_PROJECTS_URL, project_id),
json=model)
else:
# create (post) a new project
action = "create"
status, api_output = APIRequest.post(
API_PROJECTS_URL, json=model)
# if api post or put failed
if status >= 400:
result = {'error_message': f'Unable to {action} project.'}
# end if post
# if the above work (if any) didn't produce an error message, return
# the projects list
if result is None:
_, result = _get_projects(include_stats=True, is_active=is_active)
return render_template('manage_projects.html',
**build_login_variables(),
result=result), 200
@app.route('/email_stats', methods=['GET', 'POST'])
def email_stats():
_, result = _get_projects(include_stats=False, is_active=True)
projects = result.get('projects')
if request.method == 'GET':
project = request.args.get('project', None)
email = request.args.get('email')
if email is None:
# They want to search for emails, show them the search dialog
return render_template("email_stats_pulldown.html",
**build_login_variables(),
resource=None,
search_error=None,
projects=projects)
emails = [email, ]
elif request.method == 'POST':
project = request.form.get('project', None)
emails, upload_err = upload_util.parse_request_csv_col(
request,
'file',
'email'
)
if upload_err is not None:
return render_template('email_stats_pulldown.html',
**build_login_variables(),
resource=None,
search_error=[{'error': upload_err}],
projects=projects)
else:
raise BadRequest()
if project == "":
project = None
# de-duplicate
emails = list({e.lower() for e in emails})
status, result = APIRequest.post(
'/api/admin/account_email_summary',
json={
"emails": emails,
"project": project
})
if status != 200:
return render_template('email_stats_pulldown.html',
search_error=[{'error': result}],
resource=None,
**build_login_variables(),
projects=projects)
# At a minimum, our table will display these columns.
# We may show additional info depending on what comes back from the request
base_data_template = {
'email': 'XXX',
'summary': 'XXX',
'account_id': 'XXX',
'creation_time': 'XXX',
'kit_name': 'XXX',
'project': 'XXX',
'unclaimed-samples-in-kit': 0,
'never-scanned': 0,
'sample-is-valid': 0,
'no-associated-source': 0,
'no-registered-account': 0,
'no-collection-info': 0,
'sample-has-inconsistencies': 0,
'received-unknown-validity': 0
}
df = pd.DataFrame([base_data_template] + result)
df = df.drop(0) # remove the template row
numeric_cols = [
"unclaimed-samples-in-kit", "never-scanned", "sample-is-valid",
"no-associated-source", "no-registered-account", "no-collection-info",
"sample-has-inconsistencies", "received-unknown-validity"
]
df[numeric_cols] = df[numeric_cols].apply(pd.to_numeric)
df[numeric_cols] = df[numeric_cols].fillna(0)
def urlify_account_id(id_):
if pd.isnull(id_):
return "No associated account"
else:
ui_endpoint = SERVER_CONFIG['ui_endpoint']
account_url = f"{ui_endpoint}/accounts/{id_}"
return f'<a target="_blank" href="{account_url}">{id_}</a>'
# see https://stackoverflow.com/questions/20035518/insert-a-link-inside-a-pandas-table # noqa
df['account_id'] = df["account_id"].apply(urlify_account_id)
return render_template("email_stats_pulldown.html",
search_error=None,
resource=df,
**build_login_variables(),
projects=projects)
@app.route('/per_sample_summary', methods=['GET', 'POST'])
def per_sample_summary():
# get a list of all projects in the system
_, result = _get_projects(include_stats=False, is_active=True)
projects = result.get('projects')
# filter out any projects that don't belong to Microsetta
projects = [x for x in projects if x['is_microsetta'] is True]
# build a list of dictionaries with just the project id and the project
# name.
projects = [{'project_name': x['project_name'],
'project_id': x['project_id']} for x in projects]
# determine if user wants sample ids stripped
strip_sampleid = request.form.get('strip_sampleid', 'off')
strip_sampleid = strip_sampleid.lower() == 'on'
if request.method == 'GET':
# If user arrived via GET then they are either here w/out
# querying and they simply need the default webpage, or they are
# querying with either a list of barcodes, or with a project id.
# look for both parameters to determine which state we are in.
sample_barcode = request.args.get('sample_barcode')
project_id = request.args.get('project_id')
if sample_barcode is None and project_id is None:
# user just wants the default page.
return render_template('per_sample_summary.html',
resource=None,
projects=projects,
**build_login_variables())
if project_id is not None:
# user wants to get summaries on all samples in a project.
payload = {'project_id': project_id}
status, result = APIRequest.post('/api/admin/account_barcode_summa'
'ry?strip_sampleid=False',
json=payload)
if status == 200:
if result['partial_result'] is True:
unprocessed_barcodes = result['unprocessed_barcodes']
else:
unprocessed_barcodes = None
resource = pd.DataFrame(result['samples'])
order = ['sampleid', 'project', 'account-email',
'account-first-name', 'account-last-name',
'source-type', 'site-sampled', 'sample-date',
'sample-time', 'sample-status', 'sample-received',
'first-scan-status', 'first-scan-timestamp',
'latest-scan-status', 'latest-scan-timestamp',
'sample-has-inconsistencies', 'sample-is-valid',
'no-associated-source', 'no-collection-info',
'no-registered-account', 'received-unknown-validity',
'ffq-taken', 'ffq-complete', 'vioscreen_username',
'kit-id', 'outbound-tracking',
'inbound-tracking', 'daklapack-order-id'
]
order.extend(sorted(set(resource.columns) - set(order)))
resource = resource[order]
if unprocessed_barcodes:
return render_template('per_sample_summary.html',
resource=resource,
projects=projects,
error_message="Too many barcodes. S"
"erver processed only"
" the first 1000.",
**build_login_variables())
else:
return render_template('per_sample_summary.html',
resource=resource,
projects=projects,
**build_login_variables())
else:
return render_template('per_sample_summary.html',
resource=None,
projects=projects,
error_message=result,
**build_login_variables())
else:
search_field = request.form.get('search_field')
search_value = request.form.get('single_search')
uploaded_file = request.files.get('upload_list')
search_values = []
if uploaded_file:
file_content = io.TextIOWrapper(uploaded_file,
encoding='utf-8-sig')
csv_reader = csv.reader(file_content)
for row in csv_reader:
search_values.extend(row)
else:
search_values = [search_value] if search_value else []
payload = {}
payload[search_field] = search_values
# perform the main query.
status, result = APIRequest.post('/api/admin/account_barcode_summary?'
'strip_sampleid=%s' %
str(strip_sampleid),
json=payload)
if status == 200:
if result['partial_result'] is True:
unprocessed_barcodes = result['unprocessed_barcodes']
else:
unprocessed_barcodes = None
resource = pd.DataFrame(result['samples'])
if not resource.empty:
order = ['sampleid', 'project', 'account-email',
'account-first-name', 'account-last-name',
'source-type', 'site-sampled', 'sample-date',
'sample-time', 'sample-status', 'sample-received',
'first-scan-status', 'first-scan-timestamp',
'latest-scan-status', 'latest-scan-timestamp',
'sample-has-inconsistencies', 'sample-is-valid',
'no-associated-source', 'no-collection-info',
'no-registered-account', 'received-unknown-validity',
'ffq-taken', 'ffq-complete', 'vioscreen_username',
'kit-id', 'outbound-tracking',
'inbound-tracking', 'daklapack-order-id'
]
order.extend(sorted(set(resource.columns) - set(order)))
resource = resource[order]
else:
return render_template('per_sample_summary.html',
resource=resource,
projects=projects,
error_message="No sample found",
**build_login_variables())
if unprocessed_barcodes:
return render_template('per_sample_summary.html',
resource=resource,
projects=projects,
error_message="Too many barcodes. S"
"erver processed only"
" the first 1000.",
**build_login_variables())
else:
return render_template('per_sample_summary.html',
resource=resource,
projects=projects,
**build_login_variables())
else:
return render_template('per_sample_summary.html',
resource=None,
projects=projects,
error_message=result,
**build_login_variables())
def _get_by_sample_barcode(sample_barcodes, strip_sampleid, projects):
payload = {'sample_barcodes': sample_barcodes}
status, result = APIRequest.post('/api/admin/account_barcode_summary?'
'strip_sampleid=%s' % str(strip_sampleid),
json=payload)
if status == 200:
if result['partial_result'] is True:
unprocessed_barcodes = result['unprocessed_barcodes']
else:
unprocessed_barcodes = None
resource = pd.DataFrame(result['samples'])
order = ['sampleid', 'project', 'account-email',
'source-type', 'site-sampled', 'sample-status',
'sample-received', 'ffq-taken', 'ffq-complete',
'vioscreen_username']
order.extend(sorted(set(resource.columns) - set(order)))
resource = resource[order]
if unprocessed_barcodes:
return render_template('per_sample_summary.html',
resource=resource,
projects=projects,
error_message="Too many barcodes. S"
"erver processed only"
" the first 1000.",
**build_login_variables())
else:
return render_template('per_sample_summary.html',
resource=resource,
projects=projects,
**build_login_variables())
else:
return render_template('per_sample_summary.html',
resource=None,
projects=projects,
error_message=result,
**build_login_variables())
@app.route('/create_kits', methods=['GET', 'POST'])
def new_kits():
_, result = _get_projects(include_stats=False, is_active=True)
projects = result.get('projects')
if request.method == 'GET':
return render_template('create_kits.html',
error_message=result.get('error_message'),
projects=projects,
**build_login_variables())
elif request.method == 'POST':
num_kits = int(request.form['number_of_kits'])
num_samples = int(request.form['number_of_samples'])
prefix = request.form['prefix']
selected_project_ids = request.form.getlist('project_ids')
barcodes_container = []
# Determine if each sample slot was provided or is to be generated.
# We default to generating novel barcodes.
for i in range(1, num_samples+1):
barcode_file = request.files.get(f'upload_csv_{i}')
if barcode_file:
# Barcodes provided for this slot
barcodes = _read_csv_file(barcode_file)
else:
# Generate barcodes for this slot
barcodes = []
# Add this slot's barcodes (or empty list) to the container
barcodes_container.append(barcodes)
payload = {
'number_of_kits': num_kits,
'number_of_samples': num_samples,
'project_ids': selected_project_ids,
'barcodes': barcodes_container
}
if prefix:
payload['kit_id_prefix'] = prefix
status, result = APIRequest.post('/api/admin/create/kits',
json=payload)
if status != 201:
start_index = result.find("Key")
if start_index != -1:
error_message = result[start_index:]
error_message = error_message[:44]
else:
error_message = result
return render_template('create_kits.html',
error_message=error_message,
projects=projects,
**build_login_variables())
buf = io.StringIO()
payload = io.BytesIO()
kits = pd.DataFrame(result['created'])
for kit_index, row in kits.iterrows():
sample_barcodes = row['sample_barcodes']
for sample_index in range(len(sample_barcodes)):
kits.at[kit_index, f'barcode_{sample_index + 1}'] = \
sample_barcodes[sample_index]
kits.drop(columns='sample_barcodes', inplace=True)
kits.to_csv(buf, sep=',', index=False, header=True)
payload.write(buf.getvalue().encode('utf-8'))
payload.seek(0)
buf.close()
stamp = datetime.now().strftime('%d%b%Y-%H%M')
fname = f'kits-{stamp}.csv'
return send_file(payload, as_attachment=True,
download_name=fname,
mimetype='text/csv')
def _read_csv_file(file):
content = file.read().decode('utf-8-sig')
return [row[0] for row in csv.reader(io.StringIO(content),
skipinitialspace=True)
if row]
@app.route('/add_barcode_to_kit', methods=['GET', 'POST'])
def new_barcode_kit():
if request.method == 'GET':
return render_template('add_barcode_to_kit.html',
**build_login_variables())
elif request.method == 'POST':
if 'add_single_barcode' in request.form:
kit_ids = [request.form['kit_id']]
if 'user_barcode' in request.form:
# User provided a barcode
barcodes = [request.form['user_barcode']]
generate_barcodes = False
else:
# Generate barcode
barcodes = []
generate_barcodes = True
elif 'add_multiple_barcodes' in request.form:
kit_ids_file = request.files['kit_ids']
kit_ids = _read_csv_file(kit_ids_file)
if 'barcodes_file' in request.files:
# User provided barcodes
barcodes = _read_csv_file(request.files['barcodes_file'])
generate_barcodes = False
else:
# Generate barcodes
barcodes = []
generate_barcodes = True
payload = {
'kit_ids': kit_ids,
'barcodes': barcodes,
'generate_barcodes': generate_barcodes
}
status, result = APIRequest.post(
'/api/admin/add_barcodes_to_kits',
json=payload
)
if status != 201:
return render_template(
'add_barcode_to_kit.html',
error_message=result,
**build_login_variables()
)
with tempfile.NamedTemporaryFile(
mode='w',
delete=False,
newline=''
) as file:
writer = csv.writer(file)
writer.writerow(['Kit ID', 'Barcode'])
writer.writerows(result)
filename = file.name
timestamp = datetime.now().strftime('%d%b%Y-%H%M')
fname = f'kit_ids-barcodes-{timestamp}.csv'
return send_file(
filename,
as_attachment=True,
download_name=fname
)
def _check_sample_status(extended_barcode_info):
warning = None
in_microsetta_project = any(
[x['is_microsetta'] for x in extended_barcode_info['projects_info']])
# one warning to rule them all; check in order of precendence
if not in_microsetta_project:
warning = UNKNOWN_VALIDITY_STATUS
elif extended_barcode_info['account'] is None:
warning = NO_ACCOUNT_STATUS
elif extended_barcode_info['source'] is None:
warning = NO_SOURCE_STATUS
# collection datetime is used as the bellwether for the whole
# set of sample collection info because it is relevant to all
# kinds of samples (whereas previously used field, sample site, is not
# filled when environmental samples are returned).
elif extended_barcode_info['sample'].get('datetime_collected') is None:
warning = NO_COLLECTION_INFO_STATUS
return warning
# Set up handlers for the cases,
# GET to view the page,
# POST to update info for a barcode -AND (possibly)-
# email end user about the change in sample status,
def _scan_get(sample_barcode, update_error, observations):
# If there is no sample_barcode in the GET
# they still need to enter one in the box, so show empty page
if sample_barcode is None and observations is None:
return render_template('scan.html', **build_login_variables())
# Assuming there is a sample barcode, grab that sample's information
status, result = APIRequest.get(
'/api/admin/search/samples/%s' % sample_barcode)
# If we successfully grab it, show the page to the user
if status == 200:
# Process result in python because its easier than jinja2.
status_warning = _check_sample_status(result)
# check the latest scan to find the default sample_status for form
latest_status = DUMMY_SELECT_TEXT
if result['latest_scan']:
latest_status = result['latest_scan']['sample_status']
account = result.get('account')
events = []
if account:
event_status, event_result = APIRequest.get(
'/api/admin/events/accounts/%s' % account['id']
)
if event_status != 200:
raise Exception("Couldn't pull event history")
events = event_result
return render_template(
'scan.html',
**build_login_variables(),
barcode_info=result["barcode_info"],
projects_info=result['projects_info'],
scans_info=result['scans_info'],
latest_status=latest_status,
dummy_status=DUMMY_SELECT_TEXT,
status_options=STATUS_OPTIONS,
send_email=session.get(SEND_EMAIL_CHECKBOX_DEFAULT_NAME, True),
sample_info=result['sample'],
extended_info=result,
status_warning=status_warning,
update_error=update_error,
received_type_dropdown=RECEIVED_TYPE_DROPDOWN,
source=result['source'],
events=events,
observations=observations
)
elif status == 401:
# If we fail due to unauthorized, need the user to log in again
return redirect('/logout')
elif status == 404:
# If we fail due to not found, need to tell the user to pick a diff
# barcode
return render_template(
'scan.html',
**build_login_variables(),
search_error="Barcode %s Not Found" % sample_barcode,
update_error=update_error,
received_type_dropdown=RECEIVED_TYPE_DROPDOWN
)
else:
raise BadRequest()
def _scan_post_update_info(sample_barcode,
technician_notes,
sample_status,
action,
issue_type,
template,
received_type,
recorded_type,
observations):
###
# Bugfix Part 1 for duplicate emails being sent. Theory is that client is
# out of sync due to hitting back button after a scan has changed
# state.
# Can't test if client is up to date without ETags, so for right now,
# we just validate whether or not they should send an email, duplicating
# the client log. (This can still break with multiple admin clients,
# but that is unlikely at the moment.)
latest_status = None
# TODO: Replace this with ETags!
status, result = APIRequest.get(
'/api/admin/search/samples/%s' % sample_barcode)
if result['latest_scan']:
latest_status = result['latest_scan']['sample_status']
###
# Do the actual update
status, response = APIRequest.post(
'/api/admin/scan/%s' % sample_barcode,
json={
"sample_status": sample_status,
"technician_notes": technician_notes,
"observations": observations
}
)
# if the update failed, keep track of the error so it can be displayed
if status != 201:
update_error = response
return _scan_get(sample_barcode, update_error, observations)
else:
update_error = None
# If we're not supposed to send an email, go back to GET
if action != "send_email":
return _scan_get(sample_barcode, update_error, observations)
###
# Bugfix Part 2 for duplicate emails being sent.
if sample_status == latest_status:
# This is what we'll hit if javascript thinks it's updating status
# but is out of sync with the database.
update_error = "Ignoring Send Email, sample_status would " \
"not have been updated (Displayed page was out of " \
"sync)"
return _scan_get(sample_barcode, update_error, observations)
###
# This is what we'll hit if there are no email templates to send for
# the new sample status (or if we screw up javascript side :D )
if template is None:
update_error = "Cannot Send Email: No Issue Type Specified " \
"(or no issue types available)"
return _scan_get(sample_barcode, update_error, observations)
# Otherwise, send out an email to the end user
status, response = APIRequest.post(
'/api/admin/email',
json={
"issue_type": issue_type,
"template": template,
"template_args": {
"sample_barcode": sample_barcode,
"recorded_type": recorded_type,
"received_type": received_type
}
}
)
# if the email failed to send, keep track of the error
# so it can be displayed
if status != 200:
update_error = response
else:
update_error = None
return _scan_get(sample_barcode, update_error, observations)
def get_observations(sample_barcode):
status, result = APIRequest.get('/api/admin/scan/observations/%s'
% sample_barcode)
return result
@app.route('/scan', methods=['GET', 'POST'])
def scan():
# Now that the handlers are set up, parse the request to determine what
# to do.
# If its a get, grab the sample_barcode from the query string rather than
# form parameters
if request.method == 'GET':
sample_barcode = request.args.get('sample_barcode')
update_error = None
if sample_barcode is not None:
observations = get_observations(sample_barcode)
else:
observations = None
return _scan_get(sample_barcode, update_error, observations)
# If its a post, make the changes, then refresh the page
if request.method == 'POST':
# Without some extra ajax, we can't persist the send_email checkbox
# until they actually post the form
send_email = request.form.get('send_email', False)
session[SEND_EMAIL_CHECKBOX_DEFAULT_NAME] = send_email
sample_barcode = request.form['sample_barcode']
technician_notes = request.form['technician_notes']
sample_status = request.form['sample_status']
action = request.form.get('action')
issue_type = request.form.get('issue_type')
template = request.form.get('template')
received_type = request.form.get('received_type')
recorded_type = request.form.get('recorded_type')
observations = request.form.getlist('observation_id')
_scan_post_update_info(sample_barcode,
technician_notes,
sample_status,
action,
issue_type,
template,
received_type,
recorded_type,
observations)
return redirect(url_for('scan', sample_barcode=sample_barcode))
@app.route('/metadata_pulldown', methods=['GET', 'POST'])
def metadata_pulldown():
allow_missing = request.form.get('allow_missing_samples', False)
if request.method == 'GET':
sample_barcode = request.args.get('sample_barcode')
# If there is no sample_barcode in the GET
# they still need to enter one in the box, so show empty page
if sample_barcode is None:
return render_template('metadata_pulldown.html',
**build_login_variables())
sample_barcodes = [sample_barcode]
elif request.method == 'POST':
sample_barcodes, upload_err = upload_util.parse_request_csv_col(
request,
'file',
'sample_name'
)
if upload_err is not None:
return render_template('metadata_pulldown.html',
**build_login_variables(),
search_error=[{'error': upload_err}])
else:
raise BadRequest()
df, errors = metadata_util.retrieve_metadata(sample_barcodes)
# Strangely, these api requests are returning an html error page rather
# than a machine parseable json error response object with message.
# This is almost certainly due to error handling for the cohosted minimal
# client. In future, we should just pass down whatever the api says here.
if len(errors) == 0 or allow_missing:
df = metadata_util.drop_private_columns(df)
# TODO: Streaming direct from pandas is a pain. Need to search for
# better ways to iterate and chunk this file as we generate it
strstream = io.StringIO()
df.to_csv(strstream, sep='\t', index=True, header=True)
# TODO: utf-8 or utf-16 encoding??
bytestream = io.BytesIO()
bytestream.write(strstream.getvalue().encode('utf-8'))
bytestream.seek(0)
strstream.close()
return send_file(bytestream,
mimetype="text/tab-separated-values",
as_attachment=True,
download_name="metadata_pulldown.tsv",
etag=False,
max_age=None,
conditional=False,
last_modified=None,
)
else:
return render_template('metadata_pulldown.html',
**build_login_variables(),
info={'barcodes': sample_barcodes},
search_error=errors)
@app.route('/submit_daklapack_order', methods=['GET'])
def submit_daklapack_order():
error_msg_key = "error_message"
def return_error(msg):
return render_template('submit_daklapack_order.html',
**build_login_variables(),
error_message=msg)
status, dak_shipping_type_by_provider = APIRequest.get(
'/api/admin/daklapack_shipping')
if status >= 400:
return return_error("Unable to load daklapack shipping information.")