-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormsManager.py
2962 lines (1958 loc) · 121 KB
/
FormsManager.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
try:
import sys
import os
from json import loads as json_loads
from json import dumps as json_dumps
import pysodium
from base64 import b64decode, b64encode
from datetime import datetime
from urllib.parse import unquote
from random import randint
import db.ChecklistConfig as cfg
from FormsEnum import *
from datetime import datetime
def dict_factory(cursor, row):
return {col[0]: row[idx] for idx, col in enumerate(cursor.description)}
all_commands = {"get_main_forms", "get_class_forms", "get_sample_forms",
"add_main_form", "add_class_form", "add_sample_form",
"copy_main_form", "copy_class_form", "copy_sample_form",
"delete_main_form", "delete_class_form", "delete_sample_form",
"delete_selected_class_forms", "delete_selected_sample_forms",
"get_all_class_forms", "get_all_sample_forms",
"import_class_forms", "import_sample_forms",
"complete_partial_form",
"export_report", "import_report",
"get_pdf", "publish", "get_public_link",
"get_form_content", "update_form_content",
"export_samples", "export_selected_samples", "import_samples",
"export_lipid_class", "export_selected_lipid_classes", "import_lipid_class",
"get_fragment_suggestions", "get_published_forms"}
conn = None
table_prefix = "TCrpQ_"
version = cfg.version
path_name = "lipidomics-checklist"
main_form_id = "checklist"
class_form_id = "lipid-class"
sample_form_id = "sample"
partial_label = "partial"
completed_label = "completed"
published_label = "published"
workflow_types = {"di", "sep", "img"}
form_types = {"main": main_form_id,
"class": class_form_id,
"sample": sample_form_id
}
def copy_form(original_form, new_form):
original_fields = {}
def fill_fields(form, original_fields):
if type(form) == list:
for element in form: fill_fields(element, original_fields)
elif type(form) == dict:
if "name" in form: original_fields[form["name"]] = form
for k, v in form.items():
fill_fields(v, original_fields)
fill_fields(original_form, original_fields)
def copy_fields(form, original_fields):
if type(form) == list:
for element in form: copy_fields(element, original_fields)
elif type(form) == dict:
if "name" in form:
form_name = form["name"]
if form_name in original_fields:
orig_field = original_fields[form_name]
if (("type" not in form and "type" not in orig_field) or form["type"] == orig_field["type"]) and "value" in form and "value" in orig_field:
form["value"] = orig_field["value"]
for k, v in form.items():
copy_fields(v, original_fields)
copy_fields(new_form, original_fields)
def dbconnect():
try:
from sqlite3 import connect as sqlite3_connect
conn = sqlite3_connect(cfg.db_file)
conn.row_factory = dict_factory
curr = conn.cursor()
except Exception as e:
print(str(ErrorCodes.NO_DATABASE_CONNECTION) + " in dbconnect", e)
exit()
return conn, curr
def check_entry_id(entry_id, uid, db_cursor, form_type):
entry_id = int(entry_id)
uid = int(uid)
sql = "SELECT count(*) AS cnt FROM %sentries WHERE id = ? and form = ? and user_id = ?;" % table_prefix
db_cursor.execute(sql, (entry_id, form_types[form_type], uid))
request = db_cursor.fetchone()
return request["cnt"] != 0
def check_status(entry_id, uid, db_cursor, not_in = None, is_in = None):
global table_prefix
# checking if main form is partial or completed
sql = "SELECT * FROM %sentries WHERE user_id = ? AND id = ?;" % table_prefix
db_cursor.execute(sql, (uid, entry_id))
request = db_cursor.fetchone()
status = request["status"]
if not_in != None:
if status not in not_in:
print(str(ErrorCodes.PUBLISHED_ERROR) + " in check_state")
exit()
elif is_in != None:
if status in is_in:
print(str(ErrorCodes.PUBLISHED_ERROR) + " in check_state")
exit()
return status, request
def get_encrypted_entry(entry_id):
conn, db_cursor = dbconnect()
try:
message = bytes(str(entry_id), 'utf-8')
nonce = pysodium.randombytes(pysodium.crypto_stream_NONCEBYTES)
key = b64decode(cfg.encryption_key)
cipher = nonce + pysodium.crypto_secretbox(message, nonce, key)
return str(b64encode(cipher), "utf-8")
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_MAIN_FORMS) + " in get_encrypted_entry", e)
finally:
if conn is not None: conn.close()
def get_decrypted_entry(entry_id):
conn, db_cursor = dbconnect()
try:
message = bytes(str(entry_id), 'utf-8')
key = b64decode(cfg.encryption_key)
decoded_entry_id = b64decode(entry_id)
nonce = decoded_entry_id[:pysodium.crypto_stream_NONCEBYTES]
return str(pysodium.crypto_secretbox_open(decoded_entry_id[pysodium.crypto_stream_NONCEBYTES:], nonce, key), "utf-8")
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_MAIN_FORMS) + " in get_decrypted_entry", e)
finally:
if conn is not None: conn.close()
def get_content(request):
content = {}
for entry in request.split("&"):
tokens = entry.split("=")
if len(tokens) == 2:
content[tokens[0]] = unquote(tokens[1])
elif len(tokens) == 1:
content[tokens[0]] = ""
return content
if len(sys.argv) > 1:
content = get_content(sys.argv[1])
else:
print("ErrorCodes.NO_REQUEST_CONTENT")
exit()
if "request_file" in content:
with open(content["request_file"], "rt") as request_file:
request = request_file.read()
os.remove(content["request_file"])
content = get_content(request)
if len(content) == 0:
print(str(ErrorCodes.NO_CONTENT) + " in main")
exit()
# check if manager command is present and valid
if "command" not in content:
print(str(ErrorCodes.NO_COMMAND_ARGUMENT) + " in main")
exit()
if content["command"] not in all_commands:
print(str(ErrorCodes.INVALID_COMMAND_ARGUMENT) + " in main")
exit()
def get_select_value(field, field_name, current_label):
if "label" in field and field["label"] == field_name and "choice" in field and len(field["choice"]) > 0:
for choice in field["choice"]:
if "label" in choice and "value" in choice and choice["value"] == 1:
return choice["label"]
return current_label
################################################################################
## get forms
################################################################################
if content["command"] == "get_main_forms":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
try:
# connect with the database
conn, db_cursor = dbconnect()
# getting all main forms
sql = "SELECT status, id, date, fields FROM %sentries WHERE form = ? AND user_id = ?;" % table_prefix
db_cursor.execute(sql, (main_form_id, uid))
request = db_cursor.fetchall()
type_to_name = {"di": "direct infusion", "sep": "separation", "img": "imaging"}
for entry in request:
entry["entry_id"] = get_encrypted_entry(entry["id"])
title = ""
entry["type"] = ""
entry["version"] = ""
if len(entry["fields"]) > 0:
field_data = json_loads(entry["fields"])
del entry["fields"]
if "version" in field_data: entry["version"] = field_data["version"]
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
if "label" in field and field["label"] == "Title of the study" and len(field["value"]) > 0:
title = field["value"]
elif "name" in field and field["name"] == "workflowtype" and len(field["value"]) > 0:
entry["type"] = field["value"]
if len(title) == 0: entry["title"] = "Untitled %s report" % (type_to_name[entry["type"]] if entry["type"] in type_to_name else "")
else: entry["title"] = title
entry["type"] = (type_to_name[entry["type"]] if entry["type"] in type_to_name else "").capitalize()
request.sort(key = lambda x: x["date"], reverse = True)
for entry in request:
try:
entry["date"] = datetime.fromisoformat(entry["date"]).strftime('%m/%d/%Y')
if len(entry["version"]) > 0: entry["date"] += " (%s)" % entry["version"]
except Exception as e:
pass
print(json_dumps(request))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_MAIN_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
if content["command"] == "get_published_forms":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
type_to_name = {"di": "direct infusion", "sep": "separation", "img": "imaging"}
try:
# connect with the database
conn, db_cursor = dbconnect()
# getting all main forms
sql = "SELECT id, date, fields FROM %sentries WHERE status = 'published';" % table_prefix
db_cursor.execute(sql)
request = db_cursor.fetchall()
for entry in request:
entry["entry_id"] = get_encrypted_entry(entry["id"])
del entry["id"]
entry["type"] = ""
entry["author"] = ""
title = ""
if len(entry["fields"]) > 0:
field_data = json_loads(entry["fields"])
del entry["fields"]
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
if "label" in field and field["label"] == "Title of the study" and len(field["value"]) > 0:
title = field["value"]
elif "name" in field and field["name"] == "principle_investigator" and len(field["value"]) > 0:
entry["author"] = field["value"]
elif "name" in field and field["name"] == "workflowtype" and len(field["value"]) > 0:
entry["type"] = field["value"]
if len(title) == 0: entry["title"] = "Untitled %s report" % (type_to_name[entry["type"]] if entry["type"] in type_to_name else "")
else: entry["title"] = title
entry["type"] = (type_to_name[entry["type"]] if entry["type"] in type_to_name else "").capitalize()
request.sort(key = lambda x: x["date"], reverse = True)
print(json_dumps(request))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_MAIN_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
elif content["command"] == "get_class_forms":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
# check if main form entry id is within the request and an integer
if "main_entry_id" not in content:
print(str(ErrorCodes.NO_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
main_entry_id = int(get_decrypted_entry(content["main_entry_id"]))
except:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
if main_entry_id < 0:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
# connect with the database
conn, db_cursor = dbconnect()
if not check_entry_id(main_entry_id, uid, db_cursor, "main"):
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
# getting all main forms
sql = "SELECT wpe.status, wpe.id, wpe.date, wpe.date, wpe.fields FROM %sconnect_lipid_class AS c INNER JOIN %sentries AS wpe ON c.class_form_entry_id = wpe.id WHERE c.main_form_entry_id = ? and wpe.form = ? AND wpe.user_id = ?;" % (table_prefix, table_prefix)
db_cursor.execute(sql, (main_entry_id, class_form_id, uid))
request = db_cursor.fetchall()
for entry in request:
entry["entry_id"] = get_encrypted_entry(entry["id"])
if len(entry["fields"]) > 0:
field_data = json_loads(entry["fields"])
del entry["fields"]
lipid_class, other_lipid_class, ion_type, pos_ion, neg_ion = "", "", "", "", ""
other_pos_ion, other_neg_ion = "", ""
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
lipid_class = get_select_value(field, "Lipid class", lipid_class)
pos_ion = get_select_value(field, "Type of positive (precursor)ion", pos_ion)
neg_ion = get_select_value(field, "Type of negative (precursor)ion", neg_ion)
ion_type = get_select_value(field, "Polarity mode", ion_type)
if "name" in field and field["name"] == "other_lipid_class" and "value" in field and len(field["value"]) > 0:
other_lipid_class = field["value"]
if "name" in field and field["name"] == "other_pos_ion" and "value" in field and len(field["value"]) > 0:
other_pos_ion = field["value"]
if "name" in field and field["name"] == "other_neg_ion" and "value" in field and len(field["value"]) > 0:
other_neg_ion = field["value"]
if len(other_pos_ion) > 0: pos_ion = other_pos_ion
if len(other_neg_ion) > 0: neg_ion = other_neg_ion
if lipid_class[:5].lower() == "other": lipid_class = other_lipid_class
ion = pos_ion if ion_type.lower() == "positive" else neg_ion
entry["title"] = "%s%s" % (lipid_class, ion)
print(json_dumps(request))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_CLASS_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
elif content["command"] == "get_sample_forms":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
# check if main form entry id is within the request and an integer
if "main_entry_id" not in content:
print(str(ErrorCodes.NO_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
main_entry_id = int(get_decrypted_entry(content["main_entry_id"]))
except:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
if main_entry_id < 0:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
# connect with the database
conn, db_cursor = dbconnect()
if not check_entry_id(main_entry_id, uid, db_cursor, "main"):
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
# getting all main forms
sql = "SELECT wpe.status, wpe.id, wpe.date, wpe.fields FROM %sconnect_sample AS c INNER JOIN %sentries AS wpe ON c.sample_form_entry_id = wpe.id WHERE c.main_form_entry_id = ? and wpe.form = ? AND wpe.user_id = ?;" % (table_prefix, table_prefix)
db_cursor.execute(sql, (main_entry_id, sample_form_id, uid))
request = db_cursor.fetchall()
for entry in request:
entry["entry_id"] = get_encrypted_entry(entry["id"])
entry["title"] = "Unspecified sample"
sample_type, sample_set = "", ""
if len(entry["fields"]) > 0:
field_data = json_loads(entry["fields"])
del entry["fields"]
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
if "label" in field and field["label"] == "Sample set name" and "value" in field and len(field["value"]) > 0:
sample_set = field["value"]
sample_type = get_select_value(field, "Sample type", sample_type)
if len(sample_type) > 0 and len(sample_set) > 0:
entry["title"] = "%s / %s" % (sample_set, sample_type)
print(json_dumps(request))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_SAMPLE_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
################################################################################
## get all secondary forms
################################################################################
elif content["command"] == "get_all_class_forms":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
try:
# connect with the database
conn, db_cursor = dbconnect()
# getting all main forms
sql = "SELECT wpe2.fields as main_fields, wpe.status, wpe.id, wpe.date, wpe.fields FROM %sconnect_lipid_class AS c INNER JOIN %sentries AS wpe ON c.class_form_entry_id = wpe.id INNER JOIN %sentries as wpe2 ON c.main_form_entry_id = wpe2.id WHERE wpe.form = ? AND wpe.user_id = ? AND wpe.status <> ? AND wpe2.status <> ?;" % (table_prefix, table_prefix, table_prefix)
db_cursor.execute(sql, (class_form_id, uid, partial_label, partial_label))
request = db_cursor.fetchall()
for entry in request:
entry["entry_id"] = get_encrypted_entry(entry["id"])
entry["main_title"] = "Untitled report"
if "main_fields" in entry and len(entry["main_fields"]) > 0:
field_data = json_loads(entry["main_fields"])
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
if "label" in field and field["label"] == "Title of the study" and len(field["value"]) > 0:
entry["main_title"] = field["value"]
del entry["main_fields"]
title = ["Unspecified class", "[M]", "No Instrument"]
if len(entry["fields"]) > 0:
field_data = json_loads(entry["fields"])
lipid_class = ""
other_lipid_class = ""
ion_type = ""
pos_ion = ""
neg_ion = ""
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
lipid_class = get_select_value(field, "Lipid class", lipid_class)
pos_ion = get_select_value(field, "Type of positive (precursor)ion", pos_ion)
neg_ion = get_select_value(field, "Type of negative (precursor)ion", neg_ion)
ion_type = get_select_value(field, "Polarity mode", ion_type)
if "label" in field and field["label"] == "Other Lipid class" and "value" in field and len(field["value"]) > 0:
other_lipid_class = field["value"]
if lipid_class[:5] == "other": lipid_class = other_lipid_class
ion = pos_ion if ion_type.lower() == "positive" else neg_ion
del entry["fields"]
entry["title"] = "%s%s" % (lipid_class, ion)
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_MAIN_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
print(json_dumps(request))
elif content["command"] == "get_all_sample_forms":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
# check if main form entry id is within the request and an integer
try:
# connect with the database
conn, db_cursor = dbconnect()
# getting all main forms
sql = "SELECT wpe2.fields as main_fields, wpe.status, wpe.id, wpe.date, wpe.fields FROM %sconnect_sample AS c INNER JOIN %sentries AS wpe ON c.sample_form_entry_id = wpe.id INNER JOIN %sentries as wpe2 ON c.main_form_entry_id = wpe2.id WHERE wpe.form = ? AND wpe.user_id = ? AND wpe.status <> ? AND wpe2.status <> ?;" % (table_prefix, table_prefix, table_prefix)
db_cursor.execute(sql, (sample_form_id, uid, partial_label, partial_label))
request = db_cursor.fetchall()
for entry in request:
entry["entry_id"] = get_encrypted_entry(entry["id"])
entry["main_title"], entry["title"] = "Untitled report", "Unspecified sample"
if "main_fields" in entry and len(entry["main_fields"]) > 0:
field_data = json_loads(entry["main_fields"])
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
if "label" in field and field["label"] == "Title of the study" and len(field["value"]) > 0:
entry["main_title"] = field["value"]
del entry["main_fields"]
if len(entry["fields"]) > 0:
field_data = json_loads(entry["fields"])
del entry["fields"]
sample_set_name = ""
sample_origin = ""
sample_type = ""
if len(field_data) > 0:
for field in field_data["pages"][0]["content"]:
if "label" in field and field["label"] == "Sample set name" and "value" in field and len(field["value"]) > 0:
sample_set_name = field["value"]
sample_type = get_select_value(field, "Sample type", sample_type)
sample_origin = get_select_value(field, "Sample origin", sample_origin)
if len(sample_set_name) > 0 and len(sample_origin) > 0 and len(sample_type) > 0:
entry["title"] = "%s / %s / %s" % (sample_set_name, sample_origin, sample_type)
print(json_dumps(request))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_GETTING_MAIN_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
################################################################################
## add forms
################################################################################
elif content["command"] == "add_main_form":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
if "workflow_type" not in content:
print(str(ErrorCodes.NO_WORKFLOW_TYPE) + " in %s" % content["command"])
exit()
if content["workflow_type"] not in workflow_types:
print(str(ErrorCodes.INCORRECT_WORKFLOW_TYPE) + " in %s" % content["command"])
exit()
workflow_type = content["workflow_type"]
# connect with the database
try:
conn, db_cursor = dbconnect()
field_template = json_loads(open("workflow-templates/checklist.json").read())
if "pages" in field_template and len(field_template["pages"]) > 0:
for field in field_template["pages"][0]["content"]:
if field["type"] == "hidden":
field["value"] = workflow_type
break
field_template["version"] = version
field_template = json_dumps(field_template)
# add main form entry
sql = "INSERT INTO %sentries (form, user_id, status, fields, date, user_uuid) VALUES (?, ?, 'partial', ?, DATETIME('now'), ?);" % table_prefix
values = (main_form_id, uid, field_template, user_uuid)
db_cursor.execute(sql, values)
conn.commit()
sql = "SELECT max(id) AS max_id FROM %sentries WHERE user_id = ? AND form = ?;" % table_prefix
db_cursor.execute(sql, (uid, main_form_id))
print(get_encrypted_entry(db_cursor.fetchone()["max_id"]))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_ADDING_MAIN_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
elif content["command"] == "add_class_form":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
# check if main form entry id is within the request and an integer
if "main_entry_id" not in content:
print(str(ErrorCodes.NO_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
main_entry_id = int(get_decrypted_entry(content["main_entry_id"]))
except:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
if main_entry_id < 0:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
# connect with the database
conn, db_cursor = dbconnect()
if not check_entry_id(main_entry_id, uid, db_cursor, "main"):
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
# checking if main form is partial or completed
status, request = check_status(main_entry_id, uid, db_cursor, not_in = {partial_label, completed_label})
field_data = json_loads(request["fields"])
workflow_type = ""
for field in field_data["pages"][0]["content"]:
if "name" in field and field["name"] == "workflowtype" and len(field["value"]) > 0:
workflow_type = field["value"]
field_template = json_loads(open("workflow-templates/lipid-class.json").read())
if "pages" in field_template and len(field_template["pages"]) > 0:
for field in field_template["pages"][0]["content"]:
if field["type"] == "hidden":
field["value"] = workflow_type
break
field_template["version"] = version
field_template["creation_date"] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
field_template = json_dumps(field_template)
# add main form entry
sql = "INSERT INTO %sentries (form, user_id, status, fields, date, user_uuid) VALUES (?, ?, 'partial', ?, DATETIME('now'), ?);" % table_prefix
values = (class_form_id, uid, field_template, user_uuid)
db_cursor.execute(sql, values)
conn.commit()
# get new class entry id
sql = "SELECT max(id) as eid FROM %sentries WHERE user_id = ? and form = ? and status = 'partial';" % table_prefix
db_cursor.execute(sql, (uid, class_form_id))
request = db_cursor.fetchone()
new_class_entry_id = request["eid"]
# add main entry id and class entry id pair into DB
sql = "INSERT INTO %sconnect_lipid_class (main_form_entry_id, class_form_entry_id) VALUES (?, ?);" % table_prefix
db_cursor.execute(sql, (main_entry_id, new_class_entry_id))
conn.commit()
if status == completed_label:
sql = "UPDATE %sentries SET status = ? WHERE id = ? AND user_id = ?;" % table_prefix
db_cursor.execute(sql, (partial_label, main_entry_id, uid))
conn.commit()
print(get_encrypted_entry(new_class_entry_id))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_ADDING_CLASS_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
elif content["command"] == "add_sample_form":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
# check if main form entry id is within the request and an integer
if "main_entry_id" not in content:
print(str(ErrorCodes.NO_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
main_entry_id = int(get_decrypted_entry(content["main_entry_id"]))
except:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
if main_entry_id < 0:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
# connect with the database
conn, db_cursor = dbconnect()
if not check_entry_id(main_entry_id, uid, db_cursor, "main"):
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
# checking if main form is partial or completed
status, request = check_status(main_entry_id, uid, db_cursor, not_in = {partial_label, completed_label})
field_template = json_loads(open("workflow-templates/sample.json").read())
field_template["version"] = version
field_template["creation_date"] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
field_template = json_dumps(field_template)
# add main form entry
sql = "INSERT INTO %sentries (form, user_id, status, fields, date, user_uuid) VALUES (?, ?, ?, ?, DATETIME('now'), ?);" % table_prefix
values = (sample_form_id, uid, partial_label, field_template, user_uuid)
db_cursor.execute(sql, values)
conn.commit()
sql = "SELECT max(id) as eid FROM %sentries WHERE user_id = ? and form = ? and status = ?;" % table_prefix
db_cursor.execute(sql, (uid, sample_form_id, partial_label))
request = db_cursor.fetchone()
new_sample_entry_id = request["eid"]
# add main entry id and sample entry id pair into DB
sql = "INSERT INTO %sconnect_sample (main_form_entry_id, sample_form_entry_id) VALUES (?, ?);" % table_prefix
db_cursor.execute(sql, (main_entry_id, new_sample_entry_id))
conn.commit()
if status == completed_label:
sql = "UPDATE %sentries SET status = ? WHERE id = ? AND user_id = ?;" % table_prefix
db_cursor.execute(sql, (partial_label, main_entry_id, uid))
conn.commit()
print(get_encrypted_entry(new_sample_entry_id))
except Exception as e:
print(str(ErrorCodes.ERROR_ON_ADDING_SAMPLE_FORMS) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
################################################################################
## complete partial form
################################################################################
elif content["command"] == "complete_partial_form":
# check if main form entry id is within the request and an integer
if "entry_id" not in content:
print(str(ErrorCodes.NO_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
entry_id = int(get_decrypted_entry(content["entry_id"]))
except:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
if entry_id < 0:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
try:
# connect with the database
conn, db_cursor = dbconnect()
# checking if main form is partial or completed
status, request = check_status(entry_id, uid, db_cursor, not_in = {partial_label, completed_label})
# delete old partial entry
sql = "UPDATE %sentries SET status = ? WHERE id = ? AND user_id = ?;" % table_prefix
db_cursor.execute(sql, (completed_label, entry_id, uid))
conn.commit()
sql = "SELECT form FROM %sentries WHERE id = ? AND user_id = ?;" % table_prefix
db_cursor.execute(sql, (entry_id, uid))
request = db_cursor.fetchone()
# add report hash number if necessary
if request["form"] == main_form_id:
sql = "SELECT COUNT(*) as cnt FROM %sreports WHERE entry_id = ?;" % table_prefix
db_cursor.execute(sql, (entry_id,))
request = db_cursor.fetchone()["cnt"]
if request == 0:
while True:
hash_value = chr(randint(97, 122)) + chr(randint(97, 122)) + "".join(str(randint(0, 9)) for i in range(8))
sql = "SELECT COUNT(*) AS cnt FROM %sreports WHERE hash = ?;" % table_prefix
db_cursor.execute(sql, (hash_value,))
if db_cursor.fetchone()["cnt"] == 0: break
sql = "INSERT INTO %sreports (entry_id, hash, DOI) VALUES (?, ?, '');" % table_prefix
db_cursor.execute(sql, (entry_id, hash_value))
conn.commit()
except Exception as e:
print(str(ErrorCodes.ERROR_ON_DELETING_MAIN_FORM) + " in %s" % content["command"], e)
finally:
if conn is not None: conn.close()
print(0)
################################################################################
## copy forms
################################################################################
elif content["command"] == "copy_main_form":
if "user_uuid" not in content or "uid" not in content:
print(str(ErrorCodes.NO_USER_UUID) + " in %s" % content["command"])
exit()
user_uuid = content["user_uuid"]
uid = int(content["uid"])
# check if main form entry id is within the request and an integer
if "entry_id" not in content:
print(str(ErrorCodes.NO_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
main_entry_id = int(get_decrypted_entry(content["entry_id"]))
except:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
if main_entry_id < 0:
print(str(ErrorCodes.INVALID_MAIN_ENTRY_ID) + " in %s" % content["command"])
exit()
try:
# connect with the database
conn, db_cursor = dbconnect()