Merge pull request #1365 from solgenomics/topic/trial_layout_retrieval
[sgn.git] / js / CXGN / Trial.js
blob2208231a93cbd596f526a1a36bbde4e17411d75f
1 // Depends on CXGN.BreedersToolbox.HTMLSelect
3 function delete_phenotype_data_by_trial_id(trial_id) {
4     var yes = confirm("Are you sure you want to delete all phenotypic data associated with trial "+trial_id+" ? This action cannot be undone.");
5     if (yes) {
7         jQuery.ajax( {
8       url: '/ajax/breeders/trial/'+trial_id+'/delete/phenotypes',
9       beforeSend: function(){
10         jQuery('#working_modal').modal('show');
11       },
12       success: function(response) {
13         jQuery('#working_modal').modal('hide');
14         if (response.error) {
15            alert(response.error);
16                        }
17                     else {
18                        alert('The phenotypic data has been deleted.'); // to do: give some idea how many items were deleted.
19                     window.location.href="/breeders/trial/"+trial_id;
20                 }
21             },
22       error: function(response) {
23                     jQuery('#working_modal').modal('hide');
24                     alert("An error occurred.");
25             }
26         });
27  }
31 function delete_layout_data_by_trial_id(trial_id) {
32     var yes = confirm("Are you sure you want to delete the layout data associated with trial "+trial_id+" ? This action cannot be undone.");
33     if (yes) {
35         jQuery.ajax( {
36       url: '/ajax/breeders/trial/'+trial_id+'/delete/layout',
37       beforeSend: function(){
38         jQuery('#working_modal').modal('show');
39       },
40       success: function(response) {
41         jQuery('#working_modal').modal('hide');
42                     if (response.error) {
43                     alert(response.error);
44                     }
45                     else {
46                     alert('The layout data has been deleted.'); // to do: give some idea how many items were deleted.
47                     window.location.href="/breeders/trial/"+trial_id;
48                     }
49        },
50       error: function(response) {
51                     jQuery('#working_modal').modal('hide');
52                     alert("An error occurred.");
53        }
54          });
55   }
58 function delete_project_entry_by_trial_id(trial_id) {
59        var yes = confirm("Are you sure you want to delete the trial entry for trial "+trial_id+" ? This action cannot be undone.");
60     if (yes) {
62         jQuery.ajax( {
63       url: '/ajax/breeders/trial/'+trial_id+'/delete/entry',
64       beforeSend: function(){
65         jQuery('#working_modal').modal('show');
66         },
67         success: function(response) {
68           jQuery('#working_modal').modal('hide');
69                       if (response.error) {
70                       alert(response.error);
71                       }
72                       else {
73                       alert('The project entry has been deleted.'); // to do: give some idea how many items were deleted.
74                       window.location.href="/breeders/trial/"+trial_id;
75                       }
76         },
77         error: function(response) {
78                       jQuery('#working_modal').modal('hide');
79                       alert("An error occurred.");
80         }
81             });
82     }
86 function associate_breeding_program() {
87     var program = jQuery('#breeding_program_select').val();
89     var trial_id = get_trial_id();
90     jQuery.ajax( {
91         url: '/breeders/program/associate/'+program+'/'+ trial_id,
92         async: false,
93         success: function(response) {
94             alert("Associated program with id "+program + " to trial with id "+ trial_id);
96         }
97     });
100 function load_breeding_program_info(trial_id) {
101     jQuery.ajax( {
102         url:'/breeders/programs_by_trial/'+trial_id,
103         success: function(response) {
104             if (response.error) {
105                 jQuery('#breeding_programs').html('[ An error occurred fetching the breeding program information ]');
106             }
107             else {
108                 var programs = response.projects;
109                 for (var i=0; i< programs.length; i++) {
110                     var html =  programs[0][1] + ' (' + programs[0][2] + ') ';
111                 }
112                 if (programs.length == 0) { html = "(none)"; }
113                 jQuery('#breeding_programs').html(html);
114             }
115         },
116         error: function() {
117             jQuery('#breeding_programs').html('[ An error occurred ]');
118         }
119     });
123 function open_create_DataCollector_dialog() {
124     //jQuery('#working').dialog("open");
125     jQuery('#working_modal').modal("show");
126     var list = new CXGN.List();
127     jQuery("#trait_list_dc").html(list.listSelect("trait_list", [ 'traits' ]));
128     //jQuery('#working').dialog("close");
129     jQuery('#working_modal').modal("hide");
130     jQuery('#create_DataCollector_dialog').dialog("open");
134 function create_DataCollector() {
135     //jQuery('#working').dialog("open");
136     jQuery('#working_modal').modal("show");
137     var trialID = parseInt(jQuery('#trialIDDiv').text());
138     var list = new CXGN.List();
139     var trait_list_id = jQuery('#trait_list_list_select').val();
140     var trait_list;
141     if (! trait_list_id == "") {
142         trait_list = JSON.stringify(list.getList(trait_list_id));
143     }
144      new jQuery.ajax({
145          type: 'POST',
146          url: '/ajax/phenotype/create_DataCollector',
147          dataType: "json",
148          data: {
149              'trial_id': trialID,
150              'trait_list': trait_list,
151          },
153          success: function (response) {
154      //console.log("success "+JSON.stringify(response));
155      jQuery('#working_modal').modal("hide");
157      if (response.error) {
158        console.log("error: "+response.error);
159        alert("error: "+response.error);
160        jQuery('#open_create_DataCollector_dialog').dialog("close");
161      } else {
162        //alert("success: "+response.filename);
163        jQuery('#open_create_DataCollector_dialog').dialog("close");
164        jQuery('#working_modal').modal("hide");
165        window.location.href = "/download/"+response.filename;
166      }
167          },
168          error: function () {
169              //jQuery('#working').dialog("close");
170              jQuery('#working_modal').modal("hide");
171              alert('An error occurred creating a DataCollector file.');
172              jQuery('#open_download_DataCollector_dialog').dialog("close");
173          }
174      });
177 function open_derived_trait_dialog() {
178     jQuery('#working_modal').modal("show");
179     jQuery('#compute_derived_trait_dialog').dialog("open");
180     var trait = jQuery('#sel1').val();
181     jQuery("#test_xyz").html(trait);
182     jQuery('#working_modal').modal("hide");
186 function compute_derived_trait() {
187     jQuery('#working_modal').modal("show");
188     var trait = jQuery('#derived_trait_select').val();
189     var trialID = parseInt(jQuery('#trialIDDiv').text());
190     if (trait === '') {
191                 alert("No trait selected");
192             }
194      new jQuery.ajax({
195          type: 'POST',
196          url: '/ajax/phenotype/create_derived_trait',
197          dataType: "json",
198          data: {
199              'trial_id': trialID,
200              'trait': trait,
201          },
203          success: function (response) {
204              jQuery('#working_modal').modal("hide");
206              if (response.error) {
207                  alert("Computation stopped: "+response.error);
208                  //alert("Computation for "+trait+" stopped: "+response.error);
209                  jQuery('#open_derived_trait_dialog').dialog("close");
211              } else {
212                  jQuery('#open_derived_trait_dialog').dialog("close");
213                  jQuery('#working_modal').modal("hide");
214                  jQuery('derived_trait_saved_dialog_message');
215                  alert("Successfully derived and uploaded phenotype");
216                 // alert("Successfully derived and uploaded ' "+trait+" ' values for this trial");
217              }
218          },
219          error: function () {
220              jQuery('#working_modal').modal("hide");
221              alert('An error occurred creating trait.');
222          }
223      });
227 function delete_field_map() {
228     jQuery('#working_modal').modal("show");
230   var trialID = parseInt(jQuery('#trialIDDiv').text());
231   new jQuery.ajax({
232          type: 'POST',
233          url: '/ajax/phenotype/delete_field_coords',
234          dataType: "json",
235          data: {
236              'trial_id': trialID,
237          },
239          success: function (response) {
240              jQuery('#working_modal').modal("hide");
242       if (response.error) {
243                       alert("Error Deleting Field Map: "+response.error);
244       } else {
245           //alert("Field map deletion Successful...");
246                       jQuery('#delete_field_map_dialog_message').dialog("open");
247           }
248          },
249          error: function () {
250              jQuery('#working_modal').modal("hide");
251              alert('An error occurred deleting field map.');
252          }
253   });
256 function replace_accessions() {
257   jQuery('#working_modal').modal("show");
259   var trialID = parseInt(jQuery('#trialIDDiv').text());
260   var old_accession_name = jQuery('#old_accession').val();
261   var new_accession_name = jQuery('#new_accession').val();
262   new jQuery.ajax({
263     type: 'POST',
264     url: '/ajax/phenotype/replace_accessions',
265     dataType: "json",
266     data: {
267       'trial_id': trialID,
268       'old_accession_name': old_accession_name,
269       'new_accession_name': new_accession_name,
270     },
272     success: function (response) {
273              jQuery('#working_modal').modal("hide");
275        if (response.error) {
276                       alert("Error replacing accessions: "+response.error);
277        } else {
278            //alert("Field map deletion Successful...");
279                       jQuery('#replace_accessions_dialog_message').dialog("open");
280            }
281          },
282          error: function () {
283              jQuery('#working_modal').modal("hide");
284               alert('An error occurred replacing accessions.');
285          }
286  });
290 function trial_detail_page_setup_dialogs() {
292      jQuery('#compute_derived_trait_dialog').dialog({
293         autoOpen: false,
294         modal: true,
295         autoResize:true,
296         width: 500,
297         position: ['top', 75],
298         modal: true,
299         buttons: {
300             Cancel: function() {
301                 jQuery( this ).dialog( "close" );
302                 return;
303             },
304             Create: {text: "Create", id:"create_derived_trait_submit_button", click:function() {
305                 compute_derived_trait();
306                 jQuery( this ).dialog( "close" );
307                 }
308             },
309         },
310     });
312     jQuery('#edit_trial_details').click(function () { 
313         // set up inout handlers
314         jQuery('#clear_planting_date').click(function() {
315           planting_date_element.val('');
316           highlight_changed_details(planting_date_element);
317         });
319         jQuery('#clear_harvest_date').click(function() {
320           harvest_date_element.val('');
321           highlight_changed_details(harvest_date_element);
322         });
324         jQuery('[id^="edit_trial_"]').change(function () {
325           var this_element = jQuery(this);
326           highlight_changed_details(this_element);
327         });
329         //save dialog body html for resetting on close
330         var edit_details_body_html = document.getElementById('trial_details_edit_body').innerHTML;
332         //populate breeding_programs, locations, years, and types dropdowns, and save defaults
333         var default_bp = document.getElementById("edit_trial_breeding_program").getAttribute("value");
334         get_select_box('breeding_programs', 'edit_trial_breeding_program', { 'default' : default_bp });
335         jQuery('#edit_trial_breeding_program').data("originalValue", default_bp);
337         var default_loc = document.getElementById("edit_trial_location").getAttribute("value");
338         get_select_box('locations', 'edit_trial_location', { 'default' : default_loc });
339         jQuery('#edit_trial_location').data("originalValue", default_loc);
341         var default_year = document.getElementById("edit_trial_year").getAttribute("value");
342         get_select_box('years', 'edit_trial_year', { 'default' : default_year, 'auto_generate': 1 });
343         jQuery('#edit_trial_year').data("originalValue", default_year);
345         var default_type = document.getElementById("edit_trial_type").getAttribute("value");
346         get_select_box('trial_types', 'edit_trial_type',  { 'default' : default_type });
347         jQuery('#edit_trial_type option[value="'+default_type+'"]').attr('selected','selected');
349         //create bootstrap daterangepickers for planting and harvest dates
350         var planting_date_element = jQuery("#edit_trial_planting_date");
351         set_daterangepicker_default (planting_date_element);
352         jQuery('input[title="planting_date"]').daterangepicker(
353           {
354           "singleDatePicker": true,
355           "showDropdowns": true,
356           "autoUpdateInput": false,
357           },
358           function(start) {
359             planting_date_element.val(start.format('MM/DD/YYYY'));
360             highlight_changed_details(planting_date_element);
361           }
362         );
364         var harvest_date_element = jQuery("#edit_trial_harvest_date");
365         set_daterangepicker_default (harvest_date_element);
366         harvest_date_element.daterangepicker(
367           {
368           "singleDatePicker": true,
369           "showDropdowns": true,
370           "autoUpdateInput": false,
371           },
372           function(start) {
373             harvest_date_element.val(start.format('MM/DD/YYYY'));
374             highlight_changed_details(harvest_date_element);
375           }
376         );
378         //show dialog and handle cancel and save events
379         jQuery('#trial_details_edit_dialog').modal("show");
381         jQuery('#edit_trial_details_cancel_button').click(function () {
382             reset_dialog_body('trial_details_edit_body', edit_details_body_html);
383         });
385         jQuery('#save_trial_details').click(function () {
386           var changed_elements = document.getElementsByName("changed");
387           var categories = [];
388           var new_details = {};
389           var success_message = '';
390           for(var i=0; i<changed_elements.length; i++) {
391             var id = changed_elements[i].id;
392             var type = changed_elements[i].title;
393             var new_value = changed_elements[i].value;
394             if (type.match(/date/)) {
395               if (new_value) {
396                 new_value = moment(new_value).format('YYYY/MM/DD HH:mm:ss') || 'remove' ;
397               } else {
398                 new_value = 'remove';
399               }
400             }
401             categories.push(type);
402             new_details[type] = new_value;
403             if(jQuery('#'+id).is("select")) {
404               new_value = changed_elements[i].options[changed_elements[i].selectedIndex].text
405             }
406             success_message += "<li class='list-group-item list-group-item-success'> Changed "+type+" to: <b>"+new_value+"</b></li>";
407           }
409           jQuery('#trial_details_edit_dialog').modal("hide");
410           save_trial_details(categories, new_details, success_message);
412         });
413     });
415   jQuery('#trial_details_error_close_button').click( function() {
416     document.getElementById('trial_details_error_message').innerHTML = "";
417   });
419   jQuery('#trial_details_saved_close_button').click( function() {
420     location.reload();
421   });
423     jQuery('#delete_phenotype_data_by_trial_id').click(
424         function() {
425             var trial_id = get_trial_id();
426             delete_phenotype_data_by_trial_id(trial_id);
427         }
428     );
430     jQuery('#delete_layout_data_by_trial_id').click(
431         function() {
432             var trial_id = get_trial_id();
433             delete_layout_data_by_trial_id(trial_id);
434         });
436     jQuery('#delete_trial_entry_by_trial_id').click(
437         function() {
438             var trial_id = get_trial_id();
439             delete_project_entry_by_trial_id(trial_id);
440         });
442     jQuery('#view_layout_link').click(function () {
443         jQuery('#trial_design_view_layout').dialog("open");
444     });
446     jQuery('#compute_derived_trait_link').click( function () {
447         jQuery('#compute_derived_trait_dialog').dialog("open");
448         jQuery.ajax( {
449                 url: '/ajax/breeders/trial/trait_formula',
450                 success: function(response) {
451                 //console.log(response);
452                 if (response.error) {
453                     alert(response.error);
454                 }
455                 else {
456                     var html = "";
457                     if (response.derived_traits) {
458                         var selected = 'selected="selected"';
459                         for(var n=0; n<response.derived_traits.length; n++) {
460                             //alert("derived trait: +derived_traits"+response.derived_traits[n]);
461                             html += '<option value="'+response.derived_traits[n]+'" title="'+response.formula[n]+'" >'+response.derived_traits[n]+' </option> ';
462                         }
464                     }
465                     else {
466                         html = '<option active="false">No derived trait available</option>';
467                     }
468                 }
469                 jQuery('#derived_trait_select').html(html);
470             },
471             error: function(response) {
472                 alert("An error occurred trying to retrieve derived traits.");
473             }
474         });
478 jQuery("#delete_field_map_dialog").dialog({
479 autoOpen: false,
480 modal: true,
481 autoResize:true,
482     width: 500,
483     position: ['top', 75],
484 buttons: {
485         "Cancel": function () {
486             jQuery('#delete_field_map_dialog').dialog("close");
487         },
488   "Ok": {text: "Ok", id:"delete_field_coords_ok_button", click:function () {
489 delete_field_map();
490             jQuery('#delete_field_map_dialog').dialog("close");
491     }
492   }
498 jQuery('#delete_field_map_link').click(function () {
499     jQuery('#delete_field_map_dialog').dialog("open");
502 jQuery("#delete_field_map_dialog_message").dialog({
503 autoOpen: false,
504 modal: true,
505 buttons: {
506         Ok: { id: "dismiss_delete_field_map_dialog",
507               click: function() {
508                 location.reload();
509               },
510               text: "OK"
511             }
512     }
516 jQuery("#update_field_map_dialog_message").dialog({
517 autoOpen: false,
518 modal: true,
519 buttons: {
520         Ok: { id: "dismiss_update_field_map_dialog",
521               click: function() {
522                 location.reload();
523               },
524               text: "OK"
525             }
526     }
530 jQuery("#replace_accessions_dialog_message").dialog({
531 autoOpen: false,
532 modal: true,
533 buttons: {
534         Ok: { id: "dismiss_replace_accessions_dialog_message",
535               click: function() {
536                 location.reload();
537               },
538               text: "OK"
539             }
540     }
544 jQuery('#update_field_map_link').click(function () {
545     jQuery('#update_field_map_dialog').dialog("open");
550 function set_daterangepicker_default (date_element) {
551   var date = date_element.val() || '';
552   if (date) {
553     date = moment(date, 'YYYY-MMMM-DD').format('MM/DD/YYYY');
554   }
555   date_element.val(date);
558 function highlight_changed_details(element) { // compare changed value to default. If different, add class and feedback span, if same, remove them
559   var id = element.attr('id');
560   var current_value = element.val();
561   var default_value = document.getElementById(id).defaultValue;
562   if (element.attr('title').match(/date/)) { default_value = moment(document.getElementById(id).defaultValue, 'YYYY-MMMM-DD').format('MM/DD/YYYY');}
563   if (!default_value) { default_value = element.data("originalValue");}
564   if ((current_value || default_value) && current_value !== default_value) {
565     element.parent().siblings('#change_indicator').remove();
566     element.attr("name", "changed");
567     element.parent().parent().addClass("has-success has-feedback");
568     element.parent().after('<span class="glyphicon glyphicon-pencil form-control-feedback" id="change_indicator" aria-hidden="true" style="right: -20px;"></span>');
569   } else {
570     element.attr("name", "");
571     element.parent().parent().removeClass("has-success has-feedback");
572     element.parent().siblings('#change_indicator').remove();
573   }
576 function reset_dialog_body (body_id, body_html) {
577   document.getElementById(body_id).innerHTML = body_html;
580 function save_trial_details (categories, details, success_message) {
581   var trial_id = get_trial_id();
582   jQuery.ajax( {
583     url: '/ajax/breeders/trial/'+trial_id+'/details/',
584     type: 'POST',
585     data: { 'categories' : categories, 'details' : details },
586     beforeSend: function(){
587       disable_ui();
588     },
589     complete : function(){
590       enable_ui();
591     },
592     success: function(response) {
593       if (response.success) {
594         document.getElementById('trial_details_saved_message').innerHTML = success_message;
595         jQuery('#trial_details_saved_dialog').modal("show");
596         return;
597       }
598       else {
599         document.getElementById('trial_details_error_message').innerHTML = "<li class='list-group-item list-group-item-danger'>"+response.error+"</li>";
600         jQuery('#trial_details_error_dialog').modal("show");
601       }
602     },
603     error: function(response) {
604       document.getElementById('trial_details_error_message').innerHTML = "<li class='list-group-item list-group-item-danger'> Trial detail update AJAX request failed. Update not completed.</li>";
605       jQuery('#trial_details_error_dialog').modal("show");
606     },
607   });
610 function trial_folder_dialog() {
611     jQuery('#set_folder_dialog').dialog("open");
616 function get_trial_id() {
617     var trial_id = parseInt(jQuery('#trialIDDiv').text());
618     return trial_id;
622 var $j = jQuery.noConflict();
624 jQuery(document).ready(function ($) {
626     $('#upload_trial_coords_link').click(function () {
627         open_upload_trial_coord_dialog();
628     });
630     jQuery('#upload_trial_coords_ok_button').click(function(){
631         upload_trial_coord_file();
632     });
634      $("#trial_coordinates_upload_spreadsheet_format_info").click( function () {
635          $("#trial_coord_upload_spreadsheet_info_dialog" ).modal("show");
636     });
638      $('#upload_trial_coordinates_form').iframePostForm({
639         json: true,
640         post: function () {
641             var uploadedtrialcoordFile = $("#trial_coordinates_uploaded_file").val();
642             $('#working_modal').modal("show");
643             if (uploadedtrialcoordFile === '') {
644                 $('#working_modal').modal("hide");
645                 alert("No file selected");
646             }
647         },
648         complete: function (response) {
649             $('#working_modal').modal("hide");
650             if (response.error_string) {
651                 $("#upload_trial_coord_error_display tbody").html('');
652                 $("#upload_trial_coord_error_display tbody").append(response.error_string);
653         jQuery('#upload_trial_coord_error_display').modal('show');
655                 return;
656             }
657             if (response.error) {
658                 alert(response.error);
659                 return;
660             }
661             if (response.success) {
662                 $('#trial_coord_upload_success_dialog_message').modal("show");
663                 //alert("File uploaded successfully");
664             }
665         }
666     });
668         function upload_trial_coord_file() {
669         var uploadFile = $("#trial_coordinates_uploaded_file").val();
670         $('#upload_trial_coordinates_form').attr("action", "/ajax/breeders/trial/coordsupload");
671         if (uploadFile === '') {
672             alert("Please select a file");
673             return;
674         }
675         $("#upload_trial_coordinates_form").submit();
676     }
678     function open_upload_trial_coord_dialog() {
679              $('#upload_trial_coord_dialog').modal("show");
680     }
682     function open_replace_trial_accession_dialog() {
683       jQuery('#replace_trial_accessions_dialog').modal('show');
684     }
686     $('#replace_trial_accession_submit').click(function () {
687       jQuery('#edit_field_map_dialog').modal('hide');
688       open_replace_trial_accession_dialog();
689     });
691     function open_subtitute_plot_accession_dialog() {
692       jQuery('#subtitute_plot_accessions_dialog').modal('show');
693     }
695     $('#substitute_accession_submit').click(function () {
696       jQuery('#edit_field_map_dialog').modal('hide');
697       open_subtitute_plot_accession_dialog();
698     });
700     jQuery('#generate_trial_barcode_link').click(function () {
701         $('#generate_trial_barcode_button_dialog').modal("show");
702     });
704     jQuery('#trial_plot_barcode').click(function () {
705         $('#generate_trial_barcode_button_dialog').modal("hide");
706         $('#generate_trial_barcode_dialog').modal("show");
707     });
709     jQuery('#trial_accession_barcode').click(function () {
710         $('#generate_trial_barcode_button_dialog').modal("hide");
711         $('#generate_trial_barcode_dialog').modal("show");
712     });
714     jQuery('#trial_plant_barcode').click(function () {
715         $('#generate_trial_barcode_button_dialog').modal("hide");
716         $('#generate_trial_barcode_dialog').modal("show");
717     });