Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ayobi committed Aug 20, 2024
1 parent 9e3914b commit 21161ba
Show file tree
Hide file tree
Showing 4 changed files with 159 additions and 165 deletions.
263 changes: 109 additions & 154 deletions microsetta_admin/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,18 @@ def new_kits():
new_barcodes = [line.split(',')[0].strip('\ufeff\r')
for line in barcode_file.split('\n')
if line.strip()]
if len(new_barcodes) != num_kits:
if len(new_barcodes) > num_kits:
error_message = (f'Too many barcodes provided in '
f'file {barcode_file}.')
else:
error_message = (f'Not enough barcodes provided in '
f'file {barcode_file}.')
return render_template('create_kits.html',
error_message=error_message,
projects=projects,
**build_login_variables())

barcodes.extend(new_barcodes)
total_provided_samples += len(new_barcodes)

Expand Down Expand Up @@ -626,180 +638,123 @@ def new_kits():
mimetype='text/csv')


@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())
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]

elif request.method == 'POST':
kit_ids = []
barcodes = []

if 'kit_ids' in request.form:
kit_ids = request.form['kit_ids']
def handle_api_request(payload):
status, result = APIRequest.post('/api/admin/add_barcodes',
json=payload)
if status != 200 and status != 204:
return render_template('add_barcode_to_kit.html',
error_message=result,
**build_login_variables()), status
return result

if 'user_barcode' in request.form:
user_barcode = request.form['user_barcode']
barcodes.append(user_barcode)

if 'generate_barcode_single' in request.form:
generate_barcode_single = request.form['generate_barcode_single']
else:
generate_barcode_single = None
def save_and_send_csv(kit_ids, barcodes):
with tempfile.NamedTemporaryFile(mode='w',
delete=False,
newline='') as file:
writer = csv.writer(file)
writer.writerow(['Kit IDs', 'Barcode'])
writer.writerows(zip(kit_ids, barcodes))
filename = file.name

if 'generate_barcodes_multiple' in request.form:
generate_barcodes_multiple = request.form
['generate_barcodes_multiple']
else:
generate_barcodes_multiple = None

if 'kit_ids' in request.files:
kit_ids_file = request.files['kit_ids']
kit_ids_content = kit_ids_file.read().decode('utf-8-sig')
kit_ids = [row[0] for row in csv.reader(io.StringIO
(kit_ids_content),
skipinitialspace=True)
if row]

if 'barcodes_file' in request.files:
barcodes_file = request.files['barcodes_file']
barcodes_content = barcodes_file.read().decode('utf-8-sig')
barcodes = [row[0] for row in csv.reader(io.StringIO
(barcodes_content),
skipinitialspace=True)]

if generate_barcode_single or 'user_barcode' in request.form:
if user_barcode == '':
generate_barcode_payload = {
'action': 'create',
'kit_ids': kit_ids,
'generate_barcode_single': generate_barcode_single
}

status, result = APIRequest.post('/api/admin/add_barcodes',
json=generate_barcode_payload)
if status != 200:
return render_template('add_barcode_to_kit.html',
error_message="Kit ID not found",
**build_login_variables())
else:
result = barcodes
stamp = datetime.now().strftime('%d%b%Y-%H%M')
fname = f'kits-{stamp}.csv'
return send_file(filename,
as_attachment=True,
download_name=fname)

user_barcode_payload = {
"action": "insert",
"barcodes": result,
"kit_ids": kit_ids
}
status, results = APIRequest.post('/api/admin/add_barcodes',
json=user_barcode_payload)

error_message = "Unable to insert barcode(s), " \
"barcode already exists"
@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())

if status != 204:
return render_template('add_barcode_to_kit.html',
error_message=error_message,
**build_login_variables())
kit_ids = []
barcodes = []

return render_template('add_barcode_to_kit.html',
barcodes=result,
kit_id=kit_ids,
**build_login_variables())
if 'kit_ids' in request.form:
kit_ids = request.form['kit_ids']

if generate_barcodes_multiple:
generate_barcode_payload = {
'action': 'create',
'kit_ids': kit_ids,
'generate_barcodes_multiple': generate_barcodes_multiple
}
status, result = APIRequest.post('/api/admin/add_barcodes',
json=generate_barcode_payload)
if status == 404:
return render_template('add_barcode_to_kit.html',
error_message="Kit ID not found",
**build_login_variables())

barcodes = result
if 'user_barcode' in request.form:
user_barcode = request.form['user_barcode']
barcodes.append(user_barcode)
else:
user_barcode = None

if len(kit_ids) != len(barcodes):
error_message = (f'The number of kit IDs ({len(kit_ids)}) '
f'does not match the number of barcodes '
f'({len(barcodes)}).')
return render_template('add_barcode_to_kit.html',
error_message=error_message,
**build_login_variables())
csv_payload = {
"action": "insert",
"barcodes": barcodes,
"kit_ids": kit_ids
}
generate_barcode_single = \
request.form.get('generate_barcode_single')
generate_barcodes_multiple = \
request.form.get('generate_barcodes_multiple')

status, results = APIRequest.post('/api/admin/add_barcodes',
json=csv_payload)
if status == 404:
return render_template('add_barcode_to_kit.html',
error_message="Kit ID not found",
**build_login_variables())
if 'kit_ids' in request.files:
kit_ids_file = request.files['kit_ids']
kit_ids = read_csv_file(kit_ids_file)

