Bug 14100: (follow-up) Language overlay for item types
[koha.git] / C4 / Items.pm
index ab2456b..ec51058 100644 (file)
@@ -5,18 +5,18 @@ package C4::Items;
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY 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.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use strict;
 #use warnings; FIXME - Bug 2505
@@ -25,7 +25,7 @@ use Carp;
 use C4::Context;
 use C4::Koha;
 use C4::Biblio;
-use C4::Dates qw/format_date format_date_in_iso/;
+use Koha::DateUtils;
 use MARC::Record;
 use C4::ClassSource;
 use C4::Log;
@@ -174,6 +174,8 @@ sub GetItem {
         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
     }
        #if we don't have an items.itype, use biblioitems.itemtype.
+    # FIXME this should respect the itypes systempreference
+    # if (C4::Context->preference('item-level_itypes')) {
        if( ! $data->{'itype'} ) {
                my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems  WHERE biblionumber = ?");
                $sth->execute($data->{'biblionumber'});
@@ -430,7 +432,7 @@ other purposes, C<ModItem> should be used.
 
 This function uses the hash %default_values_for_mod_from_marc,
 which contains default values for item fields to
-apply when modifying an item.  This is needed beccause
+apply when modifying an item.  This is needed because
 if an item field's value is cleared, TransformMarcToKoha
 does not include the column in the
 hash that's passed to ModItem, which without
@@ -466,6 +468,7 @@ sub _build_default_values_for_mod_marc {
         itemcallnumber           => undef,
         itemlost                 => 0,
         itemnotes                => undef,
+        itemnotes_nonpublic      => undef,
         itype                    => undef,
         location                 => undef,
         permanent_location       => undef,
@@ -482,11 +485,12 @@ sub _build_default_values_for_mod_marc {
         withdrawn                => 0,
     };
     while ( my ( $field, $default_value ) = each %$default_values ) {
-        $field =~ s|[^\.]*\.?(.*)|items.$1|;
+        my $kohafield = $field;
+        $kohafield =~ s|^([^\.]+)$|items.$1|;
         $default_values_for_mod_from_marc{$frameworkcode}{$field} =
           $default_value
           if C4::Koha::IsKohaFieldLinked(
-            { kohafield => $field, frameworkcode => $frameworkcode } );
+            { kohafield => $kohafield, frameworkcode => $frameworkcode } );
     }
     return $default_values_for_mod_from_marc{$frameworkcode};
 }
@@ -644,8 +648,8 @@ C<$itemnum> is the item number
 sub ModDateLastSeen {
     my ($itemnumber) = @_;
     
-    my $today = C4::Dates->new();    
-    ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
+    my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
+    ModItem({ itemlost => 0, datelastseen => $today }, undef, $itemnumber);
 }
 
 =head2 DelItem
@@ -787,7 +791,7 @@ C<items.notforloan> field.
 NOTE: does B<not> return an individual item's
 status.
 
-Can be MARC dependant.
+Can be MARC dependent.
 fwkcode is optional.
 But basically could be can be loan or not
 Create a status selector with the following code
