Merge remote branch 'kc/new/bug_5370' into kcmaster
[koha.git] / cataloguing / additem.pl
index f2f1922..9676fd6 100755 (executable)
 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along with
-# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
-# Suite 330, Boston, MA  02111-1307 USA
+# You should have received a copy of the GNU General Public License along
+# with Koha; if not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
-use CGI;
 use strict;
+#use warnings; FIXME - Bug 2505
+use CGI;
 use C4::Auth;
 use C4::Output;
 use C4::Biblio;
@@ -32,6 +33,8 @@ use C4::Dates;
 
 use MARC::File::XML;
 
+my $dbh = C4::Context->dbh;
+
 sub find_value {
     my ($tagfield,$insubfield,$record) = @_;
     my $result;
@@ -58,23 +61,63 @@ sub get_item_from_barcode {
     return($result);
 }
 
+sub set_item_default_location {
+    my $itemnumber = shift;
+    if ( C4::Context->preference('NewItemsDefaultLocation') ) {
+        my $item = GetItem( $itemnumber );
+        $item->{'permanent_location'} = $item->{'location'};
+        $item->{'location'} = C4::Context->preference('NewItemsDefaultLocation');
+        ModItem( $item, undef, $itemnumber);
+    }
+}
+
+# NOTE: This code is subject to change in the future with the implemenation of ajax based autobarcode code
+# NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
+sub _increment_barcode {
+    my ($record, $frameworkcode) = @_;
+    my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
+    unless ($record->field($tagfield)->subfield($tagsubfield)) {
+        my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
+        $sth_barcode->execute;
+        my ($newbarcode) = $sth_barcode->fetchrow;
+        $newbarcode++;
+        # OK, we have the new barcode, now create the entry in MARC record
+        my $fieldItem = $record->field($tagfield);
+        $record->delete_field($fieldItem);
+        $fieldItem->add_subfields($tagsubfield => $newbarcode);
+        $record->insert_fields_ordered($fieldItem);
+    }
+    return $record;
+}
+
+
 my $input = new CGI;
-my $dbh = C4::Context->dbh;
 my $error        = $input->param('error');
 my $biblionumber = $input->param('biblionumber');
 my $itemnumber   = $input->param('itemnumber');
 my $op           = $input->param('op');
 
+my $frameworkcode = &GetFrameworkCode($biblionumber);
+
+# Defining which userflag is needing according to the framework currently used
+my $userflags;
+if (defined $input->param('frameworkcode')) {
+    $userflags = ($input->param('frameworkcode') eq 'FA') ? "fast_cataloging" : "edit_items";
+}
+
+if (not defined $userflags) {
+    $userflags = ($frameworkcode eq 'FA') ? "fast_cataloging" : "edit_items";
+}
+
 my ($template, $loggedinuser, $cookie)
     = get_template_and_user({template_name => "cataloguing/additem.tmpl",
                  query => $input,
                  type => "intranet",
                  authnotrequired => 0,
-                 flagsrequired => {editcatalogue => 1},
+                 flagsrequired => {editcatalogue => $userflags},
                  debug => 1,
                  });
 
-my $frameworkcode = &GetFrameworkCode($biblionumber);
 
 my $today_iso = C4::Dates->today('iso');
 $template->param(today_iso => $today_iso);
@@ -97,33 +140,110 @@ if ($op eq "additem") {
     my @indicator = $input->param('indicator');
     my $xml = TransformHtmlToXml(\@tags,\@subfields,\@values,\@indicator,\@ind_tag, 'ITEM');
     my $record = MARC::Record::new_from_xml($xml, 'UTF-8');
-    # if autoBarcode is set to 'incremental', calculate barcode...
-       # NOTE: This code is subject to change in 3.2 with the implemenation of ajax based autobarcode code
-       # NOTE: 'incremental' is the ONLY autoBarcode option available to those not using javascript
+
+    # type of add
+    my $add_submit                 = $input->param('add_submit');
+    my $add_duplicate_submit       = $input->param('add_duplicate_submit');
+    my $add_multiple_copies_submit = $input->param('add_multiple_copies_submit');
+    my $number_of_copies           = $input->param('number_of_copies');
+
     if (C4::Context->preference('autoBarcode') eq 'incremental') {
-        my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
-        unless ($record->field($tagfield)->subfield($tagsubfield)) {
-            my $sth_barcode = $dbh->prepare("select max(abs(barcode)) from items");
-            $sth_barcode->execute;
-            my ($newbarcode) = $sth_barcode->fetchrow;
-            $newbarcode++;
-            # OK, we have the new barcode, now create the entry in MARC record
-            my $fieldItem = $record->field($tagfield);
-            $record->delete_field($fieldItem);
-            $fieldItem->add_subfields($tagsubfield => $newbarcode);
-            $record->insert_fields_ordered($fieldItem);
-        }
+        $record = _increment_barcode($record, $frameworkcode);
     }
-# check for item barcode # being unique
+
     my $addedolditem = TransformMarcToKoha($dbh,$record);
-    my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
-    push @errors,"barcode_not_unique" if($exist_itemnumber);
-    # if barcode exists, don't create, but report The problem.
-    my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber) unless ($exist_itemnumber);
-    $nextop = "additem";
-    if ($exist_itemnumber) {
+
+    # If we have to add or add & duplicate, we add the item
+    if ($add_submit || $add_duplicate_submit) {
+       # check for item barcode # being unique
+       my $exist_itemnumber = get_item_from_barcode($addedolditem->{'barcode'});
+       push @errors,"barcode_not_unique" if($exist_itemnumber);
+       # if barcode exists, don't create, but report The problem.
+    unless ($exist_itemnumber) {
+           my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
+        set_item_default_location($oldbibitemnum);
+    }
+       $nextop = "additem";
+       if ($exist_itemnumber) {
+           $itemrecord = $record;
+       }
+    }
+
+    # If we have to add & duplicate
+    if ($add_duplicate_submit) {
         $itemrecord = $record;
+        if (C4::Context->preference('autoBarcode') eq 'incremental') {
+            $itemrecord = _increment_barcode($itemrecord, $frameworkcode);
+        }
+        else {
+            # we have to clear the barcode field in the duplicate item record to make way for the new one generated by the javascript plugin
+            my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
+            my $fieldItem = $itemrecord->field($tagfield);
+            $itemrecord->delete_field($fieldItem);
+            $fieldItem->delete_subfields($tagsubfield);
+            $itemrecord->insert_fields_ordered($fieldItem);
+        }
+    }
+
+    # If we have to add multiple copies
+    if ($add_multiple_copies_submit) {
+
+        use C4::Barcodes;
+        my $barcodeobj = C4::Barcodes->new;
+        my $oldbarcode = $addedolditem->{'barcode'};
+        my ($tagfield,$tagsubfield) = &GetMarcFromKohaField("items.barcode",$frameworkcode);
+
+       # If there is a barcode and we can't find him new values, we can't add multiple copies
+        my $testbarcode = $barcodeobj->next_value($oldbarcode) if $barcodeobj;
+       if ($oldbarcode && !$testbarcode) {
+
+           push @errors, "no_next_barcode";
+           $itemrecord = $record;
+
+       } else {
+       # We add each item
+
+           # For the first iteration
+           my $barcodevalue = $oldbarcode;
+           my $exist_itemnumber;
+
+
+           for (my $i = 0; $i < $number_of_copies;) {
+
+               # If there is a barcode
+               if ($barcodevalue) {
+
+                   # Getting a new barcode (if it is not the first iteration or the barcode we tried already exists)
+                   $barcodevalue = $barcodeobj->next_value($oldbarcode) if ($i > 0 || $exist_itemnumber);
+
+                   # Putting it into the record
+                   if ($barcodevalue) {
+                       $record->field($tagfield)->update($tagsubfield => $barcodevalue);
+                   }
+
+                   # Checking if the barcode already exists
+                   $exist_itemnumber = get_item_from_barcode($barcodevalue);
+               }
+
+               # Adding the item
+        if (!$exist_itemnumber) {
+            my ($oldbiblionumber,$oldbibnum,$oldbibitemnum) = AddItemFromMarc($record,$biblionumber);
+            set_item_default_location($oldbibitemnum);
+
+            # We count the item only if it was really added
+            # That way, all items are added, even if there was some already existing barcodes
+            # FIXME : Please note that there is a risk of infinite loop here if we never find a suitable barcode
+            $i++;
+        }
+
+               # Preparing the next iteration
+               $oldbarcode = $barcodevalue;
+           }
+           undef($itemrecord);
+       }
     }
+
+
 #-------------------------------------------------------------------------------
 } elsif ($op eq "edititem") {
 #-------------------------------------------------------------------------------
@@ -134,26 +254,28 @@ if ($op eq "additem") {
 } elsif ($op eq "delitem") {
 #-------------------------------------------------------------------------------
     # check that there is no issue on this item before deletion.
-    my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
-    $sth->execute($itemnumber);
-    my $onloan=$sth->fetchrow;
-       $sth->finish();
-    $nextop="additem";
-    if ($onloan){
-        push @errors,"book_on_loan";
-    } else {
-               # check it doesnt have a waiting reserve
-               $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
-               $sth->execute($itemnumber);
-               my $reserve=$sth->fetchrow;
-               unless ($reserve){
-                       &DelItem($dbh,$biblionumber,$itemnumber);
-                       print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
-            exit;
-               }
-        push @errors,"book_reserved";
+    $error = &DelItemCheck($dbh,$biblionumber,$itemnumber);
+    if($error == 1){
+        print $input->redirect("additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode");
+    }else{
+        push @errors,$error;
+        $nextop="additem";
     }
 #-------------------------------------------------------------------------------
+} elsif ($op eq "delallitems") {
+#-------------------------------------------------------------------------------
+    my @biblioitems = &GetBiblioItemByBiblioNumber($biblionumber);
+    foreach my $biblioitem (@biblioitems){
+        my $items = &GetItemsByBiblioitemnumber($biblioitem->{biblioitemnumber});
+
+        foreach my $item (@$items){
+            # FIXME although it won't delete items that have loans
+            # or waiting holds on them, should explicitly tell operator
+            # about items that are not deleted
+            &DelItemCheck($dbh,$biblionumber,$item->{itemnumber});
+        }
+       }
+#-------------------------------------------------------------------------------
 } elsif ($op eq "saveitem") {
 #-------------------------------------------------------------------------------
     # rebuild
@@ -197,8 +319,7 @@ my ($branchtagfield, $branchtagsubfield) = &GetMarcFromKohaField("items.homebran
 
 foreach my $field (@fields) {
     next if ($field->tag()<10);
-    my @subf = $field->subfields;
-    (defined @subf) or @subf = ();
+    my @subf = $field->subfields or (); # don't use ||, as that forces $field->subfelds to be interpreted in scalar context
     my %this_row;
 # loop through each subfield
     for my $i (0..$#subf) {
@@ -252,13 +373,15 @@ foreach my $subfield_code (sort keys(%witness)) {
 # now, build the item form for entering a new item
 my @loop_data =();
 my $i=0;
-my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib");
 
-my $onlymine = C4::Context->preference('IndependantBranches') && 
-               C4::Context->userenv                           && 
-               C4::Context->userenv->{flags}!=1               && 
-               C4::Context->userenv->{branch};
-my $branches = GetBranches($onlymine);  # build once ahead of time, instead of multiple times later.
+my $branches = GetBranchesLoop();  # build once ahead of time, instead of multiple times later.
+my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
+
+# Getting the fields where the item location is
+my ($location_field, $location_subfield) = GetMarcFromKohaField('items.location', $frameworkcode);
+
+# Getting the name of the authorised values' category for item location
+my $item_location_category = $tagslib->{$location_field}->{$location_subfield}->{'authorised_value'};
 
 foreach my $tag (sort keys %{$tagslib}) {
 # loop through each subfield
@@ -286,19 +409,13 @@ foreach my $tag (sort keys %{$tagslib}) {
     unless ($value) {
         $value = $tagslib->{$tag}->{$subfield}->{defaultvalue};
         # get today date & replace YYYY, MM, DD if provided in the default value
-        my ( $year, $month, $day ) = split ',', $today_iso;
+        my ( $year, $month, $day ) = split ',', $today_iso;     # FIXME: iso dates don't have commas!
         $value =~ s/YYYY/$year/g;
         $value =~ s/MM/$month/g;
         $value =~ s/DD/$day/g;
     }
     $subfield_data{visibility} = "display:none;" if (($tagslib->{$tag}->{$subfield}->{hidden} > 4) || ($tagslib->{$tag}->{$subfield}->{hidden} < -4));
     # testing branch value if IndependantBranches.
-    # my $test = (C4::Context->preference("IndependantBranches")) &&
-    #          ($tag eq $branchtagfield) && ($subfield eq $branchtagsubfield) &&
-    #          (C4::Context->userenv->{flags} != 1) && ($value) && ($value ne C4::Context->userenv->{branch}) ;
-    # $test and print $input->redirect(".pl?biblionumber=$biblionumber") and exit;
-        # search for itemcallnumber if applicable
-    my $pref_itemcallnumber = C4::Context->preference('itemcallnumber');
     if (!$value && $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber) {
         my $CNtag       = substr($pref_itemcallnumber, 0, 3);
         my $CNsubfield  = substr($pref_itemcallnumber, 3, 1);
@@ -311,7 +428,7 @@ foreach my $tag (sort keys %{$tagslib}) {
         }
     }
 
-    my $attributes_no_value = qq(tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
+    my $attributes_no_value = qq(id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" );
     my $attributes          = qq($attributes_no_value value="$value" );
     if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
       my @authorised_values;
@@ -319,27 +436,28 @@ foreach my $tag (sort keys %{$tagslib}) {
       # builds list, depending on authorised value...
   
       if ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "branches" ) {
-          foreach my $thisbranch ( sort keys %$branches ) {
-              push @authorised_values, $thisbranch;
-              $authorised_lib{$thisbranch} = $branches->{$thisbranch}->{'branchname'};
+          foreach my $thisbranch (@$branches) {
+              push @authorised_values, $thisbranch->{value};
+              $authorised_lib{$thisbranch->{value}} = $thisbranch->{branchname};
+              # in edit item this is set to the data value otherwise use default
+              if ($op ne 'edititem' && $thisbranch->{selected} ) {
+                  $value = $thisbranch->{value};
+              }
           }
       }
       elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
           my $sth = $dbh->prepare("select itemtype,description from itemtypes order by description");
           $sth->execute;
-          my $itemtype;     # FIXME: double declaration of $itemtype
           while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
               push @authorised_values, $itemtype;
               $authorised_lib{$itemtype} = $description;
           }
 
           unless ( $value ) {
-              my $default_itemtype;
               my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
               $itype_sth->execute( $biblionumber );
-              ( $default_itemtype ) = $itype_sth->fetchrow_array;
-              $value = $default_itemtype;
+              ( $value ) = $itype_sth->fetchrow_array;
           }
   
           #---- class_sources
@@ -363,13 +481,31 @@ foreach my $tag (sort keys %{$tagslib}) {
       }
       else {
           push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
-          $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
+
+         # Are we dealing with item location ?
+          my $item_location = ($tagslib->{$tag}->{$subfield}->{authorised_value} eq $item_location_category) ? 1 : 0;
+
+          # If so, we sort by authorised_value, else by libelle
+          my $orderby = $item_location ? 'authorised_value' : 'lib';
+
+          my $authorised_values_sth = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY $orderby");
+
+          $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value});
+
+
           while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
-              push @authorised_values, $value;
-              $authorised_lib{$value} = $lib;
+            push @authorised_values, $value;
+               if ($tagslib->{$tag}->{$subfield}->{authorised_value} eq $item_location_category) {
+                               $authorised_lib{$value} = $value . " - " . $lib;
+               } else {
+                               $authorised_lib{$value} = $lib;
+               }
+
+               # For item location, we show the code and the libelle
+               $authorised_lib{$value} = ($item_location) ? $value . " - " . $lib : $lib;
           }
       }
-      $subfield_data{marc_value} =CGI::scrolling_list( # FIXME: factor out scrolling_list
+      $subfield_data{marc_value} =CGI::scrolling_list(      # FIXME: factor out scrolling_list
           -name     => "field_value",
           -values   => \@authorised_values,
           -default  => $value,
@@ -377,7 +513,7 @@ foreach my $tag (sort keys %{$tagslib}) {
           -override => 1,
           -size     => 1,
           -multiple => 0,
-          -tabindex => 1,
+         # -tabindex => 1,
           -id       => "tag_".$tag."_subfield_".$subfield."_".$index_subfield,
           -class    => "input_marceditor",
       );
@@ -444,6 +580,7 @@ $template->param(
     itemtagsubfield  => $itemtagsubfield,
     op      => $nextop,
     opisadd => ($nextop eq "saveitem") ? 0 : 1,
+    C4::Search::enabled_staff_search_views,
 );
 foreach my $error (@errors) {
     $template->param($error => 1);