with tempfile.NamedTemporaryFile(mode='w', delete=False,
newline='') as file:
writer = csv.writer(file)
writer.writerow(['Kit IDs', 'Barcode'])
writer.writerows(zip(kit_ids, barcodes))
filename = file.name

stamp = datetime.now().strftime('%d%b%Y-%H%M')
fname = f'kits-{stamp}.csv'

return send_file(filename,
as_attachment=True,
download_name=fname)

if kit_ids and barcodes:
if len(kit_ids) != len(barcodes):
error_message = (f'The number of kit IDs ({len(kit_ids)}) '
f'does not match the number of barcodes '
f'({len(barcodes)}).')
return render_template('add_barcode_to_kit.html',
error_message=error_message,
**build_login_variables())
if 'barcodes_file' in request.files:
barcodes_file = request.files['barcodes_file']
barcodes = read_csv_file(barcodes_file)

csv_payload = {
"action": "insert",
"barcodes": barcodes,
"kit_ids": kit_ids
if generate_barcode_single or user_barcode:
if not user_barcode:
payload = {
'action': 'create',
'kit_ids': kit_ids,
'generate_barcode_single': generate_barcode_single
}
barcodes = handle_api_request(payload)
if isinstance(barcodes, tuple):
return barcodes

status, results = APIRequest.post('/api/admin/add_barcodes',
json=csv_payload)

if status != 204:
start_index = results.find("Key")
if start_index != -1:
error_message = results[start_index:]
error_message = error_message[:44]
else:
error_message = "Error message not found in the results."
payload = {
"action": "insert",
"barcodes": barcodes,
"kit_ids": kit_ids
}
result = handle_api_request(payload)
if isinstance(result, tuple):
return result

return render_template('add_barcode_to_kit.html',
error_message=error_message,
**build_login_variables())
return render_template('add_barcode_to_kit.html',
barcodes=barcodes,
kit_id=kit_ids,
**build_login_variables())

with tempfile.NamedTemporaryFile(mode='w', delete=False,
newline='') as file:
writer = csv.writer(file)
writer.writerow(['Kit IDs', 'Barcode'])
writer.writerows(zip(kit_ids, barcodes))
filename = file.name
if generate_barcodes_multiple:
payload = {
'action': 'create',
'kit_ids': kit_ids,
'generate_barcodes_multiple': generate_barcodes_multiple
}
barcodes = handle_api_request(payload)
if isinstance(barcodes, tuple):
return barcodes

if len(kit_ids) != len(barcodes):
error_message = f'The number of kit IDs ({len(kit_ids)}) '\
f'does not match the number of barcodes '\
f'({len(barcodes)}).'
return render_template('add_barcode_to_kit.html',
error_message=error_message,
**build_login_variables()), 400

stamp = datetime.now().strftime('%d%b%Y-%H%M')
fname = f'kits-{stamp}.csv'
payload = {
"action": "insert",
"barcodes": barcodes,
"kit_ids": kit_ids
}
result = handle_api_request(payload)
if isinstance(result, tuple):
return result

return send_file(filename,
as_attachment=True,
download_name=fname)
return save_and_send_csv(kit_ids, barcodes)


def _check_sample_status(extended_barcode_info):
Expand Down
13 changes: 10 additions & 3 deletions microsetta_admin/templates/add_barcode_to_kit.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js"></script>
<script>
$(document).ready(function(){
// Initialize form validation on the registration form.
// Initialize form validation on the form.
$("form[name='single_kit_form']").validate({
rules: {
kit_id: "required",
Expand Down Expand Up @@ -33,14 +33,21 @@
}
});

function clearMessages() {
$('#error_message').text("");
$('#success_message').empty();
}

// Toggle form visibility
$('#single_kit_button').click(function() {
$('#single_kit_form').show();
$('#multiple_kits_form').hide();
clearMessages();
});
$('#multiple_kits_button').click(function() {
$('#multiple_kits_form').show();
$('#single_kit_form').hide();
clearMessages();
});

$("#generate_barcode_single").on("change", function() {
Expand Down Expand Up @@ -103,7 +110,7 @@ <h3>Add Barcode to Kit(s)</h3>
</style>
<div style="height: 335px;">
{% if error_message %}
<p style="color:red">
<p id="error_message" style="color:red">
{{ error_message |e }}
</p>
{% endif %}
Expand Down Expand Up @@ -132,7 +139,7 @@ <h3>Add Barcode to Kit(s)</h3>
</table>
</form>
{% if barcodes %}
<ul>
<ul id="success_message">
{% for barcode in barcodes %}
<span>You added {{ barcode }} to Kit ID {{ kit_id }}</span><br>
{% endfor %}
Expand Down
13 changes: 11 additions & 2 deletions microsetta_admin/templates/create_kits.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,19 @@
$("form[name='kit_form']").validate({
rules: {
number_of_kits: "required",
number_of_samples: "required",
number_of_samples: {
required: true,
max: 25
},
project_ids: "required",
submitHandler: function (form) {
form.submit();
}
},
messages: {
number_of_samples: {
max: "You cannot add more than 25 samples per kit."
}
}
});

Expand Down Expand Up @@ -63,7 +71,8 @@ <h4>Sample ${j}</h4>
toggleDisableOptions();
});

$("#number_of_samples").val(1).trigger('change'); // Default value to 1 on page load
$("#number_of_samples").val(1).trigger('change');
$("#number_of_kits").val(1).trigger('change');
});
</script>
<style>
Expand Down
Loading

0 comments on commit 21161ba

Please sign in to comment.