hook up and test duplication server-side logic
Tara L Andrews [Mon, 24 Jun 2013 19:48:42 +0000 (21:48 +0200)]
lib/stemmaweb/Controller/Relation.pm
root/js/relationship.js
root/src/relate.tt

index e59cd7e..52bc5f9 100644 (file)
@@ -390,18 +390,21 @@ sub reading :Chained('text') :PathPart :Args(1) {
 
 =head2 duplicate
 
- POST relation/$textid/duplicate/$id/ { witnesses }
+ POST relation/$textid/duplicate { data }
  
-Duplicates the given reading, detaching the witnesses specified in the list to use
-the new reading instead of the old. The 'witnesses' param should be a JSON array.
+Duplicates the requested readings, detaching the witnesses specified in
+the list to use the new reading(s) instead of the old. The data to be
+passed should be a JSON structure:
+
+ { readings: rid1,rid2,rid3,...
+   witnesses: [ wit1, ... ] }
 
 =cut
 
-sub duplicate :Chained('text') :PathPart :Args(1) {
-       my( $self, $c, $reading_id ) = @_;
+sub duplicate :Chained('text') :PathPart :Args(0) {
+       my( $self, $c ) = @_;
        my $tradition = delete $c->stash->{'tradition'};
        my $collation = $tradition->collation;
-       my $rdg = $collation->reading( $reading_id );
        my $m = $c->model('Directory');
        if( $c->request->method eq 'POST' ) {
                if( $c->stash->{'permission'} ne 'full' ) {
@@ -413,11 +416,62 @@ sub duplicate :Chained('text') :PathPart :Args(1) {
                }
                my $errmsg;
                my $response = {};
-               if( $c->request->param('witnesses') ) {
-                       my $witlist = from_json( $c->request->param('witnesses') );
+               # Sort out which readings need to be duplicated from the set given, and
+               # ensure that all the given wits bear each relevant reading.
+               
+               my %wits = ();
+               map { $wits{$_} = 1 } $c->request->param('witnesses[]');
+               my %rdgranks = ();
+               foreach my $rid ( $c->request->param('readings[]') ) {
+                       my $numwits = 0;
+                       my $rdg = $collation->reading( $rid );
+                       foreach my $rwit ( $rdg->witnesses( $rid ) ) {
+                               $numwits++ if exists $wits{$rwit};
+                       }
+                       if( $numwits > 0 && $numwits < keys( %wits ) ) {
+                               $errmsg = "Reading $rid contains some but not all of the specified witnesses.";
+                               last;
+                       } elsif( exists $rdgranks{ $rdg->rank } ) {
+                               $errmsg = "More than one reading would be detached along with $rid at rank " . $rdg->rank;
+                               last;
+                       } else {
+                               $rdgranks{ $rdg->rank } = $rid;
+                       }
+               }
+               
+               # Now check that the readings make a single sequence.
+               unless( $errmsg ) {
+                       my $prior;
+                       foreach my $rank ( sort { $a <=> $b } keys %rdgranks ) {
+                               my $rid = $rdgranks{$rank};
+                               if( $prior ) {
+                                       # Check that there is only one path between $prior and $rdg.
+                                       foreach my $wit ( keys %wits ) {
+                                               unless( $collation->prior_reading( $rid, $wit ) eq $prior ) {
+                                                       $errmsg = "Diverging witness paths from $prior to $rid at $wit";
+                                                       last;
+                                               }
+                                       }
+                               }
+                               $prior = $rid;
+                       }
+               }
+               
+               # Abort if we've run into a problem.
+               if( $errmsg ) {
+                       $c->stash->{'result'} = { 'error' => $errmsg };
+                       $c->response->status( '403' );
+                       $c->forward('View::JSON');
+                       return;
+               }
+               
+               # Otherwise, do the dirty work.
+               my @witlist = keys %wits;
+               foreach my $rank ( sort { $a <=> $b } keys %rdgranks ) {
                        my $newrdg;
+                       my $reading_id = $rdgranks{$rank};
                        try {
-                               $newrdg = $collation->duplicate_reading( $reading_id, @$witlist );
+                               $newrdg = $collation->duplicate_reading( $reading_id, @witlist );
                        } catch( Text::Tradition::Error $e ) {
                                $c->response->status( '403' );
                                $errmsg = $e->message;
@@ -427,13 +481,15 @@ sub duplicate :Chained('text') :PathPart :Args(1) {
                                $errmsg = 'Something went wrong with the request';      
                        }
                        if( $newrdg ) {
-                               $response = { reading => $newrdg->id, witnesses => $witlist };
+                               $response->{$reading_id} = _reading_struct( $newrdg );
                        }
+               } 
+               if( $errmsg ) {
+                       $c->stash->{'result'} = { 'error' => $errmsg };
                } else {
-                       $c->response->status( '403' );
-                       $errmsg = "At least one witness must be specified for a duplication";
+                       $m->save( $collation );
+                       $c->stash->{'result'} = $response;
                }
-               $c->stash->{'result'} = $errmsg ? { 'error' => $errmsg } : $response;
        }
        $c->forward('View::JSON');
 }
index 7298613..0b0b959 100644 (file)
@@ -691,6 +691,7 @@ function Marquee() {
             var cx_max = p.matrixTransform(tf).x;
             var cy_max = p.matrixTransform(tf).y;
             //select any node with its center inside the marquee
+            var readings = [];
             //also merge witness sets from nodes
             var witnesses = [];
             $('#svgenlargement ellipse').each( function( index ) {
@@ -700,16 +701,28 @@ function Marquee() {
                     if( cy > cy_min && cy < cy_max) {
                         // we actually heve no real 'selected' state for nodes, except coloring
                         $(this).attr( 'fill', '#9999ff' );
+                        // Take note of the selected reading(s) and applicable witness(es)
+                        // so we can populate the multipleselect-form 
+                        readings.push( $(this).parent().attr('id') );
                         var this_witnesses = $(this).data( 'node_obj' ).get_witnesses();
                         witnesses = arrayUnique( witnesses.concat( this_witnesses ) );
                     }
                 }
             });
             if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
-                //add interesectio of witnesses sets to the multi select form and open it
+                //add intersection of witnesses sets to the multi select form and open it
+                $('#detach_collated_form').empty();
+                $.each( readings, function( index, value ) {
+                       $('#detach_collated_form').append( $('<input>').attr(
+                       "type", "hidden").attr("name", "readings[]").attr(
+                               "value", value ) );
+                   });
                 $.each( witnesses, function( index, value ) {
-                    $('#multipleselect-form').append( '<input type="checkbox" name="witnesses" value="' + value + '">' + value + '<br>' );
+                    $('#detach_collated_form').append( 
+                       '<input type="checkbox" name="witnesses[]" value="' + value 
+                       + '">' + value + '<br>' );
                 });
+                $('#multiple_selected_readings').attr('value', readings.join(',') );
                 $('#multipleselect-form').dialog( 'open' );
             }
             self.svg_rect.remove( $('#marquee') );
@@ -928,28 +941,33 @@ $(document).ready(function () {
     close: function() {}
   });
 
-  var multipleselect_buttonset = {
-        cancel: function() { $( this ).dialog( "close" ); },
-        button1: function () {  },
-        button2: function() {  }
-  };   
-
   $( "#multipleselect-form" ).dialog({
     autoOpen: false,
     height: 150,
     width: 250,
     modal: true,
+    buttons: {
+       Cancel: function() { $( this ).dialog( "close" ); },
+       Detach: function ( evt ) { 
+               $(evt.target).button("disable");
+               var form_values = $('#detach_collated_form').serialize();
+                       ncpath = getTextURL( 'duplicate' );
+                       var jqjson = $.post( ncpath, form_values, function(data) {
+                               $.each( data, function(reading, newreading) { 
+                                       alert( "Would detach reading " + newreading['id'] + " from " + reading );
+                               });
+                               $(evt.target).button("enable");
+                       });
+               }
+    },
     create: function(event, ui) {
         var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
         buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
     },
     open: function() {
         $( this ).dialog( "option", "width", 200 );
-        $( this ).dialog( "option", "buttons",
-            [{ text: "Button_1", click: multipleselect_buttonset['button1'] },
-             { text: "Button_2", click: multipleselect_buttonset['button2'] },
-             { text: "Cancel", click: multipleselect_buttonset['cancel'] }] );
         $(".ui-widget-overlay").css("background", "none");
+        $('#multipleselect-form-status').empty();
         $("#dialog_overlay").show();
         $("#dialog_overlay").height( $("#enlargement_container").height() );
         $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
@@ -959,7 +977,25 @@ $(document).ready(function () {
         marquee.unselect();
         $("#dialog_overlay").hide();
     }
-  });
+  }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
+               if( ajaxSettings.url == getTextURL('duplicate') 
+                       && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
+                       var error;
+                       if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
+                               error = 'You are not authorized to modify this tradition. (Try logging in again?)';
+                       } else {
+                               try {
+                                       var errobj = jQuery.parseJSON( jqXHR.responseText );
+                                       error = errobj.error + '</br>The relationship cannot be made.</p>';
+                               } catch(e) {
+                                       error = jqXHR.responseText;
+                               }
+                       }
+                       $('#multipleselect-form-status').append( '<p class="error">Error: ' + error );
+               }
+               $(event.target).parent().find('.ui-button').button("enable");
+       });
+
 
   // Helpers for relationship deletion
   
index 36403b4..15ae28d 100644 (file)
@@ -90,11 +90,10 @@ $(document).ready(function () {
        </div>
 
        <div id="multipleselect-form" title="Multiple nodes selected...">
-               <form id="multipleselect_form" action="#">
-                       <input type="hidden" name="source_id" id="delete_source_node_id"/>
-                       <input type="hidden" name="target_id" id="delete_target_node_id"/>
+               <div id="multipleselect-form-status"></div>
+               <div id="multipleselect-form-text">Select witness(es) to detach:</div>
+               <form id="detach_collated_form" action="#">
                </form>
-               <div id="multipleselect-form-text">This should turn into a proper form.</div>
        </div>
        
        <div id="reading-form" title="Reading info...">