@@ -957,7 +961,7 @@ sub GetItemLocation {
 
 =head2 GetLostItems
 
-  $items = GetLostItems( $where, $orderby );
+  $items = GetLostItems( $where );
 
 This function gets a list of lost items.
 
@@ -971,9 +975,6 @@ and the value to match as value. For example:
 { barcode    => 'abc123',
   homebranch => 'CPL',    }
 
-C<$orderby> is a field of the items table by which the resultset
-should be orderd.
-
 =item return:
 
 C<$items> is a reference to an array full of hashrefs with columns
@@ -982,7 +983,7 @@ from the "items" table as keys.
 =item usage in the perl script:
 
   my $where = { barcode => '0001548' };
-  my $items = GetLostItems( $where, "homebranch" );
+  my $items = GetLostItems( $where );
   $template->param( itemsloop => $items );
 
 =back
@@ -992,12 +993,11 @@ from the "items" table as keys.
 sub GetLostItems {
     # Getting input args.
     my $where   = shift;
-    my $orderby = shift;
     my $dbh     = C4::Context->dbh;
 
     my $query   = "
         SELECT title, author, lib, itemlost, authorised_value, barcode, datelastseen, price, replacementprice, homebranch,
-               itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber
+               itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber, itemcallnumber
         FROM   items
             LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
             LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
@@ -1012,11 +1012,6 @@ sub GetLostItems {
         $query .= " AND $key LIKE ?";
         push @query_parameters, "%$where->{$key}%";
     }
-    my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
-    
-    if ( defined $orderby && grep($orderby, @ordervalues)) {
-        $query .= ' ORDER BY '.$orderby;
-    }
 
     my $sth = $dbh->prepare($query);
     $sth->execute( @query_parameters );
@@ -1029,7 +1024,20 @@ sub GetLostItems {
 
 =head2 GetItemsForInventory
 
-($itemlist, $iTotalRecords)  = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $offset, $size, $statushash);
+($itemlist, $iTotalRecords) = GetItemsForInventory( {
+  minlocation  => $minlocation,
+  maxlocation  => $maxlocation,
+  location     => $location,
+  itemtype     => $itemtype,
+  ignoreissued => $ignoreissued,
+  datelastseen => $datelastseen,
+  branchcode   => $branchcode,
+  branch       => $branch,
+  offset       => $offset,
+  size         => $size,
+  statushash   => $statushash,
+  interface    => $interface,
+} );
 
 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
 
@@ -1047,7 +1055,20 @@ $iTotalRecords is the number of rows that would have been returned without the $
 =cut
 
 sub GetItemsForInventory {
-    my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
+    my ( $parameters ) = @_;
+    my $minlocation  = $parameters->{'minlocation'}  // '';
+    my $maxlocation  = $parameters->{'maxlocation'}  // '';
+    my $location     = $parameters->{'location'}     // '';
+    my $itemtype     = $parameters->{'itemtype'}     // '';
+    my $ignoreissued = $parameters->{'ignoreissued'} // '';
+    my $datelastseen = $parameters->{'datelastseen'} // '';
+    my $branchcode   = $parameters->{'branchcode'}   // '';
+    my $branch       = $parameters->{'branch'}       // '';
+    my $offset       = $parameters->{'offset'}       // '';
+    my $size         = $parameters->{'size'}         // '';
+    my $statushash   = $parameters->{'statushash'}   // '';
+    my $interface    = $parameters->{'interface'}    // '';
+
     my $dbh = C4::Context->dbh;
     my ( @bind_params, @where_strings );
 
@@ -1126,16 +1147,15 @@ sub GetItemsForInventory {
     $sth->execute( @bind_params );
     my ($iTotalRecords) = $sth->fetchrow_array();
 
+    my $avmapping = C4::Koha::GetKohaAuthorisedValuesMapping( {
+                      interface => $interface
+                    } );
     foreach my $row (@$tmpresults) {
 
         # Auth values
         foreach (keys %$row) {
-            # If the koha field is mapped to a marc field
-            my ($f, $sf) = GetMarcFromKohaField("items.$_", $row->{'frameworkcode'});
-            if ($f and $sf) {
-                # We replace the code with it's description
-                my $authvals = C4::Koha::GetKohaAuthorisedValuesFromField($f, $sf, $row->{'frameworkcode'});
-                $row->{$_} = $authvals->{$row->{$_}} if defined $authvals->{$row->{$_}};
+            if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
+                $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
             }
         }
         push @results, $row;
@@ -1281,6 +1301,7 @@ sub GetItemsInfo {
     my ( $biblionumber ) = @_;
     my $dbh   = C4::Context->dbh;
     # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
+    my $language = C4::Languages::getlanguage();
     my $query = "
     SELECT items.*,
            biblio.*,
@@ -1298,6 +1319,7 @@ sub GetItemsInfo {
            items.notforloan as itemnotforloan,
            issues.borrowernumber,
            issues.date_due as datedue,
+           issues.onsite_checkout,
            borrowers.cardnumber,
            borrowers.surname,
            borrowers.firstname,
@@ -1305,14 +1327,13 @@ sub GetItemsInfo {
            serial.serialseq,
            serial.publisheddate,
            itemtypes.description,
+           COALESCE( localization.translation, itemtypes.description ) AS translated_description,
            itemtypes.notforloan as notforloan_per_itemtype,
            holding.branchurl,
            holding.branchname,
            holding.opac_info as holding_branch_opac_info,
            home.opac_info as home_branch_opac_info
     ";
-    $query .= ", issues.onsite_checkout"
-        if C4::Context->preference("OnSiteCheckouts");
     $query .= "
      FROM items
      LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
@@ -1325,11 +1346,15 @@ sub GetItemsInfo {
      LEFT JOIN serial USING (serialid)
      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
-    $query .= " LEFT JOIN issues ON issues.itemnumber = items.itemnumber"
-        if C4::Context->preference("OnSiteCheckouts");
+    $query .= q|
+    LEFT JOIN localization ON itemtypes.itemtype = localization.code
+        AND localization.entity = 'itemtypes'
+        AND localization.lang = ?
+    |;
+
     $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
     my $sth = $dbh->prepare($query);
-    $sth->execute($biblionumber);
+    $sth->execute($language, $biblionumber);
     my $i = 0;
     my @results;
     my $serial;
@@ -2031,7 +2056,11 @@ sub _do_column_fixes_for_mod {
         (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
         $item->{'withdrawn'} = 0;
     }
-    if (exists $item->{'location'} && !$item->{'permanent_location'}) {
+    if (exists $item->{location}
+        and $item->{location} ne 'CART'
+        and $item->{location} ne 'PROC'
+        and not $item->{permanent_location}
+    ) {
         $item->{'permanent_location'} = $item->{'location'};
     }
     if (exists $item->{'timestamp'}) {
@@ -2111,7 +2140,7 @@ C<items.withdrawn>
 
 sub _set_defaults_for_add {
     my $item = shift;
-    $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
+    $item->{dateaccessioned} ||= output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
     $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
 }
 
@@ -2127,6 +2156,7 @@ sub _koha_new_item {
     my ( $item, $barcode ) = @_;
     my $dbh=C4::Context->dbh;  
     my $error;
+    $item->{permanent_location} //= $item->{location};
     my $query =
            "INSERT INTO items SET
             biblionumber        = ?,
@@ -2144,15 +2174,16 @@ sub _koha_new_item {
             notforloan          = ?,
             damaged             = ?,
             itemlost            = ?,
-            withdrawn            = ?,
+            withdrawn           = ?,
             itemcallnumber      = ?,
             coded_location_qualifier = ?,
             restricted          = ?,
             itemnotes           = ?,
+            itemnotes_nonpublic = ?,
             holdingbranch       = ?,
             paidfor             = ?,
             location            = ?,
-            permanent_location            = ?,
+            permanent_location  = ?,
             onloan              = ?,
             issues              = ?,
             renewals            = ?,
@@ -2162,14 +2193,14 @@ sub _koha_new_item {
             ccode               = ?,
             itype               = ?,
             materials           = ?,
-            uri = ?,
+            uri                 = ?,
             enumchron           = ?,
             more_subfields_xml  = ?,
             copynumber          = ?,
             stocknumber         = ?
           ";
     my $sth = $dbh->prepare($query);
-    my $today = C4::Dates->today('iso');
+    my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
    $sth->execute(
             $item->{'biblionumber'},
             $item->{'biblioitemnumber'},
@@ -2191,6 +2222,7 @@ sub _koha_new_item {
             $item->{'coded_location_qualifier'},
             $item->{'restricted'},
             $item->{'itemnotes'},
+            $item->{'itemnotes_nonpublic'},
             $item->{'holdingbranch'},
             $item->{'paidfor'},
             $item->{'location'},
@@ -2235,11 +2267,18 @@ Returns undef if the move failed or the biblionumber of the destination record o
 sub MoveItemFromBiblio {
     my ($itemnumber, $frombiblio, $tobiblio) = @_;
     my $dbh = C4::Context->dbh;
-    my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
-    $sth->execute( $tobiblio );
-    my ( $tobiblioitem ) = $sth->fetchrow();
-    $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
-    my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
+    my ( $tobiblioitem ) = $dbh->selectrow_array(q|
+        SELECT biblioitemnumber
+        FROM biblioitems
+        WHERE biblionumber = ?
+    |, undef, $tobiblio );
+    my $return = $dbh->do(q|
+        UPDATE items
+        SET biblioitemnumber = ?,
+            biblionumber = ?
+        WHERE itemnumber = ?
+            AND biblionumber = ?
+    |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
     if ($return == 1) {
         ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
         ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
@@ -2251,6 +2290,15 @@ sub MoveItemFromBiblio {
                    $order->{'biblionumber'} = $tobiblio;
                C4::Acquisition::ModOrder($order);
            }
+
+        # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
+        for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
+            $dbh->do( qq|
+                UPDATE $table_name
+                SET biblionumber = ?
+                WHERE itemnumber = ?
+            |, undef, $tobiblio, $itemnumber );
+        }
         return $tobiblio;
        }
     return;
@@ -2291,7 +2339,7 @@ sub DelItemCheck {
         $error = "not_same_branch";
     }
        else{
-        # check it doesnt have a waiting reserve
+        # check it doesn't have a waiting reserve
         $sth = $dbh->prepare(q{
             SELECT COUNT(*) FROM reserves
             WHERE (found = 'W' OR found = 'T')
@@ -2589,10 +2637,10 @@ For instance you can search all items with a specific stocknumber like this:
 sub SearchItemsByField {
     my ($field, $value) = @_;
 
-    my $filters = {
-            field => $field,
-            query => $value,
-    } ];
+    my $filters = {
+        field => $field,
+        query => $value,
+    };
 
     my ($results) = SearchItems($filters);
     return $results;
@@ -2601,6 +2649,8 @@ sub SearchItemsByField {
 sub _SearchItems_build_where_fragment {
     my ($filter) = @_;
 
+    my $dbh = C4::Context->dbh;
+
     my $where_fragment;
     if (exists($filter->{conjunction})) {
         my (@where_strs, @where_args);
@@ -2637,13 +2687,33 @@ sub _SearchItems_build_where_fragment {
             if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
                 my $marcfield = $1;
                 my $marcsubfield = $2;
-                my $xpath;
-                if ($marcfield < 10) {
-                    $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
+                my ($kohafield) = $dbh->selectrow_array(q|
+                    SELECT kohafield FROM marc_subfield_structure
+                    WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
+                |, undef, $marcfield, $marcsubfield);
+
+                if ($kohafield) {
+                    $column = $kohafield;
                 } else {
-                    $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
+                    # MARC field is not linked to a DB field so we need to use
+                    # ExtractValue on biblioitems.marcxml or
+                    # items.more_subfields_xml, depending on the MARC field.
+                    my $xpath;
+                    my $sqlfield;
+                    my ($itemfield) = GetMarcFromKohaField('items.itemnumber');
+                    if ($marcfield eq $itemfield) {
+                        $sqlfield = 'more_subfields_xml';
+                        $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
+                    } else {
+                        $sqlfield = 'marcxml';
+                        if ($marcfield < 10) {
+                            $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
+                        } else {
+                            $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
+                        }
+                    }
+                    $column = "ExtractValue($sqlfield, '$xpath')";
                 }
-                $column = "ExtractValue(marcxml, '$xpath')";
             } else {
                 $column = $field;
             }
@@ -2965,13 +3035,12 @@ sub PrepareItemrecordDisplay {
 
                         #----- itemtypes
                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
-                        my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
-                        $sth->execute;
+                        my $itemtypes = GetItemTypes( style => 'array' );
                         push @authorised_values, ""
                           unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
-                        while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
-                            push @authorised_values, $itemtype;
-                            $authorised_lib{$itemtype} = $description;
+                        for my $itemtype ( @$itemtypes ) {
+                            push @authorised_values, $itemtype->{itemtype};
+                            $authorised_lib{$itemtype->{itemtype}} = $itemtype->{translated_description};
                         }
                         #---- class_sources
                     } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
@@ -3009,21 +3078,24 @@ sub PrepareItemrecordDisplay {
                         labels  => \%authorised_lib,
                     };
                 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
-                        # opening plugin
-                        my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
-                        if (do $plugin) {
-                            my $extended_param = plugin_parameters( $dbh, undef, $tagslib, $subfield_data{id}, undef );
-                            my ( $function_name, $javascript ) = plugin_javascript( $dbh, undef, $tagslib, $subfield_data{id}, undef );
-                            $subfield_data{random}     = int(rand(1000000));    # why do we need 2 different randoms?
-                            $subfield_data{marc_value} = qq[<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255"
-                                onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
-                                 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
-                                <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
-                                $javascript];
-                        } else {
-                            warn "Plugin Failed: $plugin";
-                            $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" />); # supply default input form
-                        }
+                # it is a plugin
+                    require Koha::FrameworkPlugin;
+                    my $plugin = Koha::FrameworkPlugin->new({
+                        name => $tagslib->{$tag}->{$subfield}->{value_builder},
+                        item_style => 1,
+                    });
+                    my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id}, tabloop => undef };
+                    $plugin->build( $pars );
+                    if( !$plugin->errstr ) {
+                        #TODO Move html to template; see report 12176/13397
+                        my $tab= $plugin->noclick? '-1': '';
+                        my $class= $plugin->noclick? ' disabled': '';
+                        my $title= $plugin->noclick? 'No popup': 'Tag editor';
+                        $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" /><a href="#" id="buttonDot_$subfield_data{id}" tabindex="$tab" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
+                    } else {
+                        warn $plugin->errstr;
+                        $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" />); # supply default input form
+                    }
                 }
                 elsif ( $tag eq '' ) {       # it's an hidden field
                     $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);