revert accidental changes
[sgn.git] / lib / SGN / Controller / AJAX / Trial.pm
blob307beb464c15545e446510ed652226d6a7df219f
2 =head1 NAME
4 SGN::Controller::AJAX::Trial - a REST controller class to provide the
5 backend for adding trials and viewing trials
7 =head1 DESCRIPTION
9 Creating, viewing and deleting trials
11 =head1 AUTHOR
13 Jeremy Edwards <jde22@cornell.edu>
15 Deletion by Lukas
17 =cut
19 package SGN::Controller::AJAX::Trial;
21 use Moose;
22 use Try::Tiny;
23 use Scalar::Util qw(looks_like_number);
24 use DateTime;
25 use File::Basename qw | basename dirname|;
26 use File::Copy;
27 use File::Slurp;
28 use File::Spec::Functions;
29 use Digest::MD5;
30 use List::MoreUtils qw /any /;
31 use Data::Dumper;
32 use CXGN::Trial;
33 use CXGN::Trial::TrialDesign;
34 use CXGN::Trial::TrialCreate;
35 use JSON -support_by_pp;
36 use SGN::View::Trial qw/design_layout_view design_info_view/;
37 use CXGN::Location::LocationLookup;
38 use CXGN::Stock::StockLookup;
39 use CXGN::Trial::TrialLayout;
40 use CXGN::BreedersToolbox::Projects;
41 use CXGN::BreedersToolbox::Delete;
42 use CXGN::UploadFile;
43 use CXGN::Trial::ParseUpload;
44 use CXGN::List::Transform;
45 use CXGN::List::Validate;
46 use SGN::Model::Cvterm;
47 use JSON;
48 use CXGN::BreedersToolbox::Accessions;
50 BEGIN { extends 'Catalyst::Controller::REST' }
52 __PACKAGE__->config(
53 default => 'application/json',
54 stash_key => 'rest',
55 map => { 'application/json' => 'JSON', 'text/html' => 'JSON' },
58 has 'schema' => (
59 is => 'rw',
60 isa => 'DBIx::Class::Schema',
61 lazy_build => 1,
64 #DEPRECATED by lack of use. below functions handle saving an uploaded trial and generating/saving a new trial.
65 #sub get_trial_layout : Path('/ajax/trial/layout') : ActionClass('REST') { }
67 #sub get_trial_layout_POST : Args(0) {
68 # my ($self, $c) = @_;
69 # my $schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
70 # my $project;
71 # print STDERR "\n\ntrial layout controller\n";
72 # my $trial_layout = CXGN::Trial::TrialLayout->new({schema => $schema, project => $project} );
74 #my $trial_id = $c->req->parm('trial_id');
75 # my $project = $schema->resultset('Project::Project')->find(
76 # {
77 # id => $trial_id,
78 # }
79 # );
83 sub generate_experimental_design : Path('/ajax/trial/generate_experimental_design') : ActionClass('REST') { }
85 sub generate_experimental_design_POST : Args(0) {
86 my ($self, $c) = @_;
87 my $schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
88 my $trial_design = CXGN::Trial::TrialDesign->new();
89 my %design;
90 my %design_info;
91 my $error;
92 my $project_name = $c->req->param('project_name');
93 my $project_description = $c->req->param('project_description');
94 my $year = $c->req->param('year');
95 my @stock_names;
96 my $design_layout_view_html;
97 my $design_info_view_html;
98 if ($c->req->param('stock_list')) {
99 @stock_names = @{_parse_list_from_json($c->req->param('stock_list'))};
101 my $seedlot_hash_json = $c->req->param('seedlot_hash');
102 my @control_names;
103 if ($c->req->param('control_list')) {
104 @control_names = @{_parse_list_from_json($c->req->param('control_list'))};
107 my @control_names_crbd;
108 if ($c->req->param('control_list_crbd')) {
109 @control_names_crbd = @{_parse_list_from_json($c->req->param('control_list_crbd'))};
112 my $design_type = $c->req->param('design_type');
113 my $rep_count = $c->req->param('rep_count');
114 my $block_number = $c->req->param('block_number');
116 my $row_number = $c->req->param('row_number');
117 my $block_row_number=$c->req->param('row_number_per_block');
118 my $block_col_number=$c->req->param('col_number_per_block');
119 my $col_number =$c->req->param('col_number');
121 my $block_size = $c->req->param('block_size');
122 my $max_block_size = $c->req->param('max_block_size');
123 my $plot_prefix = $c->req->param('plot_prefix');
124 my $start_number = $c->req->param('start_number');
125 my $increment = $c->req->param('increment');
126 my $trial_location = $c->req->param('trial_location');
127 my $fieldmap_col_number = $c->req->param('fieldmap_col_number');
128 my $fieldmap_row_number = $c->req->param('fieldmap_row_number');
129 my $plot_layout_format = $c->req->param('plot_layout_format');
130 my @treatments = $c->req->param('treatments[]');
131 my $num_plants_per_plot = $c->req->param('num_plants_per_plot');
132 my $num_seed_per_plot = $c->req->param('num_seed_per_plot');
134 #if (!$num_seed_per_plot){
135 # $c->stash->{rest} = { error => "You need to provide number of seeds per plot so that your breeding material can be tracked."};
136 # return;
139 if ($design_type eq 'splitplot'){
140 if (scalar(@treatments)<1){
141 $c->stash->{rest} = { error => "You need to provide at least one treatment for a splitplot design."};
142 return;
144 if (!$num_plants_per_plot){
145 $c->stash->{rest} = { error => "You need to provide number of plants per treatment for a splitplot design."};
146 return;
148 if ($num_plants_per_plot <1){
149 $c->stash->{rest} = { error => "You need to provide number of plants per treatment for a splitplot design."};
150 return;
152 if (($num_plants_per_plot%(scalar(@treatments)))!=0){
153 $c->stash->{rest} = {error => "Number of plants per plot needs to divide evenly by the number of treatments. For example: if you have two treatments and there are 3 plants per treatment, that means you have 6 plants per plot." };
154 return;
158 my $row_in_design_number = $c->req->param('row_in_design_number');
159 my $col_in_design_number = $c->req->param('col_in_design_number');
160 my $no_of_rep_times = $c->req->param('no_of_rep_times');
161 my $no_of_block_sequence = $c->req->param('no_of_block_sequence');
162 my $unreplicated_accession_list = $c->req->param('unreplicated_accession_list');
163 my $replicated_accession_list = $c->req->param('replicated_accession_list');
164 my $no_of_sub_block_sequence = $c->req->param('no_of_sub_block_sequence');
166 my @replicated_accession;
167 if ($c->req->param('replicated_accession_list')) {
168 @replicated_accession = @{_parse_list_from_json($c->req->param('replicated_accession_list'))};
170 my $number_of_replicated_accession = scalar(@replicated_accession);
172 my @unreplicated_accession;
173 if ($c->req->param('unreplicated_accession_list')) {
174 @unreplicated_accession = @{_parse_list_from_json($c->req->param('unreplicated_accession_list'))};
176 my $number_of_unreplicated_accession = scalar(@unreplicated_accession);
178 #my $trial_name = $c->req->param('project_name');
179 my $greenhouse_num_plants = $c->req->param('greenhouse_num_plants');
180 my $use_same_layout = $c->req->param('use_same_layout');
181 my $number_of_checks = scalar(@control_names_crbd);
182 #my $trial_name = "Trial $trial_location $year"; #need to add something to make unique in case of multiple trials in location per year?
183 if ($design_type eq "RCBD" || $design_type eq "Alpha" || $design_type eq "CRD" || $design_type eq "Lattice") {
184 if (@control_names_crbd) {
185 @stock_names = (@stock_names, @control_names_crbd);
188 if($design_type eq "p-rep"){
189 @stock_names = (@replicated_accession, @unreplicated_accession);
191 #print STDERR Dumper(\@stock_names);
192 my $number_of_prep_accession = scalar(@stock_names);
193 my $p_rep_total_plots = $row_in_design_number * $col_in_design_number;
194 my $replicated_plots = $no_of_rep_times * $number_of_replicated_accession;
195 my $unreplicated_plots = scalar(@unreplicated_accession);
196 my $calculated_total_plot = $replicated_plots + $unreplicated_plots;
198 my @locations;
199 my $trial_locations;
200 my $multi_location;
202 try {
203 $multi_location = decode_json($trial_location);
204 foreach my $loc (@$multi_location) {
205 push @locations, $loc;
209 catch {
210 push @locations, $trial_location;
213 my $location_number = scalar(@locations);
215 #print STDERR Dumper(@locations);
217 if (!$c->user()) {
218 $c->stash->{rest} = {error => "You need to be logged in to add a trial" };
219 return;
222 if (!any { $_ eq "curator" || $_ eq "submitter" } ($c->user()->roles) ) { #user must have privileges to add a trial
223 $c->stash->{rest} = {error => "You have insufficient privileges to add a trial." };
224 return;
226 #print "TOTAL PLOTS $p_rep_total_plots AND CALCULATED PLOTS $calculated_total_plot\n";
227 if($p_rep_total_plots != $calculated_total_plot){
228 $c->stash->{rest} = {error => "Treatment repeats do not equal number of plots in design" };
229 return;
232 my @design_array;
233 my @design_layout_view_html_array;
235 foreach $trial_locations (@locations) {
237 my $trial_name = $c->req->param('project_name');
238 my $geolocation_lookup = CXGN::Location::LocationLookup->new(schema => $schema);
239 #$geolocation_lookup->set_location_name($c->req->param('trial_location'));
240 $geolocation_lookup->set_location_name($trial_locations);
241 #print STDERR Dumper(\$geolocation_lookup);
242 if (!$geolocation_lookup->get_geolocation()){
243 $c->stash->{rest} = { error => "Trial location not found" };
244 return;
248 if (scalar(@locations) > 1) {
249 $trial_name = $trial_name."_".$trial_locations;
252 $trial_design->set_trial_name($trial_name);
254 my $design_created = 0;
255 if ($use_same_layout) {
256 $design_created = 1;
259 if ($design_created) {
260 $trial_design->set_randomization_seed($design_created);
264 if (@stock_names) {
265 $trial_design->set_stock_list(\@stock_names);
266 $design_info{'number_of_stocks'} = scalar(@stock_names);
267 } else {
268 $c->stash->{rest} = {error => "No list of stocks supplied." };
269 return;
271 if ($seedlot_hash_json){
272 my $json = JSON->new();
273 $trial_design->set_seedlot_hash($json->decode($seedlot_hash_json));
275 if ($num_seed_per_plot){
276 $trial_design->set_num_seed_per_plot($num_seed_per_plot);
278 if (@control_names) {
279 $trial_design->set_control_list(\@control_names);
280 $design_info{'number_of_controls'} = scalar(@control_names);
282 if (@control_names_crbd) {
283 $trial_design->set_control_list_crbd(\@control_names_crbd);
284 $design_info{'number_of_controls_crbd'} = scalar(@control_names_crbd);
286 if ($start_number) {
287 $trial_design->set_plot_start_number($start_number);
288 } else {
289 $trial_design->clear_plot_start_number();
291 if ($increment) {
292 $trial_design->set_plot_number_increment($increment);
293 } else {
294 $trial_design->clear_plot_number_increment();
296 if ($plot_prefix) {
297 $trial_design->set_plot_name_prefix($plot_prefix);
299 if ($rep_count) {
300 $trial_design->set_number_of_reps($rep_count);
302 if ($block_number) {
303 $trial_design->set_number_of_blocks($block_number);
304 #$trial_design->set_number_of_blocks(8);
306 if($row_number){
307 $trial_design->set_number_of_rows($row_number);
308 #$trial_design->set_number_of_rows(9);
310 if($block_row_number){
311 $trial_design->set_block_row_numbers($block_row_number);
312 #$trial_design->set_number_of_rows(9);
314 if($block_col_number){
315 $trial_design->set_block_col_numbers($block_col_number);
316 #$trial_design->set_number_of_rows(9);
318 if($col_number){
319 $trial_design->set_number_of_cols($col_number);
320 #$trial_design->set_number_of_rows(9);
322 if ($block_size) {
323 $trial_design->set_block_size($block_size);
325 if ($max_block_size) {
326 $trial_design->set_maximum_block_size($max_block_size);
328 if ($greenhouse_num_plants) {
329 my $json = JSON->new();
330 $trial_design->set_greenhouse_num_plants($json->decode($greenhouse_num_plants));
332 if ($location_number) {
333 $design_info{'number_of_locations'} = $location_number;
335 if($number_of_checks){
336 $design_info{'number_of_checks'} = $number_of_checks;
338 if ($design_type) {
339 $trial_design->set_design_type($design_type);
340 $design_info{'design_type'} = $design_type;
341 } else {
342 $c->stash->{rest} = {error => "No design type supplied." };
343 return;
345 if (!$trial_design->has_design_type()) {
346 $c->stash->{rest} = {error => "Design type not supported." };
347 return;
349 if ($fieldmap_col_number) {
350 $trial_design->set_fieldmap_col_number($fieldmap_col_number);
352 if ($fieldmap_row_number) {
353 $trial_design->set_fieldmap_row_number($fieldmap_row_number);
355 if ($plot_layout_format) {
356 $trial_design->set_plot_layout_format($plot_layout_format);
358 if ($number_of_replicated_accession) {
359 $trial_design->set_replicated_accession_no($number_of_replicated_accession);
361 if ($number_of_unreplicated_accession) {
362 $trial_design->set_unreplicated_accession_no($number_of_unreplicated_accession);
364 if ($row_in_design_number) {
365 $trial_design->set_row_in_design_number($row_in_design_number);
367 if ($col_in_design_number) {
368 $trial_design->set_col_in_design_number($col_in_design_number);
370 if ($no_of_rep_times) {
371 $trial_design->set_num_of_replicated_times($no_of_rep_times);
373 if ($no_of_block_sequence) {
374 $trial_design->set_block_sequence($no_of_block_sequence);
376 if ($no_of_sub_block_sequence) {
377 $trial_design->set_sub_block_sequence($no_of_sub_block_sequence);
380 if (scalar(@treatments)>0) {
381 $trial_design->set_treatments(\@treatments);
383 if($num_plants_per_plot){
384 $trial_design->set_num_plants_per_plot($num_plants_per_plot);
387 try {
388 $trial_design->calculate_design();
389 } catch {
390 $c->stash->{rest} = {error => "Could not calculate design: $_"};
391 $error=1;
393 if ($error) {return;}
394 if ($trial_design->get_design()) {
395 %design = %{$trial_design->get_design()};
396 #print STDERR "DESIGN: ". Dumper(%design);
397 } else {
398 $c->stash->{rest} = {error => "Could not generate design" };
399 return;
401 my $design_level;
402 if ($design_type eq 'greenhouse'){
403 $design_level = 'plants';
404 } elsif ($design_type eq 'splitplot') {
405 $design_level = 'subplots';
406 } else {
407 $design_level = 'plots';
409 $design_layout_view_html = design_layout_view(\%design, \%design_info, $design_level);
410 $design_info_view_html = design_info_view(\%design, \%design_info);
411 my $design_json = encode_json(\%design);
412 push @design_array, $design_json;
413 push @design_layout_view_html_array, $design_layout_view_html;
416 $c->stash->{rest} = {
417 success => "1",
418 design_layout_view_html => encode_json(\@design_layout_view_html_array),
419 #design_layout_view_html => $design_layout_view_html,
420 design_info_view_html => $design_info_view_html,
421 #design_json => $design_json,
422 design_json => encode_json(\@design_array),
429 sub save_experimental_design : Path('/ajax/trial/save_experimental_design') : ActionClass('REST') { }
431 sub save_experimental_design_POST : Args(0) {
432 my ($self, $c) = @_;
433 #my $schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
434 my $chado_schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
435 my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
436 my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
437 my $dbh = $c->dbc->dbh;
439 print STDERR "Saving trial... :-)\n";
441 if (!$c->user()) {
442 $c->stash->{rest} = {error => "You need to be logged in to add a trial" };
443 return;
445 if (!any { $_ eq "curator" || $_ eq "submitter" } ($c->user()->roles) ) {
446 $c->stash->{rest} = {error => "You have insufficient privileges to add a trial." };
447 return;
449 my $user_id = $c->user()->get_object()->get_sp_person_id();
451 my $user_name = $c->user()->get_object()->get_username();
452 my $error;
454 my $design = _parse_design_from_json($c->req->param('design_json'));
455 #print STDERR "\nDesign: " . Dumper $design;
457 my @locations;
458 my $trial_location;
459 my $multi_location;
460 my $trial_locations = $c->req->param('trial_location');
461 my $trial_name = $c->req->param('project_name');
462 my $trial_type = $c->req->param('trial_type');
463 my $breeding_program = $c->req->param('breeding_program_name');
464 my $schema = $c->dbic_schema("Bio::Chado::Schema");
465 my $breeding_program_id = $schema->resultset("Project::Project")->find({name=>$breeding_program})->project_id();
466 my $folder;
467 my $new_trial_id;
469 try {
470 $multi_location = decode_json($trial_locations);
471 foreach my $loc (@$multi_location) {
472 push @locations, $loc;
476 catch {
477 push @locations, $trial_locations;
479 my $folder_id;
480 my $parent_folder_id = 0;
481 if (scalar(@locations) > 1) {
483 my $existing = $schema->resultset("Project::Project")->find( { name => $trial_name });
485 if ($existing) {
486 $c->stash->{rest} = { error => "An folder or trial with that name already exists in the database. Please select another name." };
487 return;
490 $folder = CXGN::Trial::Folder->create({
491 bcs_schema => $schema,
492 parent_folder_id => $parent_folder_id,
493 name => $trial_name,
494 breeding_program_id => $breeding_program_id,
495 folder_for_trials => 1
497 $folder_id = $folder->folder_id();
500 my $design_index = 0;
502 foreach $trial_location (@locations) {
503 my $trial_name = $c->req->param('project_name');
504 if (scalar(@locations) > 1) {
505 $trial_name = $trial_name."_".$trial_location;
508 my $trial_location_design = decode_json($design->[$design_index]);
509 #print STDERR Dumper $trial_location_design;
511 my $trial_create = CXGN::Trial::TrialCreate->new({
512 chado_schema => $chado_schema,
513 dbh => $dbh,
514 user_name => $user_name, #not implemented
515 design => $trial_location_design,
516 program => $breeding_program,
517 trial_year => $c->req->param('year'),
518 trial_description => $c->req->param('project_description'),
519 trial_location => $trial_location,
520 trial_name => $trial_name,
521 design_type => $c->req->param('design_type'),
522 trial_type => $trial_type,
523 trial_has_plant_entries => $c->req->param('has_plant_entries'),
524 trial_has_subplot_entries => $c->req->param('has_subplot_entries'),
525 operator => $user_name
528 if ($trial_create->trial_name_already_exists()) {
529 $c->stash->{rest} = {error => "Trial name \"".$trial_create->get_trial_name()."\" already exists" };
530 return;
533 my $save;
534 try {
535 $save = $trial_create->save_trial();
536 } catch {
537 $save->{'error'} = $_;
540 if ($save->{'error'}) {
541 print STDERR "Error saving trial: ".$save->{'error'};
542 $c->stash->{rest} = {error => $save->{'error'}};
543 return;
544 } elsif ($save->{'trial_id'}) {
546 $design_index++;
548 if ($folder_id) {
550 my $folder1 = CXGN::Trial::Folder->new(
552 bcs_schema => $chado_schema,
553 folder_id => $save->{'trial_id'},
555 $folder1->associate_parent($folder_id);
559 $c->stash->{rest} = {success => "1",};
560 return;
564 sub verify_stock_list : Path('/ajax/trial/verify_stock_list') : ActionClass('REST') { }
566 sub verify_stock_list_POST : Args(0) {
567 my ($self, $c) = @_;
568 my $schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
569 my @stock_names;
570 my $error;
571 my %errors;
572 if ($c->req->param('stock_list')) {
573 @stock_names = @{_parse_list_from_json($c->req->param('stock_list'))};
576 if (!@stock_names) {
577 $c->stash->{rest} = {error => "No stock names supplied"};
578 $c->detach;
581 my $lv = CXGN::List::Validate->new();
582 my @accessions_missing = @{$lv->validate($schema,'accessions',\@stock_names)->{'missing'}};
584 if (scalar(@accessions_missing) > 0){
585 my $error = 'The following accessions are not valid in the database, so you must add them first: '.join ',', @accessions_missing;
586 $c->stash->{rest} = {error => $error};
587 } else {
588 $c->stash->{rest} = {
589 success => "1",
594 sub verify_seedlot_list : Path('/ajax/trial/verify_seedlot_list') : ActionClass('REST') { }
596 sub verify_seedlot_list_POST : Args(0) {
597 my ($self, $c) = @_;
598 my $schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
599 my @stock_names;
600 my @seedlot_names;
601 if ($c->req->param('stock_list')) {
602 @stock_names = @{_parse_list_from_json($c->req->param('stock_list'))};
604 if ($c->req->param('seedlot_list')) {
605 @seedlot_names = @{_parse_list_from_json($c->req->param('seedlot_list'))};
607 my $return = CXGN::Stock::Seedlot->verify_seedlot_stock_lists($schema, \@stock_names, \@seedlot_names);
609 if (exists($return->{error})){
610 $c->stash->{rest} = { error => $return->{error} };
611 $c->detach();
613 if (exists($return->{success})){
614 $c->stash->{rest} = {
615 success => "1",
616 seedlot_hash => $return->{seedlot_hash}
621 sub _parse_list_from_json {
622 my $list_json = shift;
623 my $json = new JSON;
624 if ($list_json) {
625 my $decoded_list = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($list_json);
626 #my $decoded_list = decode_json($list_json);
627 my @array_of_list_items = @{$decoded_list};
628 return \@array_of_list_items;
630 else {
631 return;
635 sub _parse_design_from_json {
636 my $design_json = shift;
637 my $json = new JSON;
638 if ($design_json) {
639 my $decoded_json = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($design_json);
640 #my $decoded_json = decode_json($design_json);
641 #my %design = %{$decoded_json};
642 return $decoded_json;
644 else {
645 return;
649 ###################################################################################
651 sub upload_trial_file : Path('/ajax/trial/upload_trial_file') : ActionClass('REST') { }
653 sub upload_trial_file_POST : Args(0) {
654 my ($self, $c) = @_;
656 print STDERR "Check 1: ".localtime()."\n";
658 my $chado_schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
659 my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
660 my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
661 my $dbh = $c->dbc->dbh;
662 my $program = $c->req->param('trial_upload_breeding_program');
663 my $trial_location = $c->req->param('trial_upload_location');
664 my $trial_name = $c->req->param('trial_upload_name');
665 my $trial_year = $c->req->param('trial_upload_year');
666 my $trial_type = $c->req->param('trial_upload_trial_type');
667 my $trial_description = $c->req->param('trial_upload_description');
668 my $trial_design_method = $c->req->param('trial_upload_design_method');
669 my $upload = $c->req->upload('trial_uploaded_file');
670 my $parser;
671 my $parsed_data;
672 my $upload_original_name = $upload->filename();
673 my $upload_tempfile = $upload->tempname;
674 my $subdirectory = "trial_upload";
675 my $archived_filename_with_path;
676 my $md5;
677 my $validate_file;
678 my $parsed_file;
679 my $parse_errors;
680 my %parsed_data;
681 my %upload_metadata;
682 my $time = DateTime->now();
683 my $timestamp = $time->ymd()."_".$time->hms();
684 my $user_id;
685 my $user_name;
686 my $error;
688 print STDERR "Check 2: ".localtime()."\n";
690 if ($upload_original_name =~ /\s/ || $upload_original_name =~ /\// || $upload_original_name =~ /\\/ ) {
691 print STDERR "File name must not have spaces or slashes.\n";
692 $c->stash->{rest} = {error => "Uploaded file name must not contain spaces or slashes." };
693 return;
696 if (!$c->user()) {
697 print STDERR "User not logged in... not uploading a trial.\n";
698 $c->stash->{rest} = {error => "You need to be logged in to upload a trial." };
699 return;
701 if (!any { $_ eq "curator" || $_ eq "submitter" } ($c->user()->roles) ) {
702 $c->stash->{rest} = {error => "You have insufficient privileges to upload a trial." };
703 return;
706 $user_id = $c->user()->get_object()->get_sp_person_id();
708 $user_name = $c->user()->get_object()->get_username();
710 ## Store uploaded temporary file in archive
711 my $uploader = CXGN::UploadFile->new({
712 tempfile => $upload_tempfile,
713 subdirectory => $subdirectory,
714 archive_path => $c->config->{archive_path},
715 archive_filename => $upload_original_name,
716 timestamp => $timestamp,
717 user_id => $user_id,
718 user_role => $c->user->get_object->get_user_type()
720 $archived_filename_with_path = $uploader->archive();
721 $md5 = $uploader->get_md5($archived_filename_with_path);
722 if (!$archived_filename_with_path) {
723 $c->stash->{rest} = {error => "Could not save file $upload_original_name in archive",};
724 return;
726 unlink $upload_tempfile;
728 print STDERR "Check 3: ".localtime()."\n";
730 $upload_metadata{'archived_file'} = $archived_filename_with_path;
731 $upload_metadata{'archived_file_type'}="trial upload file";
732 $upload_metadata{'user_id'}=$user_id;
733 $upload_metadata{'date'}="$timestamp";
735 #parse uploaded file with appropriate plugin
736 $parser = CXGN::Trial::ParseUpload->new(chado_schema => $chado_schema, filename => $archived_filename_with_path);
737 $parser->load_plugin('TrialExcelFormat');
738 $parsed_data = $parser->parse();
742 if (!$parsed_data) {
743 my $return_error = '';
745 if (! $parser->has_parse_errors() ){
746 $return_error = "Could not get parsing errors";
747 $c->stash->{rest} = {error_string => $return_error,};
750 else {
751 $parse_errors = $parser->get_parse_errors();
752 #print STDERR Dumper $parse_errors;
754 foreach my $error_string (@{$parse_errors->{'error_messages'}}){
755 $return_error=$return_error.$error_string."<br>";
759 $c->stash->{rest} = {error_string => $return_error, missing_accessions => $parse_errors->{'missing_accessions'}};
760 return;
763 print STDERR "Check 4: ".localtime()."\n";
765 #print STDERR Dumper $parsed_data;
767 my $save;
768 my $coderef = sub {
770 my $trial_create = CXGN::Trial::TrialCreate->new({
771 chado_schema => $chado_schema,
772 dbh => $dbh,
773 trial_year => $trial_year,
774 trial_description => $trial_description,
775 trial_location => $trial_location,
776 trial_type => $trial_type,
777 trial_name => $trial_name,
778 user_name => $user_name, #not implemented
779 design_type => $trial_design_method,
780 design => $parsed_data,
781 program => $program,
782 upload_trial_file => $upload,
783 operator => $c->user()->get_object()->get_username()
785 $save = $trial_create->save_trial();
787 if ($save->{error}){
788 $chado_schema->txn_rollback();
793 try {
794 $chado_schema->txn_do($coderef);
795 } catch {
796 print STDERR "Transaction Error: $_\n";
797 $save->{'error'} = $_;
800 #print STDERR "Check 5: ".localtime()."\n";
801 if ($save->{'error'}) {
802 print STDERR "Error saving trial: ".$save->{'error'};
803 $c->stash->{rest} = {error => $save->{'error'}};
804 return;
805 } elsif ($save->{'trial_id'}) {
806 $c->stash->{rest} = {success => "1"};
807 return;