3 # Copyright 2007 LibLime, Inc.
4 # Parts Copyright Biblibre 2010
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 #use warnings; FIXME - Bug 2505
24 use vars qw(@ISA @EXPORT);
44 get_hostitemnumbers_of
54 PrepareItemrecordDisplay
66 use List::MoreUtils qw(any);
68 use DateTime::Format::MySQL;
69 use Data::Dumper; # used as part of logging item record changes, not just for
70 # debugging; so please don't remove this
72 use Koha::AuthorisedValues;
73 use Koha::DateUtils qw(dt_from_string);
76 use Koha::Biblioitems;
79 use Koha::SearchEngine;
80 use Koha::SearchEngine::Search;
85 C4::Items - item management functions
89 This module contains an API for manipulating item
90 records in Koha, and is used by cataloguing, circulation,
91 acquisitions, and serials management.
93 # FIXME This POD is not up-to-date
94 A Koha item record is stored in two places: the
95 items table and embedded in a MARC tag in the XML
96 version of the associated bib record in C<biblioitems.marcxml>.
97 This is done to allow the item information to be readily
98 indexed (e.g., by Zebra), but means that each item
99 modification transaction must keep the items table
100 and the MARC XML in sync at all times.
102 The items table will be considered authoritative. In other
103 words, if there is ever a discrepancy between the items
104 table and the MARC XML, the items table should be considered
107 =head1 HISTORICAL NOTE
109 Most of the functions in C<C4::Items> were originally in
110 the C<C4::Biblio> module.
112 =head1 CORE EXPORTED FUNCTIONS
114 The following functions are meant for use by users
121 CartToShelf($itemnumber);
123 Set the current shelving location of the item record
124 to its stored permanent shelving location. This is
125 primarily used to indicate when an item whose current
126 location is a special processing ('PROC') or shelving cart
127 ('CART') location is back in the stacks.
132 my ( $itemnumber ) = @_;
134 unless ( $itemnumber ) {
135 croak "FAILED CartToShelf() - no itemnumber supplied";
138 my $item = Koha::Items->find($itemnumber);
139 if ( $item->location eq 'CART' ) {
140 ModItem({ location => $item->permanent_location}, undef, $itemnumber);
146 ShelfToCart($itemnumber);
148 Set the current shelving location of the item
149 to shelving cart ('CART').
154 my ( $itemnumber ) = @_;
156 unless ( $itemnumber ) {
157 croak "FAILED ShelfToCart() - no itemnumber supplied";
160 ModItem({ location => 'CART'}, undef, $itemnumber);
163 =head2 AddItemFromMarc
165 my ($biblionumber, $biblioitemnumber, $itemnumber)
166 = AddItemFromMarc($source_item_marc, $biblionumber);
168 Given a MARC::Record object containing an embedded item
169 record and a biblionumber, create a new item record.
173 sub AddItemFromMarc {
174 my ( $source_item_marc, $biblionumber ) = @_;
175 my $dbh = C4::Context->dbh;
177 # parse item hash from MARC
178 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
179 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
181 my $localitemmarc = MARC::Record->new;
182 $localitemmarc->append_fields( $source_item_marc->field($itemtag) );
183 my $item = C4::Biblio::TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
184 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
185 return AddItem( $item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields );
190 my ($biblionumber, $biblioitemnumber, $itemnumber)
191 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
193 Given a hash containing item column names as keys,
194 create a new Koha item record.
196 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
197 do not need to be supplied for general use; they exist
198 simply to allow them to be picked up from AddItemFromMarc.
200 The final optional parameter, C<$unlinked_item_subfields>, contains
201 an arrayref containing subfields present in the original MARC
202 representation of the item (e.g., from the item editor) that are
203 not mapped to C<items> columns directly but should instead
204 be stored in C<items.more_subfields_xml> and included in
205 the biblio items tag for display and indexing.
211 my $biblionumber = shift;
213 my $dbh = @_ ? shift : C4::Context->dbh;
214 my $frameworkcode = @_ ? shift : C4::Biblio::GetFrameworkCode($biblionumber);
215 my $unlinked_item_subfields;
217 $unlinked_item_subfields = shift;
220 # needs old biblionumber and biblioitemnumber
221 $item->{'biblionumber'} = $biblionumber;
222 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
223 $sth->execute( $item->{'biblionumber'} );
224 ( $item->{'biblioitemnumber'} ) = $sth->fetchrow;
226 _set_defaults_for_add($item);
227 _set_derived_columns_for_add($item);
228 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
230 # FIXME - checks here
231 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
232 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
233 $itype_sth->execute( $item->{'biblionumber'} );
234 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
237 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
240 $item->{'itemnumber'} = $itemnumber;
242 C4::Biblio::ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver" );
244 logaction( "CATALOGUING", "ADD", $itemnumber, "item" )
245 if C4::Context->preference("CataloguingLog");
247 return ( $item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber );
250 =head2 AddItemBatchFromMarc
252 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
253 $biblionumber, $biblioitemnumber, $frameworkcode);
255 Efficiently create item records from a MARC biblio record with
256 embedded item fields. This routine is suitable for batch jobs.
258 This API assumes that the bib record has already been
259 saved to the C<biblio> and C<biblioitems> tables. It does
260 not expect that C<biblio_metadata.metadata> is populated, but it
261 will do so via a call to ModBibiloMarc.
263 The goal of this API is to have a similar effect to using AddBiblio
264 and AddItems in succession, but without inefficient repeated
265 parsing of the MARC XML bib record.
267 This function returns an arrayref of new itemsnumbers and an arrayref of item
268 errors encountered during the processing. Each entry in the errors
269 list is a hashref containing the following keys:
275 Sequence number of original item tag in the MARC record.
279 Item barcode, provide to assist in the construction of
280 useful error messages.
284 Code representing the error condition. Can be 'duplicate_barcode',
285 'invalid_homebranch', or 'invalid_holdingbranch'.
287 =item error_information
289 Additional information appropriate to the error condition.
295 sub AddItemBatchFromMarc {
296 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
298 my @itemnumbers = ();
300 my $dbh = C4::Context->dbh;
302 # We modify the record, so lets work on a clone so we don't change the
304 $record = $record->clone();
305 # loop through the item tags and start creating items
306 my @bad_item_fields = ();
307 my ($itemtag, $itemsubfield) = C4::Biblio::GetMarcFromKohaField("items.itemnumber",'');
308 my $item_sequence_num = 0;
309 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
310 $item_sequence_num++;
311 # we take the item field and stick it into a new
312 # MARC record -- this is required so far because (FIXME)
313 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
314 # and there is no TransformMarcFieldToKoha
315 my $temp_item_marc = MARC::Record->new();
316 $temp_item_marc->append_fields($item_field);
318 # add biblionumber and biblioitemnumber
319 my $item = TransformMarcToKoha( $temp_item_marc, $frameworkcode, 'items' );
320 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
321 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
322 $item->{'biblionumber'} = $biblionumber;
323 $item->{'biblioitemnumber'} = $biblioitemnumber;
325 # check for duplicate barcode
326 my %item_errors = CheckItemPreSave($item);
328 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
329 push @bad_item_fields, $item_field;
333 _set_defaults_for_add($item);
334 _set_derived_columns_for_add($item);
335 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
336 warn $error if $error;
337 push @itemnumbers, $itemnumber; # FIXME not checking error
338 $item->{'itemnumber'} = $itemnumber;
340 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
342 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
343 $item_field->replace_with($new_item_marc->field($itemtag));
346 # remove any MARC item fields for rejected items
347 foreach my $item_field (@bad_item_fields) {
348 $record->delete_field($item_field);
351 # update the MARC biblio
352 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
354 return (\@itemnumbers, \@errors);
357 =head2 ModItemFromMarc
359 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
361 This function updates an item record based on a supplied
362 C<MARC::Record> object containing an embedded item field.
363 This API is meant for the use of C<additem.pl>; for
364 other purposes, C<ModItem> should be used.
366 This function uses the hash %default_values_for_mod_from_marc,
367 which contains default values for item fields to
368 apply when modifying an item. This is needed because
369 if an item field's value is cleared, TransformMarcToKoha
370 does not include the column in the
371 hash that's passed to ModItem, which without
372 use of this hash makes it impossible to clear
373 an item field's value. See bug 2466.
375 Note that only columns that can be directly
376 changed from the cataloging and serials
377 item editors are included in this hash.
383 sub _build_default_values_for_mod_marc {
384 # Has no framework parameter anymore, since Default is authoritative
385 # for Koha to MARC mappings.
387 my $cache = Koha::Caches->get_instance();
388 my $cache_key = "default_value_for_mod_marc-";
389 my $cached = $cache->get_from_cache($cache_key);
390 return $cached if $cached;
392 my $default_values = {
394 booksellerid => undef,
396 'items.cn_source' => undef,
397 coded_location_qualifier => undef,
401 holdingbranch => undef,
403 itemcallnumber => undef,
406 itemnotes_nonpublic => undef,
409 permanent_location => undef,
413 # paidfor => undef, # commented, see bug 12817
415 replacementprice => undef,
416 replacementpricedate => undef,
419 stocknumber => undef,
423 my %default_values_for_mod_from_marc;
424 while ( my ( $field, $default_value ) = each %$default_values ) {
425 my $kohafield = $field;
426 $kohafield =~ s|^([^\.]+)$|items.$1|;
427 $default_values_for_mod_from_marc{$field} = $default_value
428 if C4::Biblio::GetMarcFromKohaField( $kohafield );
431 $cache->set_in_cache($cache_key, \%default_values_for_mod_from_marc);
432 return \%default_values_for_mod_from_marc;
435 sub ModItemFromMarc {
436 my $item_marc = shift;
437 my $biblionumber = shift;
438 my $itemnumber = shift;
440 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
441 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
443 my $localitemmarc = MARC::Record->new;
444 $localitemmarc->append_fields( $item_marc->field($itemtag) );
445 my $item = TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
446 my $default_values = _build_default_values_for_mod_marc();
447 foreach my $item_field ( keys %$default_values ) {
448 $item->{$item_field} = $default_values->{$item_field}
449 unless exists $item->{$item_field};
451 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
453 ModItem( $item, $biblionumber, $itemnumber, { unlinked_item_subfields => $unlinked_item_subfields } );
460 { column => $newvalue },
464 [ unlinked_item_subfields => $unlinked_item_subfields, ]
469 Change one or more columns in an item record.
471 The first argument is a hashref mapping from item column
472 names to the new values. The second and third arguments
473 are the biblionumber and itemnumber, respectively.
474 The fourth, optional parameter (additional_params) may contain the keys
475 unlinked_item_subfields and log_action.
477 C<$unlinked_item_subfields> contains an arrayref containing
478 subfields present in the original MARC
479 representation of the item (e.g., from the item editor) that are
480 not mapped to C<items> columns directly but should instead
481 be stored in C<items.more_subfields_xml> and included in
482 the biblio items tag for display and indexing.
484 If one of the changed columns is used to calculate
485 the derived value of a column such as C<items.cn_sort>,
486 this routine will perform the necessary calculation
489 If log_action is set to false, the action will not be logged.
490 If log_action is true or undefined, the action will be logged.
495 my ( $item, $biblionumber, $itemnumber, $additional_params ) = @_;
496 my $log_action = $additional_params->{log_action} // 1;
497 my $unlinked_item_subfields = $additional_params->{unlinked_item_subfields};
499 return unless %$item;
500 $item->{'itemnumber'} = $itemnumber or return;
502 # if $biblionumber is undefined, get it from the current item
503 unless (defined $biblionumber) {
504 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
507 if ($unlinked_item_subfields) {
508 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
511 my @fields = qw( itemlost withdrawn damaged );
513 # Only retrieve the item if we need to set an "on" date field
514 if ( $item->{itemlost} || $item->{withdrawn} || $item->{damaged} ) {
515 my $pre_mod_item = Koha::Items->find( $item->{'itemnumber'} );
516 for my $field (@fields) {
517 if ( defined( $item->{$field} )
518 and not $pre_mod_item->$field
519 and $item->{$field} )
521 $item->{ $field . '_on' } =
522 DateTime::Format::MySQL->format_datetime( dt_from_string() );
527 # If the field is defined but empty, we are removing and,
528 # and thus need to clear out the 'on' field as well
529 for my $field (@fields) {
530 if ( defined( $item->{$field} ) && !$item->{$field} ) {
531 $item->{ $field . '_on' } = undef;
536 _set_derived_columns_for_mod($item);
537 _do_column_fixes_for_mod($item);
540 # attempt to change itemnumber
541 # attempt to change biblionumber (if we want
542 # an API to relink an item to a different bib,
543 # it should be a separate function)
546 _koha_modify_item($item);
548 # request that bib be reindexed so that searching on current
549 # item status is possible
550 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
552 logaction( "CATALOGUING", "MODIFY", $itemnumber, "item " . Dumper($item) )
553 if $log_action && C4::Context->preference("CataloguingLog");
556 =head2 ModItemTransfer
558 ModItemTransfer($itenumber, $frombranch, $tobranch);
560 Marks an item as being transferred from one branch
565 sub ModItemTransfer {
566 my ( $itemnumber, $frombranch, $tobranch ) = @_;
568 my $dbh = C4::Context->dbh;
570 # Remove the 'shelving cart' location status if it is being used.
571 CartToShelf( $itemnumber ) if ( C4::Context->preference("ReturnToShelvingCart") );
573 $dbh->do("UPDATE branchtransfers SET datearrived = NOW(), comments = ? WHERE itemnumber = ? AND datearrived IS NULL", undef, "Canceled, new transfer from $frombranch to $tobranch created", $itemnumber);
575 #new entry in branchtransfers....
576 my $sth = $dbh->prepare(
577 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
578 VALUES (?, ?, NOW(), ?)");
579 $sth->execute($itemnumber, $frombranch, $tobranch);
581 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber, { log_action => 0 });
582 ModDateLastSeen($itemnumber);
586 =head2 ModDateLastSeen
588 ModDateLastSeen( $itemnumber, $leave_item_lost );
590 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
591 C<$itemnumber> is the item number
592 C<$leave_item_lost> determines if a lost item will be found or remain lost
596 sub ModDateLastSeen {
597 my ( $itemnumber, $leave_item_lost ) = @_;
599 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
602 $params->{datelastseen} = $today;
603 $params->{itemlost} = 0 unless $leave_item_lost;
605 ModItem( $params, undef, $itemnumber, { log_action => 0 } );
610 DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
612 Exported function (core API) for deleting an item record in Koha.
619 my $itemnumber = $params->{itemnumber};
620 my $biblionumber = $params->{biblionumber};
622 unless ($biblionumber) {
623 my $item = Koha::Items->find( $itemnumber );
624 $biblionumber = $item ? $item->biblio->biblionumber : undef;
627 # If there is no biblionumber for the given itemnumber, there is nothing to delete
628 return 0 unless $biblionumber;
630 # FIXME check the item has no current issues
631 my $deleted = _koha_delete_item( $itemnumber );
633 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
635 #search item field code
636 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
640 =head2 CheckItemPreSave
642 my $item_ref = TransformMarcToKoha($marc, 'items');
644 my %errors = CheckItemPreSave($item_ref);
645 if (exists $errors{'duplicate_barcode'}) {
646 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
647 } elsif (exists $errors{'invalid_homebranch'}) {
648 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
649 } elsif (exists $errors{'invalid_holdingbranch'}) {
650 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
655 Given a hashref containing item fields, determine if it can be
656 inserted or updated in the database. Specifically, checks for
657 database integrity issues, and returns a hash containing any
658 of the following keys, if applicable.
662 =item duplicate_barcode
664 Barcode, if it duplicates one already found in the database.
666 =item invalid_homebranch
668 Home branch, if not defined in branches table.
670 =item invalid_holdingbranch
672 Holding branch, if not defined in branches table.
676 This function does NOT implement any policy-related checks,
677 e.g., whether current operator is allowed to save an
678 item that has a given branch code.
682 sub CheckItemPreSave {
683 my $item_ref = shift;
687 # check for duplicate barcode
688 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
689 my $existing_item= Koha::Items->find({barcode => $item_ref->{'barcode'}});
690 if ($existing_item) {
691 if (!exists $item_ref->{'itemnumber'} # new item
692 or $item_ref->{'itemnumber'} != $existing_item->itemnumber) { # existing item
693 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
698 # check for valid home branch
699 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
700 my $home_library = Koha::Libraries->find( $item_ref->{homebranch} );
701 unless (defined $home_library) {
702 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
706 # check for valid holding branch
707 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
708 my $holding_library = Koha::Libraries->find( $item_ref->{holdingbranch} );
709 unless (defined $holding_library) {
710 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
718 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
720 The following functions provide various ways of
721 getting an item record, a set of item records, or
722 lists of authorized values for certain item fields.
726 =head2 GetItemsForInventory
728 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
729 minlocation => $minlocation,
730 maxlocation => $maxlocation,
731 location => $location,
732 itemtype => $itemtype,
733 ignoreissued => $ignoreissued,
734 datelastseen => $datelastseen,
735 branchcode => $branchcode,
739 statushash => $statushash,
742 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
744 The sub returns a reference to a list of hashes, each containing
745 itemnumber, author, title, barcode, item callnumber, and date last
746 seen. It is ordered by callnumber then title.
748 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
749 the datelastseen can be used to specify that you want to see items not seen since a past date only.
750 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
751 $statushash requires a hashref that has the authorized values fieldname (intems.notforloan, etc...) as keys, and an arrayref of statuscodes we are searching for as values.
753 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
757 sub GetItemsForInventory {
758 my ( $parameters ) = @_;
759 my $minlocation = $parameters->{'minlocation'} // '';
760 my $maxlocation = $parameters->{'maxlocation'} // '';
761 my $class_source = $parameters->{'class_source'} // C4::Context->preference('DefaultClassificationSource');
762 my $location = $parameters->{'location'} // '';
763 my $itemtype = $parameters->{'itemtype'} // '';
764 my $ignoreissued = $parameters->{'ignoreissued'} // '';
765 my $datelastseen = $parameters->{'datelastseen'} // '';
766 my $branchcode = $parameters->{'branchcode'} // '';
767 my $branch = $parameters->{'branch'} // '';
768 my $offset = $parameters->{'offset'} // '';
769 my $size = $parameters->{'size'} // '';
770 my $statushash = $parameters->{'statushash'} // '';
771 my $ignore_waiting_holds = $parameters->{'ignore_waiting_holds'} // '';
773 my $dbh = C4::Context->dbh;
774 my ( @bind_params, @where_strings );
776 my $min_cnsort = GetClassSort($class_source,undef,$minlocation);
777 my $max_cnsort = GetClassSort($class_source,undef,$maxlocation);
779 my $select_columns = q{
780 SELECT DISTINCT(items.itemnumber), barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
782 my $select_count = q{SELECT COUNT(DISTINCT(items.itemnumber))};
785 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
786 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
789 for my $authvfield (keys %$statushash){
790 if ( scalar @{$statushash->{$authvfield}} > 0 ){
791 my $joinedvals = join ',', @{$statushash->{$authvfield}};
792 push @where_strings, "$authvfield in (" . $joinedvals . ")";
798 push @where_strings, 'items.cn_sort >= ?';
799 push @bind_params, $min_cnsort;
803 push @where_strings, 'items.cn_sort <= ?';
804 push @bind_params, $max_cnsort;
808 $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
809 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
810 push @bind_params, $datelastseen;
814 push @where_strings, 'items.location = ?';
815 push @bind_params, $location;
819 if($branch eq "homebranch"){
820 push @where_strings, 'items.homebranch = ?';
822 push @where_strings, 'items.holdingbranch = ?';
824 push @bind_params, $branchcode;
828 push @where_strings, 'biblioitems.itemtype = ?';
829 push @bind_params, $itemtype;
832 if ( $ignoreissued) {
833 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
834 push @where_strings, 'issues.date_due IS NULL';
837 if ( $ignore_waiting_holds ) {
838 $query .= "LEFT JOIN reserves ON items.itemnumber = reserves.itemnumber ";
839 push( @where_strings, q{(reserves.found != 'W' OR reserves.found IS NULL)} );
842 if ( @where_strings ) {
844 $query .= join ' AND ', @where_strings;
846 my $count_query = $select_count . $query;
847 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
848 $query .= " LIMIT $offset, $size" if ($offset and $size);
849 $query = $select_columns . $query;
850 my $sth = $dbh->prepare($query);
851 $sth->execute( @bind_params );
854 my $tmpresults = $sth->fetchall_arrayref({});
855 $sth = $dbh->prepare( $count_query );
856 $sth->execute( @bind_params );
857 my ($iTotalRecords) = $sth->fetchrow_array();
859 my @avs = Koha::AuthorisedValues->search(
860 { 'marc_subfield_structures.kohafield' => { '>' => '' },
861 'me.authorised_value' => { '>' => '' },
863 { join => { category => 'marc_subfield_structures' },
864 distinct => ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'],
865 '+select' => [ 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', 'me.lib' ],
866 '+as' => [ 'kohafield', 'frameworkcode', 'authorised_value', 'lib' ],
870 my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs };
872 foreach my $row (@$tmpresults) {
875 foreach (keys %$row) {
876 if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
877 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
883 return (\@results, $iTotalRecords);
888 @results = GetItemsInfo($biblionumber);
890 Returns information about items with the given biblionumber.
892 C<GetItemsInfo> returns a list of references-to-hash. Each element
893 contains a number of keys. Most of them are attributes from the
894 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
895 Koha database. Other keys include:
899 =item C<$data-E<gt>{branchname}>
901 The name (not the code) of the branch to which the book belongs.
903 =item C<$data-E<gt>{datelastseen}>
905 This is simply C<items.datelastseen>, except that while the date is
906 stored in YYYY-MM-DD format in the database, here it is converted to
907 DD/MM/YYYY format. A NULL date is returned as C<//>.
909 =item C<$data-E<gt>{datedue}>
911 =item C<$data-E<gt>{class}>
913 This is the concatenation of C<biblioitems.classification>, the book's
914 Dewey code, and C<biblioitems.subclass>.
916 =item C<$data-E<gt>{ocount}>
918 I think this is the number of copies of the book available.
920 =item C<$data-E<gt>{order}>
922 If this is set, it is set to C<One Order>.
929 my ( $biblionumber ) = @_;
930 my $dbh = C4::Context->dbh;
931 require C4::Languages;
932 my $language = C4::Languages::getlanguage();
938 biblioitems.itemtype,
941 biblioitems.publicationyear,
942 biblioitems.publishercode,
943 biblioitems.volumedate,
944 biblioitems.volumedesc,
947 items.notforloan as itemnotforloan,
948 issues.borrowernumber,
949 issues.date_due as datedue,
950 issues.onsite_checkout,
951 borrowers.cardnumber,
954 borrowers.branchcode as bcode,
956 serial.publisheddate,
957 itemtypes.description,
958 COALESCE( localization.translation, itemtypes.description ) AS translated_description,
959 itemtypes.notforloan as notforloan_per_itemtype,
963 holding.opac_info as holding_branch_opac_info,
964 home.opac_info as home_branch_opac_info
966 $query .= ",IF(tmp_holdsqueue.itemnumber,1,0) AS pending_hold" if !C4::Context->preference('AllowItemsOnHoldCheckout');
969 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
970 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
971 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
972 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
973 LEFT JOIN issues USING (itemnumber)
974 LEFT JOIN borrowers USING (borrowernumber)
975 LEFT JOIN serialitems USING (itemnumber)
976 LEFT JOIN serial USING (serialid)
977 LEFT JOIN itemtypes ON itemtypes.itemtype = "
978 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
980 LEFT JOIN tmp_holdsqueue USING (itemnumber)" if !C4::Context->preference('AllowItemsOnHoldCheckout');
982 LEFT JOIN localization ON itemtypes.itemtype = localization.code
983 AND localization.entity = 'itemtypes'
984 AND localization.lang = ?
987 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
988 my $sth = $dbh->prepare($query);
989 $sth->execute($language, $biblionumber);
994 my $userenv = C4::Context->userenv;
995 my $want_not_same_branch = C4::Context->preference("IndependentBranches") && !C4::Context->IsSuperLibrarian();
996 while ( my $data = $sth->fetchrow_hashref ) {
997 if ( $data->{borrowernumber} && $want_not_same_branch) {
998 $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch};
1001 $serial ||= $data->{'serial'};
1004 # get notforloan complete status if applicable
1005 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.notforloan', authorised_value => $data->{itemnotforloan} });
1006 $data->{notforloanvalue} = $descriptions->{lib} // '';
1007 $data->{notforloanvalueopac} = $descriptions->{opac_description} // '';
1009 # get restricted status and description if applicable
1010 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.restricted', authorised_value => $data->{restricted} });
1011 $data->{restrictedvalue} = $descriptions->{lib} // '';
1012 $data->{restrictedvalueopac} = $descriptions->{opac_description} // '';
1014 # my stack procedures
1015 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.stack', authorised_value => $data->{stack} });
1016 $data->{stack} = $descriptions->{lib} // '';
1018 # Find the last 3 people who borrowed this item.
1019 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1020 WHERE itemnumber = ?
1021 AND old_issues.borrowernumber = borrowers.borrowernumber
1022 ORDER BY returndate DESC
1024 $sth2->execute($data->{'itemnumber'});
1026 while (my $data2 = $sth2->fetchrow_hashref()) {
1027 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1028 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1029 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1033 $results[$i] = $data;
1038 ? sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
1042 =head2 GetItemsLocationInfo
1044 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1046 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1048 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1052 =item C<$data-E<gt>{homebranch}>
1054 Branch Name of the item's homebranch
1056 =item C<$data-E<gt>{holdingbranch}>
1058 Branch Name of the item's holdingbranch
1060 =item C<$data-E<gt>{location}>
1062 Item's shelving location code
1064 =item C<$data-E<gt>{location_intranet}>
1066 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1068 =item C<$data-E<gt>{location_opac}>
1070 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1073 =item C<$data-E<gt>{itemcallnumber}>
1075 Item's itemcallnumber
1077 =item C<$data-E<gt>{cn_sort}>
1079 Item's call number normalized for sorting
1085 sub GetItemsLocationInfo {
1086 my $biblionumber = shift;
1089 my $dbh = C4::Context->dbh;
1090 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1091 location, itemcallnumber, cn_sort
1092 FROM items, branches as a, branches as b
1093 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1094 AND biblionumber = ?
1095 ORDER BY cn_sort ASC";
1096 my $sth = $dbh->prepare($query);
1097 $sth->execute($biblionumber);
1099 while ( my $data = $sth->fetchrow_hashref ) {
1100 my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $data->{location} });
1101 $av = $av->count ? $av->next : undef;
1102 $data->{location_intranet} = $av ? $av->lib : '';
1103 $data->{location_opac} = $av ? $av->opac_description : '';
1104 push @results, $data;
1109 =head2 GetHostItemsInfo
1111 $hostiteminfo = GetHostItemsInfo($hostfield);
1112 Returns the iteminfo for items linked to records via a host field
1116 sub GetHostItemsInfo {
1118 my @returnitemsInfo;
1120 if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1121 return @returnitemsInfo;
1125 if( C4::Context->preference('marcflavour') eq 'MARC21' ||
1126 C4::Context->preference('marcflavour') eq 'NORMARC') {
1127 @fields = $record->field('773');
1128 } elsif( C4::Context->preference('marcflavour') eq 'UNIMARC') {
1129 @fields = $record->field('461');
1132 foreach my $hostfield ( @fields ) {
1133 my $hostbiblionumber = $hostfield->subfield("0");
1134 my $linkeditemnumber = $hostfield->subfield("9");
1135 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1136 foreach my $hostitemInfo (@hostitemInfos) {
1137 if( $hostitemInfo->{itemnumber} eq $linkeditemnumber ) {
1138 push @returnitemsInfo, $hostitemInfo;
1143 return @returnitemsInfo;
1146 =head2 get_hostitemnumbers_of
1148 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1150 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1152 Return a reference on a hash where key is a biblionumber and values are
1153 references on array of itemnumbers.
1158 sub get_hostitemnumbers_of {
1159 my ($biblionumber) = @_;
1161 if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1165 my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
1166 return unless $marcrecord;
1168 my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
1170 my $marcflavor = C4::Context->preference('marcflavour');
1171 if ( $marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC' ) {
1176 elsif ( $marcflavor eq 'UNIMARC' ) {
1182 foreach my $hostfield ( $marcrecord->field($tag) ) {
1183 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1184 next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield
1185 my $linkeditemnumber = $hostfield->subfield($item_s);
1186 if ( ! $linkeditemnumber ) {
1187 warn "ERROR biblionumber $biblionumber has 773^0, but doesn't have 9";
1190 my $is_from_biblio = Koha::Items->search({ itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber });
1191 push @returnhostitemnumbers, $linkeditemnumber
1195 return @returnhostitemnumbers;
1198 =head2 GetHiddenItemnumbers
1200 my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
1202 Given a list of items it checks which should be hidden from the OPAC given
1203 the current configuration. Returns a list of itemnumbers corresponding to
1204 those that should be hidden. Optionally takes a borcat parameter for certain borrower types
1209 sub GetHiddenItemnumbers {
1211 my $items = $params->{items};
1212 if (my $exceptions = C4::Context->preference('OpacHiddenItemsExceptions') and $params->{'borcat'}){
1213 foreach my $except (split(/\|/, $exceptions)){
1214 if ($params->{'borcat'} eq $except){
1215 return; # we don't hide anything for this borrower category
1221 my $yaml = C4::Context->preference('OpacHiddenItems');
1222 return () if (! $yaml =~ /\S/ );
1223 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1226 $hidingrules = YAML::Load($yaml);
1229 warn "Unable to parse OpacHiddenItems syspref : $@";
1232 my $dbh = C4::Context->dbh;
1235 foreach my $item (@$items) {
1237 # We check each rule
1238 foreach my $field (keys %$hidingrules) {
1240 if (exists $item->{$field}) {
1241 $val = $item->{$field};
1244 my $query = "SELECT $field from items where itemnumber = ?";
1245 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1247 $val = '' unless defined $val;
1249 # If the results matches the values in the yaml file
1250 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1252 # We add the itemnumber to the list
1253 push @resultitems, $item->{'itemnumber'};
1255 # If at least one rule matched for an item, no need to test the others
1260 return @resultitems;
1263 =head1 LIMITED USE FUNCTIONS
1265 The following functions, while part of the public API,
1266 are not exported. This is generally because they are
1267 meant to be used by only one script for a specific
1268 purpose, and should not be used in any other context
1269 without careful thought.
1275 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1277 Returns MARC::Record of the item passed in parameter.
1278 This function is meant for use only in C<cataloguing/additem.pl>,
1279 where it is needed to support that script's MARC-like
1285 my ( $biblionumber, $itemnumber ) = @_;
1287 # GetMarcItem has been revised so that it does the following:
1288 # 1. Gets the item information from the items table.
1289 # 2. Converts it to a MARC field for storage in the bib record.
1291 # The previous behavior was:
1292 # 1. Get the bib record.
1293 # 2. Return the MARC tag corresponding to the item record.
1295 # The difference is that one treats the items row as authoritative,
1296 # while the other treats the MARC representation as authoritative
1297 # under certain circumstances.
1299 my $item = Koha::Items->find($itemnumber) or return;
1301 # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
1302 # Also, don't emit a subfield if the underlying field is blank.
1304 return Item2Marc($item->unblessed, $biblionumber);
1308 my ($itemrecord,$biblionumber)=@_;
1311 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1312 } keys %{ $itemrecord }
1314 my $framework = C4::Biblio::GetFrameworkCode( $biblionumber );
1315 my $itemmarc = C4::Biblio::TransformKohaToMarc( $mungeditem ); # Bug 21774: no_split parameter removed to allow cloned subfields
1316 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField(
1317 "items.itemnumber", $framework,
1320 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1321 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1322 foreach my $field ($itemmarc->field($itemtag)){
1323 $field->add_subfields(@$unlinked_item_subfields);
1329 =head1 PRIVATE FUNCTIONS AND VARIABLES
1331 The following functions are not meant to be called
1332 directly, but are documented in order to explain
1333 the inner workings of C<C4::Items>.
1337 =head2 %derived_columns
1339 This hash keeps track of item columns that
1340 are strictly derived from other columns in
1341 the item record and are not meant to be set
1344 Each key in the hash should be the name of a
1345 column (as named by TransformMarcToKoha). Each
1346 value should be hashref whose keys are the
1347 columns on which the derived column depends. The
1348 hashref should also contain a 'BUILDER' key
1349 that is a reference to a sub that calculates
1354 my %derived_columns = (
1355 'items.cn_sort' => {
1356 'itemcallnumber' => 1,
1357 'items.cn_source' => 1,
1358 'BUILDER' => \&_calc_items_cn_sort,
1362 =head2 _set_derived_columns_for_add
1364 _set_derived_column_for_add($item);
1366 Given an item hash representing a new item to be added,
1367 calculate any derived columns. Currently the only
1368 such column is C<items.cn_sort>.
1372 sub _set_derived_columns_for_add {
1375 foreach my $column (keys %derived_columns) {
1376 my $builder = $derived_columns{$column}->{'BUILDER'};
1377 my $source_values = {};
1378 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1379 next if $source_column eq 'BUILDER';
1380 $source_values->{$source_column} = $item->{$source_column};
1382 $builder->($item, $source_values);
1386 =head2 _set_derived_columns_for_mod
1388 _set_derived_column_for_mod($item);
1390 Given an item hash representing a new item to be modified.
1391 calculate any derived columns. Currently the only
1392 such column is C<items.cn_sort>.
1394 This routine differs from C<_set_derived_columns_for_add>
1395 in that it needs to handle partial item records. In other
1396 words, the caller of C<ModItem> may have supplied only one
1397 or two columns to be changed, so this function needs to
1398 determine whether any of the columns to be changed affect
1399 any of the derived columns. Also, if a derived column
1400 depends on more than one column, but the caller is not
1401 changing all of then, this routine retrieves the unchanged
1402 values from the database in order to ensure a correct
1407 sub _set_derived_columns_for_mod {
1410 foreach my $column (keys %derived_columns) {
1411 my $builder = $derived_columns{$column}->{'BUILDER'};
1412 my $source_values = {};
1413 my %missing_sources = ();
1414 my $must_recalc = 0;
1415 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1416 next if $source_column eq 'BUILDER';
1417 if (exists $item->{$source_column}) {
1419 $source_values->{$source_column} = $item->{$source_column};
1421 $missing_sources{$source_column} = 1;
1425 foreach my $source_column (keys %missing_sources) {
1426 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1428 $builder->($item, $source_values);
1433 =head2 _do_column_fixes_for_mod
1435 _do_column_fixes_for_mod($item);
1437 Given an item hashref containing one or more
1438 columns to modify, fix up certain values.
1439 Specifically, set to 0 any passed value
1440 of C<notforloan>, C<damaged>, C<itemlost>, or
1441 C<withdrawn> that is either undefined or
1442 contains the empty string.
1446 sub _do_column_fixes_for_mod {
1449 if (exists $item->{'notforloan'} and
1450 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1451 $item->{'notforloan'} = 0;
1453 if (exists $item->{'damaged'} and
1454 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1455 $item->{'damaged'} = 0;
1457 if (exists $item->{'itemlost'} and
1458 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1459 $item->{'itemlost'} = 0;
1461 if (exists $item->{'withdrawn'} and
1462 (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
1463 $item->{'withdrawn'} = 0;
1465 if (exists $item->{location}
1466 and $item->{location} ne 'CART'
1467 and $item->{location} ne 'PROC'
1468 and not $item->{permanent_location}
1470 $item->{'permanent_location'} = $item->{'location'};
1472 if (exists $item->{'timestamp'}) {
1473 delete $item->{'timestamp'};
1477 =head2 _get_single_item_column
1479 _get_single_item_column($column, $itemnumber);
1481 Retrieves the value of a single column from an C<items>
1482 row specified by C<$itemnumber>.
1486 sub _get_single_item_column {
1488 my $itemnumber = shift;
1490 my $dbh = C4::Context->dbh;
1491 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1492 $sth->execute($itemnumber);
1493 my ($value) = $sth->fetchrow();
1497 =head2 _calc_items_cn_sort
1499 _calc_items_cn_sort($item, $source_values);
1501 Helper routine to calculate C<items.cn_sort>.
1505 sub _calc_items_cn_sort {
1507 my $source_values = shift;
1509 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1512 =head2 _set_defaults_for_add
1514 _set_defaults_for_add($item_hash);
1516 Given an item hash representing an item to be added, set
1517 correct default values for columns whose default value
1518 is not handled by the DBMS. This includes the following
1525 C<items.dateaccessioned>
1547 sub _set_defaults_for_add {
1549 $item->{dateaccessioned} ||= output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1550 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
1553 =head2 _koha_new_item
1555 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1557 Perform the actual insert into the C<items> table.
1561 sub _koha_new_item {
1562 my ( $item, $barcode ) = @_;
1563 my $dbh=C4::Context->dbh;
1565 $item->{permanent_location} //= $item->{location};
1566 _mod_item_dates( $item );
1568 "INSERT INTO items SET
1570 biblioitemnumber = ?,
1572 dateaccessioned = ?,
1576 replacementprice = ?,
1577 replacementpricedate = ?,
1578 datelastborrowed = ?,
1586 coded_location_qualifier = ?,
1589 itemnotes_nonpublic = ?,
1593 permanent_location = ?,
1605 more_subfields_xml = ?,
1610 my $sth = $dbh->prepare($query);
1611 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1613 $item->{'biblionumber'},
1614 $item->{'biblioitemnumber'},
1616 $item->{'dateaccessioned'},
1617 $item->{'booksellerid'},
1618 $item->{'homebranch'},
1620 $item->{'replacementprice'},
1621 $item->{'replacementpricedate'} || $today,
1622 $item->{datelastborrowed},
1623 $item->{datelastseen} || $today,
1625 $item->{'notforloan'},
1627 $item->{'itemlost'},
1628 $item->{'withdrawn'},
1629 $item->{'itemcallnumber'},
1630 $item->{'coded_location_qualifier'},
1631 $item->{'restricted'},
1632 $item->{'itemnotes'},
1633 $item->{'itemnotes_nonpublic'},
1634 $item->{'holdingbranch'},
1636 $item->{'location'},
1637 $item->{'permanent_location'},
1640 $item->{'renewals'},
1641 $item->{'reserves'},
1642 $item->{'items.cn_source'},
1643 $item->{'items.cn_sort'},
1646 $item->{'materials'},
1648 $item->{'enumchron'},
1649 $item->{'more_subfields_xml'},
1650 $item->{'copynumber'},
1651 $item->{'stocknumber'},
1652 $item->{'new_status'},
1656 if ( defined $sth->errstr ) {
1657 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1660 $itemnumber = $dbh->{'mysql_insertid'};
1663 return ( $itemnumber, $error );
1666 =head2 MoveItemFromBiblio
1668 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
1670 Moves an item from a biblio to another
1672 Returns undef if the move failed or the biblionumber of the destination record otherwise
1676 sub MoveItemFromBiblio {
1677 my ($itemnumber, $frombiblio, $tobiblio) = @_;
1678 my $dbh = C4::Context->dbh;
1679 my ( $tobiblioitem ) = $dbh->selectrow_array(q|
1680 SELECT biblioitemnumber
1682 WHERE biblionumber = ?
1683 |, undef, $tobiblio );
1684 my $return = $dbh->do(q|
1686 SET biblioitemnumber = ?,
1688 WHERE itemnumber = ?
1689 AND biblionumber = ?
1690 |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
1692 ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
1693 ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
1694 # Checking if the item we want to move is in an order
1695 require C4::Acquisition;
1696 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
1698 # Replacing the biblionumber within the order if necessary
1699 $order->{'biblionumber'} = $tobiblio;
1700 C4::Acquisition::ModOrder($order);
1703 # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
1704 for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
1707 SET biblionumber = ?
1708 WHERE itemnumber = ?
1709 |, undef, $tobiblio, $itemnumber );
1716 =head2 ItemSafeToDelete
1718 ItemSafeToDelete( $biblionumber, $itemnumber);
1720 Exported function (core API) for checking whether an item record is safe to delete.
1722 returns 1 if the item is safe to delete,
1724 "book_on_loan" if the item is checked out,
1726 "not_same_branch" if the item is blocked by independent branches,
1728 "book_reserved" if the there are holds aganst the item, or
1730 "linked_analytics" if the item has linked analytic records.
1734 sub ItemSafeToDelete {
1735 my ( $biblionumber, $itemnumber ) = @_;
1737 my $dbh = C4::Context->dbh;
1741 my $countanalytics = GetAnalyticsCount($itemnumber);
1743 my $item = Koha::Items->find($itemnumber) or return;
1745 if ($item->checkout) {
1746 $status = "book_on_loan";
1748 elsif ( defined C4::Context->userenv
1749 and !C4::Context->IsSuperLibrarian()
1750 and C4::Context->preference("IndependentBranches")
1751 and ( C4::Context->userenv->{branch} ne $item->homebranch ) )
1753 $status = "not_same_branch";
1756 # check it doesn't have a waiting reserve
1757 my $sth = $dbh->prepare(
1759 SELECT COUNT(*) FROM reserves
1760 WHERE (found = 'W' OR found = 'T')
1764 $sth->execute($itemnumber);
1765 my ($reserve) = $sth->fetchrow;
1767 $status = "book_reserved";
1769 elsif ( $countanalytics > 0 ) {
1770 $status = "linked_analytics";
1781 DelItemCheck( $biblionumber, $itemnumber);
1783 Exported function (core API) for deleting an item record in Koha if there no current issue.
1785 DelItemCheck wraps ItemSafeToDelete around DelItem.
1790 my ( $biblionumber, $itemnumber ) = @_;
1791 my $status = ItemSafeToDelete( $biblionumber, $itemnumber );
1793 if ( $status == 1 ) {
1796 biblionumber => $biblionumber,
1797 itemnumber => $itemnumber
1804 =head2 _koha_modify_item
1806 my ($itemnumber,$error) =_koha_modify_item( $item );
1808 Perform the actual update of the C<items> row. Note that this
1809 routine accepts a hashref specifying the columns to update.
1813 sub _koha_modify_item {
1815 my $dbh=C4::Context->dbh;
1818 my $query = "UPDATE items SET ";
1820 _mod_item_dates( $item );
1821 for my $key ( keys %$item ) {
1822 next if ( $key eq 'itemnumber' );
1824 push @bind, $item->{$key};
1827 $query .= " WHERE itemnumber=?";
1828 push @bind, $item->{'itemnumber'};
1829 my $sth = $dbh->prepare($query);
1830 $sth->execute(@bind);
1832 $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
1835 return ($item->{'itemnumber'},$error);
1838 sub _mod_item_dates { # date formatting for date fields in item hash
1840 return if !$item || ref($item) ne 'HASH';
1843 { $_ =~ /^onloan$|^date|date$|datetime$/ }
1845 # Incl. dateaccessioned,replacementpricedate,datelastborrowed,datelastseen
1846 # NOTE: We do not (yet) have items fields ending with datetime
1847 # Fields with _on$ have been handled already
1849 foreach my $key ( @keys ) {
1850 next if !defined $item->{$key}; # skip undefs
1851 my $dt = eval { dt_from_string( $item->{$key} ) };
1852 # eval: dt_from_string will die on us if we pass illegal dates
1855 if( defined $dt && ref($dt) eq 'DateTime' ) {
1856 if( $key =~ /datetime/ ) {
1857 $newstr = DateTime::Format::MySQL->format_datetime($dt);
1859 $newstr = DateTime::Format::MySQL->format_date($dt);
1862 $item->{$key} = $newstr; # might be undef to clear garbage
1866 =head2 _koha_delete_item
1868 _koha_delete_item( $itemnum );
1870 Internal function to delete an item record from the koha tables
1874 sub _koha_delete_item {
1875 my ( $itemnum ) = @_;
1877 my $dbh = C4::Context->dbh;
1878 # save the deleted item to deleteditems table
1879 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1880 $sth->execute($itemnum);
1881 my $data = $sth->fetchrow_hashref();
1883 # There is no item to delete
1884 return 0 unless $data;
1886 my $query = "INSERT INTO deleteditems SET ";
1888 foreach my $key ( keys %$data ) {
1889 next if ( $key eq 'timestamp' ); # timestamp will be set by db
1890 $query .= "$key = ?,";
1891 push( @bind, $data->{$key} );
1894 $sth = $dbh->prepare($query);
1895 $sth->execute(@bind);
1897 # delete from items table
1898 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1899 my $deleted = $sth->execute($itemnum);
1900 return ( $deleted == 1 ) ? 1 : 0;
1903 =head2 _marc_from_item_hash
1905 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1907 Given an item hash representing a complete item record,
1908 create a C<MARC::Record> object containing an embedded
1909 tag representing that item.
1911 The third, optional parameter C<$unlinked_item_subfields> is
1912 an arrayref of subfields (not mapped to C<items> fields per the
1913 framework) to be added to the MARC representation
1918 sub _marc_from_item_hash {
1920 my $frameworkcode = shift;
1921 my $unlinked_item_subfields;
1923 $unlinked_item_subfields = shift;
1926 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1927 # Also, don't emit a subfield if the underlying field is blank.
1928 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1929 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1930 : () } keys %{ $item } };
1932 my $item_marc = MARC::Record->new();
1933 foreach my $item_field ( keys %{$mungeditem} ) {
1934 my ( $tag, $subfield ) = C4::Biblio::GetMarcFromKohaField( $item_field, $frameworkcode );
1935 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1936 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
1937 foreach my $value (@values){
1938 if ( my $field = $item_marc->field($tag) ) {
1939 $field->add_subfields( $subfield => $value );
1941 my $add_subfields = [];
1942 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1943 $add_subfields = $unlinked_item_subfields;
1945 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
1953 =head2 _repack_item_errors
1955 Add an error message hash generated by C<CheckItemPreSave>
1956 to a list of errors.
1960 sub _repack_item_errors {
1961 my $item_sequence_num = shift;
1962 my $item_ref = shift;
1963 my $error_ref = shift;
1965 my @repacked_errors = ();
1967 foreach my $error_code (sort keys %{ $error_ref }) {
1968 my $repacked_error = {};
1969 $repacked_error->{'item_sequence'} = $item_sequence_num;
1970 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
1971 $repacked_error->{'error_code'} = $error_code;
1972 $repacked_error->{'error_information'} = $error_ref->{$error_code};
1973 push @repacked_errors, $repacked_error;
1976 return @repacked_errors;
1979 =head2 _get_unlinked_item_subfields
1981 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
1985 sub _get_unlinked_item_subfields {
1986 my $original_item_marc = shift;
1987 my $frameworkcode = shift;
1989 my $marcstructure = C4::Biblio::GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
1991 # assume that this record has only one field, and that that
1992 # field contains only the item information
1994 my @fields = $original_item_marc->fields();
1995 if ($#fields > -1) {
1996 my $field = $fields[0];
1997 my $tag = $field->tag();
1998 foreach my $subfield ($field->subfields()) {
1999 if (defined $subfield->[1] and
2000 $subfield->[1] ne '' and
2001 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2002 push @$subfields, $subfield->[0] => $subfield->[1];
2009 =head2 _get_unlinked_subfields_xml
2011 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2015 sub _get_unlinked_subfields_xml {
2016 my $unlinked_item_subfields = shift;
2019 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2020 my $marc = MARC::Record->new();
2021 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2022 # used in the framework
2023 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2024 $marc->encoding("UTF-8");
2025 $xml = $marc->as_xml("USMARC");
2031 =head2 _parse_unlinked_item_subfields_from_xml
2033 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2037 sub _parse_unlinked_item_subfields_from_xml {
2039 require C4::Charset;
2040 return unless defined $xml and $xml ne "";
2041 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2042 my $unlinked_subfields = [];
2043 my @fields = $marc->fields();
2044 if ($#fields > -1) {
2045 foreach my $subfield ($fields[0]->subfields()) {
2046 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2049 return $unlinked_subfields;
2052 =head2 GetAnalyticsCount
2054 $count= &GetAnalyticsCount($itemnumber)
2056 counts Usage of itemnumber in Analytical bibliorecords.
2060 sub GetAnalyticsCount {
2061 my ($itemnumber) = @_;
2063 ### ZOOM search here
2065 $query= "hi=".$itemnumber;
2066 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
2067 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
2071 =head2 SearchItemsByField
2073 my $items = SearchItemsByField($field, $value);
2075 SearchItemsByField will search for items on a specific given field.
2076 For instance you can search all items with a specific stocknumber like this:
2078 my $items = SearchItemsByField('stocknumber', $stocknumber);
2082 sub SearchItemsByField {
2083 my ($field, $value) = @_;
2090 my ($results) = SearchItems($filters);
2094 sub _SearchItems_build_where_fragment {
2097 my $dbh = C4::Context->dbh;
2100 if (exists($filter->{conjunction})) {
2101 my (@where_strs, @where_args);
2102 foreach my $f (@{ $filter->{filters} }) {
2103 my $fragment = _SearchItems_build_where_fragment($f);
2105 push @where_strs, $fragment->{str};
2106 push @where_args, @{ $fragment->{args} };
2111 $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
2114 args => \@where_args,
2118 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2119 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2120 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2121 my @operators = qw(= != > < >= <= like);
2122 my $field = $filter->{field};
2123 if ( (0 < grep /^$field$/, @columns) or (substr($field, 0, 5) eq 'marc:') ) {
2124 my $op = $filter->{operator};
2125 my $query = $filter->{query};
2127 if (!$op or (0 == grep /^$op$/, @operators)) {
2128 $op = '='; # default operator
2132 if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
2134 my $marcsubfield = $2;
2135 my ($kohafield) = $dbh->selectrow_array(q|
2136 SELECT kohafield FROM marc_subfield_structure
2137 WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
2138 |, undef, $marcfield, $marcsubfield);
2141 $column = $kohafield;
2143 # MARC field is not linked to a DB field so we need to use
2144 # ExtractValue on marcxml from biblio_metadata or
2145 # items.more_subfields_xml, depending on the MARC field.
2148 my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber');
2149 if ($marcfield eq $itemfield) {
2150 $sqlfield = 'more_subfields_xml';
2151 $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
2153 $sqlfield = 'metadata'; # From biblio_metadata
2154 if ($marcfield < 10) {
2155 $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
2157 $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
2160 $column = "ExtractValue($sqlfield, '$xpath')";
2166 if (ref $query eq 'ARRAY') {
2169 } elsif ($op eq '!=') {
2173 str => "$column $op (" . join (',', ('?') x @$query) . ")",
2178 str => "$column $op ?",
2185 return $where_fragment;
2190 my ($items, $total) = SearchItems($filter, $params);
2192 Perform a search among items
2194 $filter is a reference to a hash which can be a filter, or a combination of filters.
2196 A filter has the following keys:
2200 =item * field: the name of a SQL column in table items
2202 =item * query: the value to search in this column
2204 =item * operator: comparison operator. Can be one of = != > < >= <= like
2208 A combination of filters hash the following keys:
2212 =item * conjunction: 'AND' or 'OR'
2214 =item * filters: array ref of filters
2218 $params is a reference to a hash that can contain the following parameters:
2222 =item * rows: Number of items to return. 0 returns everything (default: 0)
2224 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2227 =item * sortby: A SQL column name in items table to sort on
2229 =item * sortorder: 'ASC' or 'DESC'
2236 my ($filter, $params) = @_;
2240 return unless ref $filter eq 'HASH';
2241 return unless ref $params eq 'HASH';
2243 # Default parameters
2244 $params->{rows} ||= 0;
2245 $params->{page} ||= 1;
2246 $params->{sortby} ||= 'itemnumber';
2247 $params->{sortorder} ||= 'ASC';
2249 my ($where_str, @where_args);
2250 my $where_fragment = _SearchItems_build_where_fragment($filter);
2251 if ($where_fragment) {
2252 $where_str = $where_fragment->{str};
2253 @where_args = @{ $where_fragment->{args} };
2256 my $dbh = C4::Context->dbh;
2258 SELECT SQL_CALC_FOUND_ROWS items.*
2260 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2261 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
2262 LEFT JOIN biblio_metadata ON biblio_metadata.biblionumber = biblio.biblionumber
2265 if (defined $where_str and $where_str ne '') {
2266 $query .= qq{ AND $where_str };
2269 $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.schema = ? };
2270 push @where_args, C4::Context->preference('marcflavour');
2272 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2273 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2274 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2275 my $sortby = (0 < grep {$params->{sortby} eq $_} @columns)
2276 ? $params->{sortby} : 'itemnumber';
2277 my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC';
2278 $query .= qq{ ORDER BY $sortby $sortorder };
2280 my $rows = $params->{rows};
2283 my $offset = $rows * ($params->{page}-1);
2284 $query .= qq { LIMIT ?, ? };
2285 push @limit_args, $offset, $rows;
2288 my $sth = $dbh->prepare($query);
2289 my $rv = $sth->execute(@where_args, @limit_args);
2291 return unless ($rv);
2292 my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2294 return ($sth->fetchall_arrayref({}), $total_rows);
2298 =head1 OTHER FUNCTIONS
2302 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2304 Find the given $subfield in the given $tag in the given
2305 MARC::Record $record. If the subfield is found, returns
2306 the (indicators, value) pair; otherwise, (undef, undef) is
2310 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2311 I suggest we export it from this module.
2316 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2319 if ( $tagfield < 10 ) {
2320 if ( $record->field($tagfield) ) {
2321 push @result, $record->field($tagfield)->data();
2326 foreach my $field ( $record->field($tagfield) ) {
2327 my @subfields = $field->subfields();
2328 foreach my $subfield (@subfields) {
2329 if ( @$subfield[0] eq $insubfield ) {
2330 push @result, @$subfield[1];
2331 $indicator = $field->indicator(1) . $field->indicator(2);
2336 return ( $indicator, @result );
2340 =head2 PrepareItemrecordDisplay
2342 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2344 Returns a hash with all the fields for Display a given item data in a template
2346 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2350 sub PrepareItemrecordDisplay {
2352 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2354 my $dbh = C4::Context->dbh;
2355 $frameworkcode = C4::Biblio::GetFrameworkCode($bibnum) if $bibnum;
2356 my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2358 # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
2359 # a shared data structure. No plugin (including custom ones) should change
2360 # its contents. See also GetMarcStructure.
2361 my $tagslib = GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } );
2363 # return nothing if we don't have found an existing framework.
2364 return q{} unless $tagslib;
2367 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2371 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2373 SELECT authorised_value,lib FROM authorised_values
2376 LEFT JOIN authorised_values_branches ON ( id = av_id )
2381 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2382 $query .= qq{ ORDER BY lib};
2383 my $authorised_values_sth = $dbh->prepare( $query );
2384 foreach my $tag ( sort keys %{$tagslib} ) {
2387 # loop through each subfield
2389 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2390 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
2391 next unless ( $tagslib->{$tag}->{$subfield}->{'tab'} );
2392 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2394 $subfield_data{tag} = $tag;
2395 $subfield_data{subfield} = $subfield;
2396 $subfield_data{countsubfield} = $cntsubf++;
2397 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2398 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2400 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2401 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2402 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2403 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2404 $subfield_data{hidden} = "display:none"
2405 if ( ( $tagslib->{$tag}->{$subfield}->{hidden} > 4 )
2406 || ( $tagslib->{$tag}->{$subfield}->{hidden} < -4 ) );
2407 my ( $x, $defaultvalue );
2409 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2411 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2412 if ( !defined $defaultvalue ) {
2413 $defaultvalue = q||;
2415 $defaultvalue =~ s/"/"/g;
2418 my $maxlength = $tagslib->{$tag}->{$subfield}->{maxlength};
2420 # search for itemcallnumber if applicable
2421 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2422 && C4::Context->preference('itemcallnumber') ) {
2423 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2424 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2425 if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2426 $defaultvalue = $field->subfield($CNsubfield);
2429 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2431 && $defaultvalues->{'callnumber'} ) {
2432 if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ){
2433 # if the item record exists, only use default value if the item has no callnumber
2434 $defaultvalue = $defaultvalues->{callnumber};
2435 } elsif ( !$itemrecord and $defaultvalues ) {
2436 # if the item record *doesn't* exists, always use the default value
2437 $defaultvalue = $defaultvalues->{callnumber};
2440 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2442 && $defaultvalues->{'branchcode'} ) {
2443 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2444 $defaultvalue = $defaultvalues->{branchcode};
2447 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2449 && $defaultvalues->{'location'} ) {
2451 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2452 # if the item record exists, only use default value if the item has no locationr
2453 $defaultvalue = $defaultvalues->{location};
2454 } elsif ( !$itemrecord and $defaultvalues ) {
2455 # if the item record *doesn't* exists, always use the default value
2456 $defaultvalue = $defaultvalues->{location};
2459 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2460 my @authorised_values;
2463 # builds list, depending on authorised value...
2465 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2466 if ( ( C4::Context->preference("IndependentBranches") )
2467 && !C4::Context->IsSuperLibrarian() ) {
2468 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2469 $sth->execute( C4::Context->userenv->{branch} );
2470 push @authorised_values, ""
2471 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2472 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2473 push @authorised_values, $branchcode;
2474 $authorised_lib{$branchcode} = $branchname;
2477 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2479 push @authorised_values, ""
2480 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2481 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2482 push @authorised_values, $branchcode;
2483 $authorised_lib{$branchcode} = $branchname;
2487 $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2488 if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2489 $defaultvalue = $defaultvalues->{branchcode};
2493 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2494 my $itemtypes = Koha::ItemTypes->search_with_localization;
2495 push @authorised_values, ""
2496 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2497 while ( my $itemtype = $itemtypes->next ) {
2498 push @authorised_values, $itemtype->itemtype;
2499 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
2501 if ($defaultvalues && $defaultvalues->{'itemtype'}) {
2502 $defaultvalue = $defaultvalues->{'itemtype'};
2506 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2507 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2509 my $class_sources = GetClassSources();
2510 my $default_source = C4::Context->preference("DefaultClassificationSource");
2512 foreach my $class_source (sort keys %$class_sources) {
2513 next unless $class_sources->{$class_source}->{'used'} or
2514 ($class_source eq $default_source);
2515 push @authorised_values, $class_source;
2516 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2519 $defaultvalue = $default_source;
2521 #---- "true" authorised value
2523 $authorised_values_sth->execute(
2524 $tagslib->{$tag}->{$subfield}->{authorised_value},
2525 $branch_limit ? $branch_limit : ()
2527 push @authorised_values, ""
2528 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2529 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2530 push @authorised_values, $value;
2531 $authorised_lib{$value} = $lib;
2534 $subfield_data{marc_value} = {
2536 values => \@authorised_values,
2537 default => "$defaultvalue",
2538 labels => \%authorised_lib,
2540 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2542 require Koha::FrameworkPlugin;
2543 my $plugin = Koha::FrameworkPlugin->new({
2544 name => $tagslib->{$tag}->{$subfield}->{value_builder},
2547 my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id}, tabloop => undef };
2548 $plugin->build( $pars );
2549 if ( $itemrecord and my $field = $itemrecord->field($tag) ) {
2550 $defaultvalue = $field->subfield($subfield);
2552 if( !$plugin->errstr ) {
2553 #TODO Move html to template; see report 12176/13397
2554 my $tab= $plugin->noclick? '-1': '';
2555 my $class= $plugin->noclick? ' disabled': '';
2556 my $title= $plugin->noclick? 'No popup': 'Tag editor';
2557 $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" /><a href="#" id="buttonDot_$subfield_data{id}" tabindex="$tab" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
2559 warn $plugin->errstr;
2560 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />); # supply default input form
2563 elsif ( $tag eq '' ) { # it's an hidden field
2564 $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
2566 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2567 $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
2569 elsif ( length($defaultvalue) > 100
2570 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2571 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2572 or (C4::Context->preference("marcflavour") eq "MARC21" and
2573 500 <= $tag && $tag < 600 )
2575 # oversize field (textarea)
2576 $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength">$defaultvalue</textarea>\n");
2578 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"$maxlength\" />";
2580 push( @loop_data, \%subfield_data );
2585 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2586 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2589 'itemtagfield' => $itemtagfield,
2590 'itemtagsubfield' => $itemtagsubfield,
2591 'itemnumber' => $itemnumber,
2592 'iteminformation' => \@loop_data
2596 sub ToggleNewStatus {
2597 my ( $params ) = @_;
2598 my @rules = @{ $params->{rules} };
2599 my $report_only = $params->{report_only};
2601 my $dbh = C4::Context->dbh;
2603 my @item_columns = map { "items.$_" } Koha::Items->columns;
2604 my @biblioitem_columns = map { "biblioitems.$_" } Koha::Biblioitems->columns;
2606 for my $rule ( @rules ) {
2607 my $age = $rule->{age};
2608 my $conditions = $rule->{conditions};
2609 my $substitutions = $rule->{substitutions};
2610 foreach ( @$substitutions ) {
2611 ( $_->{item_field} ) = ( $_->{field} =~ /items\.(.*)/ );
2618 LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
2621 for my $condition ( @$conditions ) {
2623 grep {/^$condition->{field}$/} @item_columns
2624 or grep {/^$condition->{field}$/} @biblioitem_columns
2626 if ( $condition->{value} =~ /\|/ ) {
2627 my @values = split /\|/, $condition->{value};
2628 $query .= qq| AND $condition->{field} IN (|
2629 . join( ',', ('?') x scalar @values )
2631 push @params, @values;
2633 $query .= qq| AND $condition->{field} = ?|;
2634 push @params, $condition->{value};
2638 if ( defined $age ) {
2639 $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
2642 my $sth = $dbh->prepare($query);
2643 $sth->execute( @params );
2644 while ( my $values = $sth->fetchrow_hashref ) {
2645 my $biblionumber = $values->{biblionumber};
2646 my $itemnumber = $values->{itemnumber};
2647 for my $substitution ( @$substitutions ) {
2648 next unless $substitution->{field};
2649 next if ( defined $values->{ $substitution->{item_field} } and $values->{ $substitution->{item_field} } eq $substitution->{value} );
2650 C4::Items::ModItem( { $substitution->{item_field} => $substitution->{value} }, $biblionumber, $itemnumber )
2651 unless $report_only;
2652 push @{ $report->{$itemnumber} }, $substitution;