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);
45 get_hostitemnumbers_of
55 PrepareItemrecordDisplay
67 use List::MoreUtils qw(any);
69 use DateTime::Format::MySQL;
70 use Data::Dumper; # used as part of logging item record changes, not just for
71 # debugging; so please don't remove this
73 use Koha::AuthorisedValues;
74 use Koha::DateUtils qw(dt_from_string);
77 use Koha::Biblioitems;
80 use Koha::SearchEngine;
81 use Koha::SearchEngine::Search;
86 C4::Items - item management functions
90 This module contains an API for manipulating item
91 records in Koha, and is used by cataloguing, circulation,
92 acquisitions, and serials management.
94 # FIXME This POD is not up-to-date
95 A Koha item record is stored in two places: the
96 items table and embedded in a MARC tag in the XML
97 version of the associated bib record in C<biblioitems.marcxml>.
98 This is done to allow the item information to be readily
99 indexed (e.g., by Zebra), but means that each item
100 modification transaction must keep the items table
101 and the MARC XML in sync at all times.
103 Consequently, all code that creates, modifies, or deletes
104 item records B<must> use an appropriate function from
105 C<C4::Items>. If no existing function is suitable, it is
106 better to add one to C<C4::Items> than to use add
107 one-off SQL statements to add or modify items.
109 The items table will be considered authoritative. In other
110 words, if there is ever a discrepancy between the items
111 table and the MARC XML, the items table should be considered
114 =head1 HISTORICAL NOTE
116 Most of the functions in C<C4::Items> were originally in
117 the C<C4::Biblio> module.
119 =head1 CORE EXPORTED FUNCTIONS
121 The following functions are meant for use by users
128 $item = GetItem($itemnumber,$barcode,$serial);
130 Return item information, for a given itemnumber or barcode.
131 The return value is a hashref mapping item column
132 names to values. If C<$serial> is true, include serial publication data.
137 my ($itemnumber,$barcode, $serial) = @_;
138 my $dbh = C4::Context->dbh;
142 $item = Koha::Items->find( $itemnumber );
144 $item = Koha::Items->find( { barcode => $barcode } );
147 return unless ( $item );
149 my $data = $item->unblessed();
150 $data->{itype} = $item->effective_itemtype(); # set the correct itype
153 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
154 $ssth->execute( $data->{'itemnumber'} );
155 ( $data->{'serialseq'}, $data->{'publisheddate'} ) = $ssth->fetchrow_array();
163 CartToShelf($itemnumber);
165 Set the current shelving location of the item record
166 to its stored permanent shelving location. This is
167 primarily used to indicate when an item whose current
168 location is a special processing ('PROC') or shelving cart
169 ('CART') location is back in the stacks.
174 my ( $itemnumber ) = @_;
176 unless ( $itemnumber ) {
177 croak "FAILED CartToShelf() - no itemnumber supplied";
180 my $item = GetItem($itemnumber);
181 if ( $item->{location} eq 'CART' ) {
182 $item->{location} = $item->{permanent_location};
183 ModItem($item, undef, $itemnumber);
189 ShelfToCart($itemnumber);
191 Set the current shelving location of the item
192 to shelving cart ('CART').
197 my ( $itemnumber ) = @_;
199 unless ( $itemnumber ) {
200 croak "FAILED ShelfToCart() - no itemnumber supplied";
203 my $item = GetItem($itemnumber);
204 $item->{'location'} = 'CART';
205 ModItem($item, undef, $itemnumber);
208 =head2 AddItemFromMarc
210 my ($biblionumber, $biblioitemnumber, $itemnumber)
211 = AddItemFromMarc($source_item_marc, $biblionumber);
213 Given a MARC::Record object containing an embedded item
214 record and a biblionumber, create a new item record.
218 sub AddItemFromMarc {
219 my ( $source_item_marc, $biblionumber ) = @_;
220 my $dbh = C4::Context->dbh;
222 # parse item hash from MARC
223 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
224 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
226 my $localitemmarc = MARC::Record->new;
227 $localitemmarc->append_fields( $source_item_marc->field($itemtag) );
228 my $item = C4::Biblio::TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
229 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
230 return AddItem( $item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields );
235 my ($biblionumber, $biblioitemnumber, $itemnumber)
236 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
238 Given a hash containing item column names as keys,
239 create a new Koha item record.
241 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
242 do not need to be supplied for general use; they exist
243 simply to allow them to be picked up from AddItemFromMarc.
245 The final optional parameter, C<$unlinked_item_subfields>, contains
246 an arrayref containing subfields present in the original MARC
247 representation of the item (e.g., from the item editor) that are
248 not mapped to C<items> columns directly but should instead
249 be stored in C<items.more_subfields_xml> and included in
250 the biblio items tag for display and indexing.
256 my $biblionumber = shift;
258 my $dbh = @_ ? shift : C4::Context->dbh;
259 my $frameworkcode = @_ ? shift : C4::Biblio::GetFrameworkCode($biblionumber);
260 my $unlinked_item_subfields;
262 $unlinked_item_subfields = shift;
265 # needs old biblionumber and biblioitemnumber
266 $item->{'biblionumber'} = $biblionumber;
267 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
268 $sth->execute( $item->{'biblionumber'} );
269 ( $item->{'biblioitemnumber'} ) = $sth->fetchrow;
271 _set_defaults_for_add($item);
272 _set_derived_columns_for_add($item);
273 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
275 # FIXME - checks here
276 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
277 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
278 $itype_sth->execute( $item->{'biblionumber'} );
279 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
282 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
285 $item->{'itemnumber'} = $itemnumber;
287 C4::Biblio::ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver" );
289 logaction( "CATALOGUING", "ADD", $itemnumber, "item" )
290 if C4::Context->preference("CataloguingLog");
292 return ( $item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber );
295 =head2 AddItemBatchFromMarc
297 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
298 $biblionumber, $biblioitemnumber, $frameworkcode);
300 Efficiently create item records from a MARC biblio record with
301 embedded item fields. This routine is suitable for batch jobs.
303 This API assumes that the bib record has already been
304 saved to the C<biblio> and C<biblioitems> tables. It does
305 not expect that C<biblio_metadata.metadata> is populated, but it
306 will do so via a call to ModBibiloMarc.
308 The goal of this API is to have a similar effect to using AddBiblio
309 and AddItems in succession, but without inefficient repeated
310 parsing of the MARC XML bib record.
312 This function returns an arrayref of new itemsnumbers and an arrayref of item
313 errors encountered during the processing. Each entry in the errors
314 list is a hashref containing the following keys:
320 Sequence number of original item tag in the MARC record.
324 Item barcode, provide to assist in the construction of
325 useful error messages.
329 Code representing the error condition. Can be 'duplicate_barcode',
330 'invalid_homebranch', or 'invalid_holdingbranch'.
332 =item error_information
334 Additional information appropriate to the error condition.
340 sub AddItemBatchFromMarc {
341 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
343 my @itemnumbers = ();
345 my $dbh = C4::Context->dbh;
347 # We modify the record, so lets work on a clone so we don't change the
349 $record = $record->clone();
350 # loop through the item tags and start creating items
351 my @bad_item_fields = ();
352 my ($itemtag, $itemsubfield) = C4::Biblio::GetMarcFromKohaField("items.itemnumber",'');
353 my $item_sequence_num = 0;
354 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
355 $item_sequence_num++;
356 # we take the item field and stick it into a new
357 # MARC record -- this is required so far because (FIXME)
358 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
359 # and there is no TransformMarcFieldToKoha
360 my $temp_item_marc = MARC::Record->new();
361 $temp_item_marc->append_fields($item_field);
363 # add biblionumber and biblioitemnumber
364 my $item = TransformMarcToKoha( $temp_item_marc, $frameworkcode, 'items' );
365 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
366 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
367 $item->{'biblionumber'} = $biblionumber;
368 $item->{'biblioitemnumber'} = $biblioitemnumber;
370 # check for duplicate barcode
371 my %item_errors = CheckItemPreSave($item);
373 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
374 push @bad_item_fields, $item_field;
378 _set_defaults_for_add($item);
379 _set_derived_columns_for_add($item);
380 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
381 warn $error if $error;
382 push @itemnumbers, $itemnumber; # FIXME not checking error
383 $item->{'itemnumber'} = $itemnumber;
385 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
387 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
388 $item_field->replace_with($new_item_marc->field($itemtag));
391 # remove any MARC item fields for rejected items
392 foreach my $item_field (@bad_item_fields) {
393 $record->delete_field($item_field);
396 # update the MARC biblio
397 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
399 return (\@itemnumbers, \@errors);
402 =head2 ModItemFromMarc
404 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
406 This function updates an item record based on a supplied
407 C<MARC::Record> object containing an embedded item field.
408 This API is meant for the use of C<additem.pl>; for
409 other purposes, C<ModItem> should be used.
411 This function uses the hash %default_values_for_mod_from_marc,
412 which contains default values for item fields to
413 apply when modifying an item. This is needed because
414 if an item field's value is cleared, TransformMarcToKoha
415 does not include the column in the
416 hash that's passed to ModItem, which without
417 use of this hash makes it impossible to clear
418 an item field's value. See bug 2466.
420 Note that only columns that can be directly
421 changed from the cataloging and serials
422 item editors are included in this hash.
428 sub _build_default_values_for_mod_marc {
429 # Has no framework parameter anymore, since Default is authoritative
430 # for Koha to MARC mappings.
432 my $cache = Koha::Caches->get_instance();
433 my $cache_key = "default_value_for_mod_marc-";
434 my $cached = $cache->get_from_cache($cache_key);
435 return $cached if $cached;
437 my $default_values = {
439 booksellerid => undef,
441 'items.cn_source' => undef,
442 coded_location_qualifier => undef,
446 holdingbranch => undef,
448 itemcallnumber => undef,
451 itemnotes_nonpublic => undef,
454 permanent_location => undef,
458 # paidfor => undef, # commented, see bug 12817
460 replacementprice => undef,
461 replacementpricedate => undef,
464 stocknumber => undef,
468 my %default_values_for_mod_from_marc;
469 while ( my ( $field, $default_value ) = each %$default_values ) {
470 my $kohafield = $field;
471 $kohafield =~ s|^([^\.]+)$|items.$1|;
472 $default_values_for_mod_from_marc{$field} = $default_value
473 if C4::Biblio::GetMarcFromKohaField( $kohafield );
476 $cache->set_in_cache($cache_key, \%default_values_for_mod_from_marc);
477 return \%default_values_for_mod_from_marc;
480 sub ModItemFromMarc {
481 my $item_marc = shift;
482 my $biblionumber = shift;
483 my $itemnumber = shift;
485 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
486 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
488 my $localitemmarc = MARC::Record->new;
489 $localitemmarc->append_fields( $item_marc->field($itemtag) );
490 my $item = TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
491 my $default_values = _build_default_values_for_mod_marc();
492 foreach my $item_field ( keys %$default_values ) {
493 $item->{$item_field} = $default_values->{$item_field}
494 unless exists $item->{$item_field};
496 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
498 ModItem( $item, $biblionumber, $itemnumber, { unlinked_item_subfields => $unlinked_item_subfields } );
505 { column => $newvalue },
509 [ unlinked_item_subfields => $unlinked_item_subfields, ]
514 Change one or more columns in an item record.
516 The first argument is a hashref mapping from item column
517 names to the new values. The second and third arguments
518 are the biblionumber and itemnumber, respectively.
519 The fourth, optional parameter (additional_params) may contain the keys
520 unlinked_item_subfields and log_action.
522 C<$unlinked_item_subfields> contains an arrayref containing
523 subfields present in the original MARC
524 representation of the item (e.g., from the item editor) that are
525 not mapped to C<items> columns directly but should instead
526 be stored in C<items.more_subfields_xml> and included in
527 the biblio items tag for display and indexing.
529 If one of the changed columns is used to calculate
530 the derived value of a column such as C<items.cn_sort>,
531 this routine will perform the necessary calculation
534 If log_action is set to false, the action will not be logged.
535 If log_action is true or undefined, the action will be logged.
540 my ( $item, $biblionumber, $itemnumber, $additional_params ) = @_;
541 my $log_action = $additional_params->{log_action} // 1;
542 my $unlinked_item_subfields = $additional_params->{unlinked_item_subfields};
544 return unless %$item;
545 $item->{'itemnumber'} = $itemnumber or return;
547 # if $biblionumber is undefined, get it from the current item
548 unless (defined $biblionumber) {
549 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
552 if ($unlinked_item_subfields) {
553 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
556 my @fields = qw( itemlost withdrawn damaged );
558 # Only call GetItem if we need to set an "on" date field
559 if ( $item->{itemlost} || $item->{withdrawn} || $item->{damaged} ) {
560 my $pre_mod_item = GetItem( $item->{'itemnumber'} );
561 for my $field (@fields) {
562 if ( defined( $item->{$field} )
563 and not $pre_mod_item->{$field}
564 and $item->{$field} )
566 $item->{ $field . '_on' } =
567 DateTime::Format::MySQL->format_datetime( dt_from_string() );
572 # If the field is defined but empty, we are removing and,
573 # and thus need to clear out the 'on' field as well
574 for my $field (@fields) {
575 if ( defined( $item->{$field} ) && !$item->{$field} ) {
576 $item->{ $field . '_on' } = undef;
581 _set_derived_columns_for_mod($item);
582 _do_column_fixes_for_mod($item);
585 # attempt to change itemnumber
586 # attempt to change biblionumber (if we want
587 # an API to relink an item to a different bib,
588 # it should be a separate function)
591 _koha_modify_item($item);
593 # request that bib be reindexed so that searching on current
594 # item status is possible
595 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
597 logaction( "CATALOGUING", "MODIFY", $itemnumber, "item " . Dumper($item) )
598 if $log_action && C4::Context->preference("CataloguingLog");
601 =head2 ModItemTransfer
603 ModItemTransfer($itenumber, $frombranch, $tobranch);
605 Marks an item as being transferred from one branch
610 sub ModItemTransfer {
611 my ( $itemnumber, $frombranch, $tobranch ) = @_;
613 my $dbh = C4::Context->dbh;
615 # Remove the 'shelving cart' location status if it is being used.
616 CartToShelf( $itemnumber ) if ( C4::Context->preference("ReturnToShelvingCart") );
618 $dbh->do("UPDATE branchtransfers SET datearrived = NOW(), comments = ? WHERE itemnumber = ? AND datearrived IS NULL", undef, "Canceled, new transfer from $frombranch to $tobranch created", $itemnumber);
620 #new entry in branchtransfers....
621 my $sth = $dbh->prepare(
622 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
623 VALUES (?, ?, NOW(), ?)");
624 $sth->execute($itemnumber, $frombranch, $tobranch);
626 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
627 ModDateLastSeen($itemnumber);
631 =head2 ModDateLastSeen
633 ModDateLastSeen( $itemnumber, $leave_item_lost );
635 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
636 C<$itemnumber> is the item number
637 C<$leave_item_lost> determines if a lost item will be found or remain lost
641 sub ModDateLastSeen {
642 my ( $itemnumber, $leave_item_lost ) = @_;
644 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
647 $params->{datelastseen} = $today;
648 $params->{itemlost} = 0 unless $leave_item_lost;
650 ModItem( $params, undef, $itemnumber, { log_action => 0 } );
655 DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
657 Exported function (core API) for deleting an item record in Koha.
664 my $itemnumber = $params->{itemnumber};
665 my $biblionumber = $params->{biblionumber};
667 unless ($biblionumber) {
668 my $item = Koha::Items->find( $itemnumber );
669 $biblionumber = $item ? $item->biblio->biblionumber : undef;
672 # If there is no biblionumber for the given itemnumber, there is nothing to delete
673 return 0 unless $biblionumber;
675 # FIXME check the item has no current issues
676 my $deleted = _koha_delete_item( $itemnumber );
678 ModZebra( $biblionumber, "specialUpdate", "biblioserver" );
680 #search item field code
681 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
685 =head2 CheckItemPreSave
687 my $item_ref = TransformMarcToKoha($marc, 'items');
689 my %errors = CheckItemPreSave($item_ref);
690 if (exists $errors{'duplicate_barcode'}) {
691 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
692 } elsif (exists $errors{'invalid_homebranch'}) {
693 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
694 } elsif (exists $errors{'invalid_holdingbranch'}) {
695 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
700 Given a hashref containing item fields, determine if it can be
701 inserted or updated in the database. Specifically, checks for
702 database integrity issues, and returns a hash containing any
703 of the following keys, if applicable.
707 =item duplicate_barcode
709 Barcode, if it duplicates one already found in the database.
711 =item invalid_homebranch
713 Home branch, if not defined in branches table.
715 =item invalid_holdingbranch
717 Holding branch, if not defined in branches table.
721 This function does NOT implement any policy-related checks,
722 e.g., whether current operator is allowed to save an
723 item that has a given branch code.
727 sub CheckItemPreSave {
728 my $item_ref = shift;
732 # check for duplicate barcode
733 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
734 my $existing_item= Koha::Items->find({barcode => $item_ref->{'barcode'}});
735 if ($existing_item) {
736 if (!exists $item_ref->{'itemnumber'} # new item
737 or $item_ref->{'itemnumber'} != $existing_item->itemnumber) { # existing item
738 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
743 # check for valid home branch
744 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
745 my $home_library = Koha::Libraries->find( $item_ref->{homebranch} );
746 unless (defined $home_library) {
747 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
751 # check for valid holding branch
752 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
753 my $holding_library = Koha::Libraries->find( $item_ref->{holdingbranch} );
754 unless (defined $holding_library) {
755 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
763 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
765 The following functions provide various ways of
766 getting an item record, a set of item records, or
767 lists of authorized values for certain item fields.
771 =head2 GetItemsForInventory
773 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
774 minlocation => $minlocation,
775 maxlocation => $maxlocation,
776 location => $location,
777 itemtype => $itemtype,
778 ignoreissued => $ignoreissued,
779 datelastseen => $datelastseen,
780 branchcode => $branchcode,
784 statushash => $statushash,
787 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
789 The sub returns a reference to a list of hashes, each containing
790 itemnumber, author, title, barcode, item callnumber, and date last
791 seen. It is ordered by callnumber then title.
793 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
794 the datelastseen can be used to specify that you want to see items not seen since a past date only.
795 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
796 $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.
798 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
802 sub GetItemsForInventory {
803 my ( $parameters ) = @_;
804 my $minlocation = $parameters->{'minlocation'} // '';
805 my $maxlocation = $parameters->{'maxlocation'} // '';
806 my $location = $parameters->{'location'} // '';
807 my $itemtype = $parameters->{'itemtype'} // '';
808 my $ignoreissued = $parameters->{'ignoreissued'} // '';
809 my $datelastseen = $parameters->{'datelastseen'} // '';
810 my $branchcode = $parameters->{'branchcode'} // '';
811 my $branch = $parameters->{'branch'} // '';
812 my $offset = $parameters->{'offset'} // '';
813 my $size = $parameters->{'size'} // '';
814 my $statushash = $parameters->{'statushash'} // '';
815 my $ignore_waiting_holds = $parameters->{'ignore_waiting_holds'} // '';
817 my $dbh = C4::Context->dbh;
818 my ( @bind_params, @where_strings );
820 my $select_columns = q{
821 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
823 my $select_count = q{SELECT COUNT(*)};
826 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
827 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
830 for my $authvfield (keys %$statushash){
831 if ( scalar @{$statushash->{$authvfield}} > 0 ){
832 my $joinedvals = join ',', @{$statushash->{$authvfield}};
833 push @where_strings, "$authvfield in (" . $joinedvals . ")";
839 push @where_strings, 'itemcallnumber >= ?';
840 push @bind_params, $minlocation;
844 push @where_strings, 'itemcallnumber <= ?';
845 push @bind_params, $maxlocation;
849 $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
850 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
851 push @bind_params, $datelastseen;
855 push @where_strings, 'items.location = ?';
856 push @bind_params, $location;
860 if($branch eq "homebranch"){
861 push @where_strings, 'items.homebranch = ?';
863 push @where_strings, 'items.holdingbranch = ?';
865 push @bind_params, $branchcode;
869 push @where_strings, 'biblioitems.itemtype = ?';
870 push @bind_params, $itemtype;
873 if ( $ignoreissued) {
874 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
875 push @where_strings, 'issues.date_due IS NULL';
878 if ( $ignore_waiting_holds ) {
879 $query .= "LEFT JOIN reserves ON items.itemnumber = reserves.itemnumber ";
880 push( @where_strings, q{(reserves.found != 'W' OR reserves.found IS NULL)} );
883 if ( @where_strings ) {
885 $query .= join ' AND ', @where_strings;
887 my $count_query = $select_count . $query;
888 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
889 $query .= " LIMIT $offset, $size" if ($offset and $size);
890 $query = $select_columns . $query;
891 my $sth = $dbh->prepare($query);
892 $sth->execute( @bind_params );
895 my $tmpresults = $sth->fetchall_arrayref({});
896 $sth = $dbh->prepare( $count_query );
897 $sth->execute( @bind_params );
898 my ($iTotalRecords) = $sth->fetchrow_array();
900 my @avs = Koha::AuthorisedValues->search(
901 { 'marc_subfield_structures.kohafield' => { '>' => '' },
902 'me.authorised_value' => { '>' => '' },
904 { join => { category => 'marc_subfield_structures' },
905 distinct => ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'],
906 '+select' => [ 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', 'me.lib' ],
907 '+as' => [ 'kohafield', 'frameworkcode', 'authorised_value', 'lib' ],
911 my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs };
913 foreach my $row (@$tmpresults) {
916 foreach (keys %$row) {
917 if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
918 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
924 return (\@results, $iTotalRecords);
929 @results = GetItemsInfo($biblionumber);
931 Returns information about items with the given biblionumber.
933 C<GetItemsInfo> returns a list of references-to-hash. Each element
934 contains a number of keys. Most of them are attributes from the
935 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
936 Koha database. Other keys include:
940 =item C<$data-E<gt>{branchname}>
942 The name (not the code) of the branch to which the book belongs.
944 =item C<$data-E<gt>{datelastseen}>
946 This is simply C<items.datelastseen>, except that while the date is
947 stored in YYYY-MM-DD format in the database, here it is converted to
948 DD/MM/YYYY format. A NULL date is returned as C<//>.
950 =item C<$data-E<gt>{datedue}>
952 =item C<$data-E<gt>{class}>
954 This is the concatenation of C<biblioitems.classification>, the book's
955 Dewey code, and C<biblioitems.subclass>.
957 =item C<$data-E<gt>{ocount}>
959 I think this is the number of copies of the book available.
961 =item C<$data-E<gt>{order}>
963 If this is set, it is set to C<One Order>.
970 my ( $biblionumber ) = @_;
971 my $dbh = C4::Context->dbh;
972 require C4::Languages;
973 my $language = C4::Languages::getlanguage();
979 biblioitems.itemtype,
982 biblioitems.publicationyear,
983 biblioitems.publishercode,
984 biblioitems.volumedate,
985 biblioitems.volumedesc,
988 items.notforloan as itemnotforloan,
989 issues.borrowernumber,
990 issues.date_due as datedue,
991 issues.onsite_checkout,
992 borrowers.cardnumber,
995 borrowers.branchcode as bcode,
997 serial.publisheddate,
998 itemtypes.description,
999 COALESCE( localization.translation, itemtypes.description ) AS translated_description,
1000 itemtypes.notforloan as notforloan_per_itemtype,
1004 holding.opac_info as holding_branch_opac_info,
1005 home.opac_info as home_branch_opac_info
1009 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1010 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1011 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1012 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1013 LEFT JOIN issues USING (itemnumber)
1014 LEFT JOIN borrowers USING (borrowernumber)
1015 LEFT JOIN serialitems USING (itemnumber)
1016 LEFT JOIN serial USING (serialid)
1017 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1018 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1020 LEFT JOIN localization ON itemtypes.itemtype = localization.code
1021 AND localization.entity = 'itemtypes'
1022 AND localization.lang = ?
1025 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1026 my $sth = $dbh->prepare($query);
1027 $sth->execute($language, $biblionumber);
1032 my $userenv = C4::Context->userenv;
1033 my $want_not_same_branch = C4::Context->preference("IndependentBranches") && !C4::Context->IsSuperLibrarian();
1034 while ( my $data = $sth->fetchrow_hashref ) {
1035 if ( $data->{borrowernumber} && $want_not_same_branch) {
1036 $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch};
1039 $serial ||= $data->{'serial'};
1042 # get notforloan complete status if applicable
1043 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.notforloan', authorised_value => $data->{itemnotforloan} });
1044 $data->{notforloanvalue} = $descriptions->{lib} // '';
1045 $data->{notforloanvalueopac} = $descriptions->{opac_description} // '';
1047 # get restricted status and description if applicable
1048 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.restricted', authorised_value => $data->{restricted} });
1049 $data->{restricted} = $descriptions->{lib} // '';
1050 $data->{restrictedopac} = $descriptions->{opac_description} // '';
1052 # my stack procedures
1053 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.stack', authorised_value => $data->{stack} });
1054 $data->{stack} = $descriptions->{lib} // '';
1056 # Find the last 3 people who borrowed this item.
1057 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1058 WHERE itemnumber = ?
1059 AND old_issues.borrowernumber = borrowers.borrowernumber
1060 ORDER BY returndate DESC
1062 $sth2->execute($data->{'itemnumber'});
1064 while (my $data2 = $sth2->fetchrow_hashref()) {
1065 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1066 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1067 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1071 $results[$i] = $data;
1076 ? sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
1080 =head2 GetItemsLocationInfo
1082 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1084 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1086 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1090 =item C<$data-E<gt>{homebranch}>
1092 Branch Name of the item's homebranch
1094 =item C<$data-E<gt>{holdingbranch}>
1096 Branch Name of the item's holdingbranch
1098 =item C<$data-E<gt>{location}>
1100 Item's shelving location code
1102 =item C<$data-E<gt>{location_intranet}>
1104 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1106 =item C<$data-E<gt>{location_opac}>
1108 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1111 =item C<$data-E<gt>{itemcallnumber}>
1113 Item's itemcallnumber
1115 =item C<$data-E<gt>{cn_sort}>
1117 Item's call number normalized for sorting
1123 sub GetItemsLocationInfo {
1124 my $biblionumber = shift;
1127 my $dbh = C4::Context->dbh;
1128 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1129 location, itemcallnumber, cn_sort
1130 FROM items, branches as a, branches as b
1131 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1132 AND biblionumber = ?
1133 ORDER BY cn_sort ASC";
1134 my $sth = $dbh->prepare($query);
1135 $sth->execute($biblionumber);
1137 while ( my $data = $sth->fetchrow_hashref ) {
1138 my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $data->{location} });
1139 $av = $av->count ? $av->next : undef;
1140 $data->{location_intranet} = $av ? $av->lib : '';
1141 $data->{location_opac} = $av ? $av->opac_description : '';
1142 push @results, $data;
1147 =head2 GetHostItemsInfo
1149 $hostiteminfo = GetHostItemsInfo($hostfield);
1150 Returns the iteminfo for items linked to records via a host field
1154 sub GetHostItemsInfo {
1156 my @returnitemsInfo;
1158 if( !C4::Context->preference('EasyAnalyticalRecords') ) {
1159 return @returnitemsInfo;
1163 if( C4::Context->preference('marcflavour') eq 'MARC21' ||
1164 C4::Context->preference('marcflavour') eq 'NORMARC') {
1165 @fields = $record->field('773');
1166 } elsif( C4::Context->preference('marcflavour') eq 'UNIMARC') {
1167 @fields = $record->field('461');
1170 foreach my $hostfield ( @fields ) {
1171 my $hostbiblionumber = $hostfield->subfield("0");
1172 my $linkeditemnumber = $hostfield->subfield("9");
1173 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1174 foreach my $hostitemInfo (@hostitemInfos) {
1175 if( $hostitemInfo->{itemnumber} eq $linkeditemnumber ) {
1176 push @returnitemsInfo, $hostitemInfo;
1181 return @returnitemsInfo;
1184 =head2 get_hostitemnumbers_of
1186 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1188 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1190 Return a reference on a hash where key is a biblionumber and values are
1191 references on array of itemnumbers.
1196 sub get_hostitemnumbers_of {
1197 my ($biblionumber) = @_;
1198 my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
1200 return unless $marcrecord;
1202 my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
1204 my $marcflavor = C4::Context->preference('marcflavour');
1205 if ( $marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC' ) {
1210 elsif ( $marcflavor eq 'UNIMARC' ) {
1216 foreach my $hostfield ( $marcrecord->field($tag) ) {
1217 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1218 next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield
1219 my $linkeditemnumber = $hostfield->subfield($item_s);
1220 if ( ! $linkeditemnumber ) {
1221 warn "ERROR biblionumber $biblionumber has 773^0, but doesn't have 9";
1224 my $is_from_biblio = Koha::Items->search({ itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber });
1225 push @returnhostitemnumbers, $linkeditemnumber
1229 return @returnhostitemnumbers;
1232 =head2 GetHiddenItemnumbers
1234 my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
1236 Given a list of items it checks which should be hidden from the OPAC given
1237 the current configuration. Returns a list of itemnumbers corresponding to
1238 those that should be hidden. Optionally takes a borcat parameter for certain borrower types
1243 sub GetHiddenItemnumbers {
1245 my $items = $params->{items};
1246 if (my $exceptions = C4::Context->preference('OpacHiddenItemsExceptions') and $params->{'borcat'}){
1247 foreach my $except (split(/\|/, $exceptions)){
1248 if ($params->{'borcat'} eq $except){
1249 return; # we don't hide anything for this borrower category
1255 my $yaml = C4::Context->preference('OpacHiddenItems');
1256 return () if (! $yaml =~ /\S/ );
1257 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1260 $hidingrules = YAML::Load($yaml);
1263 warn "Unable to parse OpacHiddenItems syspref : $@";
1266 my $dbh = C4::Context->dbh;
1269 foreach my $item (@$items) {
1271 # We check each rule
1272 foreach my $field (keys %$hidingrules) {
1274 if (exists $item->{$field}) {
1275 $val = $item->{$field};
1278 my $query = "SELECT $field from items where itemnumber = ?";
1279 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1281 $val = '' unless defined $val;
1283 # If the results matches the values in the yaml file
1284 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1286 # We add the itemnumber to the list
1287 push @resultitems, $item->{'itemnumber'};
1289 # If at least one rule matched for an item, no need to test the others
1294 return @resultitems;
1297 =head1 LIMITED USE FUNCTIONS
1299 The following functions, while part of the public API,
1300 are not exported. This is generally because they are
1301 meant to be used by only one script for a specific
1302 purpose, and should not be used in any other context
1303 without careful thought.
1309 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1311 Returns MARC::Record of the item passed in parameter.
1312 This function is meant for use only in C<cataloguing/additem.pl>,
1313 where it is needed to support that script's MARC-like
1319 my ( $biblionumber, $itemnumber ) = @_;
1321 # GetMarcItem has been revised so that it does the following:
1322 # 1. Gets the item information from the items table.
1323 # 2. Converts it to a MARC field for storage in the bib record.
1325 # The previous behavior was:
1326 # 1. Get the bib record.
1327 # 2. Return the MARC tag corresponding to the item record.
1329 # The difference is that one treats the items row as authoritative,
1330 # while the other treats the MARC representation as authoritative
1331 # under certain circumstances.
1333 my $itemrecord = GetItem($itemnumber);
1335 # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
1336 # Also, don't emit a subfield if the underlying field is blank.
1339 return Item2Marc($itemrecord,$biblionumber);
1343 my ($itemrecord,$biblionumber)=@_;
1346 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1347 } keys %{ $itemrecord }
1349 my $framework = C4::Biblio::GetFrameworkCode( $biblionumber );
1350 my $itemmarc = C4::Biblio::TransformKohaToMarc( $mungeditem ); # Bug 21774: no_split parameter removed to allow cloned subfields
1351 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField(
1352 "items.itemnumber", $framework,
1355 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1356 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1357 foreach my $field ($itemmarc->field($itemtag)){
1358 $field->add_subfields(@$unlinked_item_subfields);
1364 =head1 PRIVATE FUNCTIONS AND VARIABLES
1366 The following functions are not meant to be called
1367 directly, but are documented in order to explain
1368 the inner workings of C<C4::Items>.
1372 =head2 %derived_columns
1374 This hash keeps track of item columns that
1375 are strictly derived from other columns in
1376 the item record and are not meant to be set
1379 Each key in the hash should be the name of a
1380 column (as named by TransformMarcToKoha). Each
1381 value should be hashref whose keys are the
1382 columns on which the derived column depends. The
1383 hashref should also contain a 'BUILDER' key
1384 that is a reference to a sub that calculates
1389 my %derived_columns = (
1390 'items.cn_sort' => {
1391 'itemcallnumber' => 1,
1392 'items.cn_source' => 1,
1393 'BUILDER' => \&_calc_items_cn_sort,
1397 =head2 _set_derived_columns_for_add
1399 _set_derived_column_for_add($item);
1401 Given an item hash representing a new item to be added,
1402 calculate any derived columns. Currently the only
1403 such column is C<items.cn_sort>.
1407 sub _set_derived_columns_for_add {
1410 foreach my $column (keys %derived_columns) {
1411 my $builder = $derived_columns{$column}->{'BUILDER'};
1412 my $source_values = {};
1413 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1414 next if $source_column eq 'BUILDER';
1415 $source_values->{$source_column} = $item->{$source_column};
1417 $builder->($item, $source_values);
1421 =head2 _set_derived_columns_for_mod
1423 _set_derived_column_for_mod($item);
1425 Given an item hash representing a new item to be modified.
1426 calculate any derived columns. Currently the only
1427 such column is C<items.cn_sort>.
1429 This routine differs from C<_set_derived_columns_for_add>
1430 in that it needs to handle partial item records. In other
1431 words, the caller of C<ModItem> may have supplied only one
1432 or two columns to be changed, so this function needs to
1433 determine whether any of the columns to be changed affect
1434 any of the derived columns. Also, if a derived column
1435 depends on more than one column, but the caller is not
1436 changing all of then, this routine retrieves the unchanged
1437 values from the database in order to ensure a correct
1442 sub _set_derived_columns_for_mod {
1445 foreach my $column (keys %derived_columns) {
1446 my $builder = $derived_columns{$column}->{'BUILDER'};
1447 my $source_values = {};
1448 my %missing_sources = ();
1449 my $must_recalc = 0;
1450 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1451 next if $source_column eq 'BUILDER';
1452 if (exists $item->{$source_column}) {
1454 $source_values->{$source_column} = $item->{$source_column};
1456 $missing_sources{$source_column} = 1;
1460 foreach my $source_column (keys %missing_sources) {
1461 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1463 $builder->($item, $source_values);
1468 =head2 _do_column_fixes_for_mod
1470 _do_column_fixes_for_mod($item);
1472 Given an item hashref containing one or more
1473 columns to modify, fix up certain values.
1474 Specifically, set to 0 any passed value
1475 of C<notforloan>, C<damaged>, C<itemlost>, or
1476 C<withdrawn> that is either undefined or
1477 contains the empty string.
1481 sub _do_column_fixes_for_mod {
1484 if (exists $item->{'notforloan'} and
1485 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1486 $item->{'notforloan'} = 0;
1488 if (exists $item->{'damaged'} and
1489 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1490 $item->{'damaged'} = 0;
1492 if (exists $item->{'itemlost'} and
1493 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1494 $item->{'itemlost'} = 0;
1496 if (exists $item->{'withdrawn'} and
1497 (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
1498 $item->{'withdrawn'} = 0;
1500 if (exists $item->{location}
1501 and $item->{location} ne 'CART'
1502 and $item->{location} ne 'PROC'
1503 and not $item->{permanent_location}
1505 $item->{'permanent_location'} = $item->{'location'};
1507 if (exists $item->{'timestamp'}) {
1508 delete $item->{'timestamp'};
1512 =head2 _get_single_item_column
1514 _get_single_item_column($column, $itemnumber);
1516 Retrieves the value of a single column from an C<items>
1517 row specified by C<$itemnumber>.
1521 sub _get_single_item_column {
1523 my $itemnumber = shift;
1525 my $dbh = C4::Context->dbh;
1526 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1527 $sth->execute($itemnumber);
1528 my ($value) = $sth->fetchrow();
1532 =head2 _calc_items_cn_sort
1534 _calc_items_cn_sort($item, $source_values);
1536 Helper routine to calculate C<items.cn_sort>.
1540 sub _calc_items_cn_sort {
1542 my $source_values = shift;
1544 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1547 =head2 _set_defaults_for_add
1549 _set_defaults_for_add($item_hash);
1551 Given an item hash representing an item to be added, set
1552 correct default values for columns whose default value
1553 is not handled by the DBMS. This includes the following
1560 C<items.dateaccessioned>
1582 sub _set_defaults_for_add {
1584 $item->{dateaccessioned} ||= output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1585 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
1588 =head2 _koha_new_item
1590 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1592 Perform the actual insert into the C<items> table.
1596 sub _koha_new_item {
1597 my ( $item, $barcode ) = @_;
1598 my $dbh=C4::Context->dbh;
1600 $item->{permanent_location} //= $item->{location};
1601 _mod_item_dates( $item );
1603 "INSERT INTO items SET
1605 biblioitemnumber = ?,
1607 dateaccessioned = ?,
1611 replacementprice = ?,
1612 replacementpricedate = ?,
1613 datelastborrowed = ?,
1621 coded_location_qualifier = ?,
1624 itemnotes_nonpublic = ?,
1628 permanent_location = ?,
1640 more_subfields_xml = ?,
1645 my $sth = $dbh->prepare($query);
1646 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1648 $item->{'biblionumber'},
1649 $item->{'biblioitemnumber'},
1651 $item->{'dateaccessioned'},
1652 $item->{'booksellerid'},
1653 $item->{'homebranch'},
1655 $item->{'replacementprice'},
1656 $item->{'replacementpricedate'} || $today,
1657 $item->{datelastborrowed},
1658 $item->{datelastseen} || $today,
1660 $item->{'notforloan'},
1662 $item->{'itemlost'},
1663 $item->{'withdrawn'},
1664 $item->{'itemcallnumber'},
1665 $item->{'coded_location_qualifier'},
1666 $item->{'restricted'},
1667 $item->{'itemnotes'},
1668 $item->{'itemnotes_nonpublic'},
1669 $item->{'holdingbranch'},
1671 $item->{'location'},
1672 $item->{'permanent_location'},
1675 $item->{'renewals'},
1676 $item->{'reserves'},
1677 $item->{'items.cn_source'},
1678 $item->{'items.cn_sort'},
1681 $item->{'materials'},
1683 $item->{'enumchron'},
1684 $item->{'more_subfields_xml'},
1685 $item->{'copynumber'},
1686 $item->{'stocknumber'},
1687 $item->{'new_status'},
1691 if ( defined $sth->errstr ) {
1692 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1695 $itemnumber = $dbh->{'mysql_insertid'};
1698 return ( $itemnumber, $error );
1701 =head2 MoveItemFromBiblio
1703 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
1705 Moves an item from a biblio to another
1707 Returns undef if the move failed or the biblionumber of the destination record otherwise
1711 sub MoveItemFromBiblio {
1712 my ($itemnumber, $frombiblio, $tobiblio) = @_;
1713 my $dbh = C4::Context->dbh;
1714 my ( $tobiblioitem ) = $dbh->selectrow_array(q|
1715 SELECT biblioitemnumber
1717 WHERE biblionumber = ?
1718 |, undef, $tobiblio );
1719 my $return = $dbh->do(q|
1721 SET biblioitemnumber = ?,
1723 WHERE itemnumber = ?
1724 AND biblionumber = ?
1725 |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
1727 ModZebra( $tobiblio, "specialUpdate", "biblioserver" );
1728 ModZebra( $frombiblio, "specialUpdate", "biblioserver" );
1729 # Checking if the item we want to move is in an order
1730 require C4::Acquisition;
1731 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
1733 # Replacing the biblionumber within the order if necessary
1734 $order->{'biblionumber'} = $tobiblio;
1735 C4::Acquisition::ModOrder($order);
1738 # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
1739 for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
1742 SET biblionumber = ?
1743 WHERE itemnumber = ?
1744 |, undef, $tobiblio, $itemnumber );
1751 =head2 ItemSafeToDelete
1753 ItemSafeToDelete( $biblionumber, $itemnumber);
1755 Exported function (core API) for checking whether an item record is safe to delete.
1757 returns 1 if the item is safe to delete,
1759 "book_on_loan" if the item is checked out,
1761 "not_same_branch" if the item is blocked by independent branches,
1763 "book_reserved" if the there are holds aganst the item, or
1765 "linked_analytics" if the item has linked analytic records.
1769 sub ItemSafeToDelete {
1770 my ( $biblionumber, $itemnumber ) = @_;
1772 my $dbh = C4::Context->dbh;
1776 my $countanalytics = GetAnalyticsCount($itemnumber);
1778 # check that there is no issue on this item before deletion.
1779 my $sth = $dbh->prepare(
1781 SELECT COUNT(*) FROM issues
1782 WHERE itemnumber = ?
1785 $sth->execute($itemnumber);
1786 my ($onloan) = $sth->fetchrow;
1788 my $item = GetItem($itemnumber);
1791 $status = "book_on_loan";
1793 elsif ( defined C4::Context->userenv
1794 and !C4::Context->IsSuperLibrarian()
1795 and C4::Context->preference("IndependentBranches")
1796 and ( C4::Context->userenv->{branch} ne $item->{'homebranch'} ) )
1798 $status = "not_same_branch";
1801 # check it doesn't have a waiting reserve
1802 $sth = $dbh->prepare(
1804 SELECT COUNT(*) FROM reserves
1805 WHERE (found = 'W' OR found = 'T')
1809 $sth->execute($itemnumber);
1810 my ($reserve) = $sth->fetchrow;
1812 $status = "book_reserved";
1814 elsif ( $countanalytics > 0 ) {
1815 $status = "linked_analytics";
1826 DelItemCheck( $biblionumber, $itemnumber);
1828 Exported function (core API) for deleting an item record in Koha if there no current issue.
1830 DelItemCheck wraps ItemSafeToDelete around DelItem.
1835 my ( $biblionumber, $itemnumber ) = @_;
1836 my $status = ItemSafeToDelete( $biblionumber, $itemnumber );
1838 if ( $status == 1 ) {
1841 biblionumber => $biblionumber,
1842 itemnumber => $itemnumber
1849 =head2 _koha_modify_item
1851 my ($itemnumber,$error) =_koha_modify_item( $item );
1853 Perform the actual update of the C<items> row. Note that this
1854 routine accepts a hashref specifying the columns to update.
1858 sub _koha_modify_item {
1860 my $dbh=C4::Context->dbh;
1863 my $query = "UPDATE items SET ";
1865 _mod_item_dates( $item );
1866 for my $key ( keys %$item ) {
1867 next if ( $key eq 'itemnumber' );
1869 push @bind, $item->{$key};
1872 $query .= " WHERE itemnumber=?";
1873 push @bind, $item->{'itemnumber'};
1874 my $sth = $dbh->prepare($query);
1875 $sth->execute(@bind);
1877 $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
1880 return ($item->{'itemnumber'},$error);
1883 sub _mod_item_dates { # date formatting for date fields in item hash
1885 return if !$item || ref($item) ne 'HASH';
1888 { $_ =~ /^onloan$|^date|date$|datetime$/ }
1890 # Incl. dateaccessioned,replacementpricedate,datelastborrowed,datelastseen
1891 # NOTE: We do not (yet) have items fields ending with datetime
1892 # Fields with _on$ have been handled already
1894 foreach my $key ( @keys ) {
1895 next if !defined $item->{$key}; # skip undefs
1896 my $dt = eval { dt_from_string( $item->{$key} ) };
1897 # eval: dt_from_string will die on us if we pass illegal dates
1900 if( defined $dt && ref($dt) eq 'DateTime' ) {
1901 if( $key =~ /datetime/ ) {
1902 $newstr = DateTime::Format::MySQL->format_datetime($dt);
1904 $newstr = DateTime::Format::MySQL->format_date($dt);
1907 $item->{$key} = $newstr; # might be undef to clear garbage
1911 =head2 _koha_delete_item
1913 _koha_delete_item( $itemnum );
1915 Internal function to delete an item record from the koha tables
1919 sub _koha_delete_item {
1920 my ( $itemnum ) = @_;
1922 my $dbh = C4::Context->dbh;
1923 # save the deleted item to deleteditems table
1924 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1925 $sth->execute($itemnum);
1926 my $data = $sth->fetchrow_hashref();
1928 # There is no item to delete
1929 return 0 unless $data;
1931 my $query = "INSERT INTO deleteditems SET ";
1933 foreach my $key ( keys %$data ) {
1934 next if ( $key eq 'timestamp' ); # timestamp will be set by db
1935 $query .= "$key = ?,";
1936 push( @bind, $data->{$key} );
1939 $sth = $dbh->prepare($query);
1940 $sth->execute(@bind);
1942 # delete from items table
1943 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1944 my $deleted = $sth->execute($itemnum);
1945 return ( $deleted == 1 ) ? 1 : 0;
1948 =head2 _marc_from_item_hash
1950 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1952 Given an item hash representing a complete item record,
1953 create a C<MARC::Record> object containing an embedded
1954 tag representing that item.
1956 The third, optional parameter C<$unlinked_item_subfields> is
1957 an arrayref of subfields (not mapped to C<items> fields per the
1958 framework) to be added to the MARC representation
1963 sub _marc_from_item_hash {
1965 my $frameworkcode = shift;
1966 my $unlinked_item_subfields;
1968 $unlinked_item_subfields = shift;
1971 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1972 # Also, don't emit a subfield if the underlying field is blank.
1973 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1974 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1975 : () } keys %{ $item } };
1977 my $item_marc = MARC::Record->new();
1978 foreach my $item_field ( keys %{$mungeditem} ) {
1979 my ( $tag, $subfield ) = C4::Biblio::GetMarcFromKohaField( $item_field, $frameworkcode );
1980 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1981 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
1982 foreach my $value (@values){
1983 if ( my $field = $item_marc->field($tag) ) {
1984 $field->add_subfields( $subfield => $value );
1986 my $add_subfields = [];
1987 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1988 $add_subfields = $unlinked_item_subfields;
1990 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
1998 =head2 _repack_item_errors
2000 Add an error message hash generated by C<CheckItemPreSave>
2001 to a list of errors.
2005 sub _repack_item_errors {
2006 my $item_sequence_num = shift;
2007 my $item_ref = shift;
2008 my $error_ref = shift;
2010 my @repacked_errors = ();
2012 foreach my $error_code (sort keys %{ $error_ref }) {
2013 my $repacked_error = {};
2014 $repacked_error->{'item_sequence'} = $item_sequence_num;
2015 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2016 $repacked_error->{'error_code'} = $error_code;
2017 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2018 push @repacked_errors, $repacked_error;
2021 return @repacked_errors;
2024 =head2 _get_unlinked_item_subfields
2026 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2030 sub _get_unlinked_item_subfields {
2031 my $original_item_marc = shift;
2032 my $frameworkcode = shift;
2034 my $marcstructure = C4::Biblio::GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
2036 # assume that this record has only one field, and that that
2037 # field contains only the item information
2039 my @fields = $original_item_marc->fields();
2040 if ($#fields > -1) {
2041 my $field = $fields[0];
2042 my $tag = $field->tag();
2043 foreach my $subfield ($field->subfields()) {
2044 if (defined $subfield->[1] and
2045 $subfield->[1] ne '' and
2046 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2047 push @$subfields, $subfield->[0] => $subfield->[1];
2054 =head2 _get_unlinked_subfields_xml
2056 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2060 sub _get_unlinked_subfields_xml {
2061 my $unlinked_item_subfields = shift;
2064 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2065 my $marc = MARC::Record->new();
2066 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2067 # used in the framework
2068 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2069 $marc->encoding("UTF-8");
2070 $xml = $marc->as_xml("USMARC");
2076 =head2 _parse_unlinked_item_subfields_from_xml
2078 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2082 sub _parse_unlinked_item_subfields_from_xml {
2084 require C4::Charset;
2085 return unless defined $xml and $xml ne "";
2086 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2087 my $unlinked_subfields = [];
2088 my @fields = $marc->fields();
2089 if ($#fields > -1) {
2090 foreach my $subfield ($fields[0]->subfields()) {
2091 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2094 return $unlinked_subfields;
2097 =head2 GetAnalyticsCount
2099 $count= &GetAnalyticsCount($itemnumber)
2101 counts Usage of itemnumber in Analytical bibliorecords.
2105 sub GetAnalyticsCount {
2106 my ($itemnumber) = @_;
2108 ### ZOOM search here
2110 $query= "hi=".$itemnumber;
2111 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
2112 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
2116 =head2 SearchItemsByField
2118 my $items = SearchItemsByField($field, $value);
2120 SearchItemsByField will search for items on a specific given field.
2121 For instance you can search all items with a specific stocknumber like this:
2123 my $items = SearchItemsByField('stocknumber', $stocknumber);
2127 sub SearchItemsByField {
2128 my ($field, $value) = @_;
2135 my ($results) = SearchItems($filters);
2139 sub _SearchItems_build_where_fragment {
2142 my $dbh = C4::Context->dbh;
2145 if (exists($filter->{conjunction})) {
2146 my (@where_strs, @where_args);
2147 foreach my $f (@{ $filter->{filters} }) {
2148 my $fragment = _SearchItems_build_where_fragment($f);
2150 push @where_strs, $fragment->{str};
2151 push @where_args, @{ $fragment->{args} };
2156 $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
2159 args => \@where_args,
2163 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2164 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2165 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2166 my @operators = qw(= != > < >= <= like);
2167 my $field = $filter->{field};
2168 if ( (0 < grep /^$field$/, @columns) or (substr($field, 0, 5) eq 'marc:') ) {
2169 my $op = $filter->{operator};
2170 my $query = $filter->{query};
2172 if (!$op or (0 == grep /^$op$/, @operators)) {
2173 $op = '='; # default operator
2177 if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
2179 my $marcsubfield = $2;
2180 my ($kohafield) = $dbh->selectrow_array(q|
2181 SELECT kohafield FROM marc_subfield_structure
2182 WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
2183 |, undef, $marcfield, $marcsubfield);
2186 $column = $kohafield;
2188 # MARC field is not linked to a DB field so we need to use
2189 # ExtractValue on marcxml from biblio_metadata or
2190 # items.more_subfields_xml, depending on the MARC field.
2193 my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber');
2194 if ($marcfield eq $itemfield) {
2195 $sqlfield = 'more_subfields_xml';
2196 $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
2198 $sqlfield = 'metadata'; # From biblio_metadata
2199 if ($marcfield < 10) {
2200 $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
2202 $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
2205 $column = "ExtractValue($sqlfield, '$xpath')";
2211 if (ref $query eq 'ARRAY') {
2214 } elsif ($op eq '!=') {
2218 str => "$column $op (" . join (',', ('?') x @$query) . ")",
2223 str => "$column $op ?",
2230 return $where_fragment;
2235 my ($items, $total) = SearchItems($filter, $params);
2237 Perform a search among items
2239 $filter is a reference to a hash which can be a filter, or a combination of filters.
2241 A filter has the following keys:
2245 =item * field: the name of a SQL column in table items
2247 =item * query: the value to search in this column
2249 =item * operator: comparison operator. Can be one of = != > < >= <= like
2253 A combination of filters hash the following keys:
2257 =item * conjunction: 'AND' or 'OR'
2259 =item * filters: array ref of filters
2263 $params is a reference to a hash that can contain the following parameters:
2267 =item * rows: Number of items to return. 0 returns everything (default: 0)
2269 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2272 =item * sortby: A SQL column name in items table to sort on
2274 =item * sortorder: 'ASC' or 'DESC'
2281 my ($filter, $params) = @_;
2285 return unless ref $filter eq 'HASH';
2286 return unless ref $params eq 'HASH';
2288 # Default parameters
2289 $params->{rows} ||= 0;
2290 $params->{page} ||= 1;
2291 $params->{sortby} ||= 'itemnumber';
2292 $params->{sortorder} ||= 'ASC';
2294 my ($where_str, @where_args);
2295 my $where_fragment = _SearchItems_build_where_fragment($filter);
2296 if ($where_fragment) {
2297 $where_str = $where_fragment->{str};
2298 @where_args = @{ $where_fragment->{args} };
2301 my $dbh = C4::Context->dbh;
2303 SELECT SQL_CALC_FOUND_ROWS items.*
2305 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2306 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
2307 LEFT JOIN biblio_metadata ON biblio_metadata.biblionumber = biblio.biblionumber
2310 if (defined $where_str and $where_str ne '') {
2311 $query .= qq{ AND $where_str };
2314 $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.marcflavour = ? };
2315 push @where_args, C4::Context->preference('marcflavour');
2317 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
2318 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
2319 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
2320 my $sortby = (0 < grep {$params->{sortby} eq $_} @columns)
2321 ? $params->{sortby} : 'itemnumber';
2322 my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC';
2323 $query .= qq{ ORDER BY $sortby $sortorder };
2325 my $rows = $params->{rows};
2328 my $offset = $rows * ($params->{page}-1);
2329 $query .= qq { LIMIT ?, ? };
2330 push @limit_args, $offset, $rows;
2333 my $sth = $dbh->prepare($query);
2334 my $rv = $sth->execute(@where_args, @limit_args);
2336 return unless ($rv);
2337 my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2339 return ($sth->fetchall_arrayref({}), $total_rows);
2343 =head1 OTHER FUNCTIONS
2347 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2349 Find the given $subfield in the given $tag in the given
2350 MARC::Record $record. If the subfield is found, returns
2351 the (indicators, value) pair; otherwise, (undef, undef) is
2355 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2356 I suggest we export it from this module.
2361 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2364 if ( $tagfield < 10 ) {
2365 if ( $record->field($tagfield) ) {
2366 push @result, $record->field($tagfield)->data();
2371 foreach my $field ( $record->field($tagfield) ) {
2372 my @subfields = $field->subfields();
2373 foreach my $subfield (@subfields) {
2374 if ( @$subfield[0] eq $insubfield ) {
2375 push @result, @$subfield[1];
2376 $indicator = $field->indicator(1) . $field->indicator(2);
2381 return ( $indicator, @result );
2385 =head2 PrepareItemrecordDisplay
2387 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2389 Returns a hash with all the fields for Display a given item data in a template
2391 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2395 sub PrepareItemrecordDisplay {
2397 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2399 my $dbh = C4::Context->dbh;
2400 $frameworkcode = C4::Biblio::GetFrameworkCode($bibnum) if $bibnum;
2401 my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2403 # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
2404 # a shared data structure. No plugin (including custom ones) should change
2405 # its contents. See also GetMarcStructure.
2406 my $tagslib = GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } );
2408 # return nothing if we don't have found an existing framework.
2409 return q{} unless $tagslib;
2412 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2416 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
2418 SELECT authorised_value,lib FROM authorised_values
2421 LEFT JOIN authorised_values_branches ON ( id = av_id )
2426 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
2427 $query .= qq{ ORDER BY lib};
2428 my $authorised_values_sth = $dbh->prepare( $query );
2429 foreach my $tag ( sort keys %{$tagslib} ) {
2432 # loop through each subfield
2434 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2435 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
2436 next unless ( $tagslib->{$tag}->{$subfield}->{'tab'} );
2437 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2439 $subfield_data{tag} = $tag;
2440 $subfield_data{subfield} = $subfield;
2441 $subfield_data{countsubfield} = $cntsubf++;
2442 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2443 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2445 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2446 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2447 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2448 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2449 $subfield_data{hidden} = "display:none"
2450 if ( ( $tagslib->{$tag}->{$subfield}->{hidden} > 4 )
2451 || ( $tagslib->{$tag}->{$subfield}->{hidden} < -4 ) );
2452 my ( $x, $defaultvalue );
2454 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2456 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2457 if ( !defined $defaultvalue ) {
2458 $defaultvalue = q||;
2460 $defaultvalue =~ s/"/"/g;
2463 # search for itemcallnumber if applicable
2464 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2465 && C4::Context->preference('itemcallnumber') ) {
2466 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2467 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2468 if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2469 $defaultvalue = $field->subfield($CNsubfield);
2472 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2474 && $defaultvalues->{'callnumber'} ) {
2475 if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ){
2476 # if the item record exists, only use default value if the item has no callnumber
2477 $defaultvalue = $defaultvalues->{callnumber};
2478 } elsif ( !$itemrecord and $defaultvalues ) {
2479 # if the item record *doesn't* exists, always use the default value
2480 $defaultvalue = $defaultvalues->{callnumber};
2483 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2485 && $defaultvalues->{'branchcode'} ) {
2486 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2487 $defaultvalue = $defaultvalues->{branchcode};
2490 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2492 && $defaultvalues->{'location'} ) {
2494 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2495 # if the item record exists, only use default value if the item has no locationr
2496 $defaultvalue = $defaultvalues->{location};
2497 } elsif ( !$itemrecord and $defaultvalues ) {
2498 # if the item record *doesn't* exists, always use the default value
2499 $defaultvalue = $defaultvalues->{location};
2502 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2503 my @authorised_values;
2506 # builds list, depending on authorised value...
2508 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2509 if ( ( C4::Context->preference("IndependentBranches") )
2510 && !C4::Context->IsSuperLibrarian() ) {
2511 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2512 $sth->execute( C4::Context->userenv->{branch} );
2513 push @authorised_values, ""
2514 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2515 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2516 push @authorised_values, $branchcode;
2517 $authorised_lib{$branchcode} = $branchname;
2520 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2522 push @authorised_values, ""
2523 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2524 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2525 push @authorised_values, $branchcode;
2526 $authorised_lib{$branchcode} = $branchname;
2530 $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
2531 if ( $defaultvalues and $defaultvalues->{branchcode} ) {
2532 $defaultvalue = $defaultvalues->{branchcode};
2536 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2537 my $itemtypes = Koha::ItemTypes->search_with_localization;
2538 push @authorised_values, ""
2539 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2540 while ( my $itemtype = $itemtypes->next ) {
2541 push @authorised_values, $itemtype->itemtype;
2542 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
2544 if ($defaultvalues && $defaultvalues->{'itemtype'}) {
2545 $defaultvalue = $defaultvalues->{'itemtype'};
2549 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2550 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2552 my $class_sources = GetClassSources();
2553 my $default_source = C4::Context->preference("DefaultClassificationSource");
2555 foreach my $class_source (sort keys %$class_sources) {
2556 next unless $class_sources->{$class_source}->{'used'} or
2557 ($class_source eq $default_source);
2558 push @authorised_values, $class_source;
2559 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2562 $defaultvalue = $default_source;
2564 #---- "true" authorised value
2566 $authorised_values_sth->execute(
2567 $tagslib->{$tag}->{$subfield}->{authorised_value},
2568 $branch_limit ? $branch_limit : ()
2570 push @authorised_values, ""
2571 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2572 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2573 push @authorised_values, $value;
2574 $authorised_lib{$value} = $lib;
2577 $subfield_data{marc_value} = {
2579 values => \@authorised_values,
2580 default => "$defaultvalue",
2581 labels => \%authorised_lib,
2583 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2585 require Koha::FrameworkPlugin;
2586 my $plugin = Koha::FrameworkPlugin->new({
2587 name => $tagslib->{$tag}->{$subfield}->{value_builder},
2590 my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id}, tabloop => undef };
2591 $plugin->build( $pars );
2592 if ( $itemrecord and my $field = $itemrecord->field($tag) ) {
2593 $defaultvalue = $field->subfield($subfield);
2595 if( !$plugin->errstr ) {
2596 #TODO Move html to template; see report 12176/13397
2597 my $tab= $plugin->noclick? '-1': '';
2598 my $class= $plugin->noclick? ' disabled': '';
2599 my $title= $plugin->noclick? 'No popup': 'Tag editor';
2600 $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" /><a href="#" id="buttonDot_$subfield_data{id}" tabindex="$tab" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
2602 warn $plugin->errstr;
2603 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />); # supply default input form
2606 elsif ( $tag eq '' ) { # it's an hidden field
2607 $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" />);
2609 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2610 $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255" value="$defaultvalue" />);
2612 elsif ( length($defaultvalue) > 100
2613 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2614 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2615 or (C4::Context->preference("marcflavour") eq "MARC21" and
2616 500 <= $tag && $tag < 600 )
2618 # oversize field (textarea)
2619 $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="255">$defaultvalue</textarea>\n");
2621 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2623 push( @loop_data, \%subfield_data );
2628 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2629 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2632 'itemtagfield' => $itemtagfield,
2633 'itemtagsubfield' => $itemtagsubfield,
2634 'itemnumber' => $itemnumber,
2635 'iteminformation' => \@loop_data
2639 sub ToggleNewStatus {
2640 my ( $params ) = @_;
2641 my @rules = @{ $params->{rules} };
2642 my $report_only = $params->{report_only};
2644 my $dbh = C4::Context->dbh;
2646 my @item_columns = map { "items.$_" } Koha::Items->columns;
2647 my @biblioitem_columns = map { "biblioitems.$_" } Koha::Biblioitems->columns;
2649 for my $rule ( @rules ) {
2650 my $age = $rule->{age};
2651 my $conditions = $rule->{conditions};
2652 my $substitutions = $rule->{substitutions};
2656 SELECT items.biblionumber, items.itemnumber
2658 LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
2661 for my $condition ( @$conditions ) {
2663 grep {/^$condition->{field}$/} @item_columns
2664 or grep {/^$condition->{field}$/} @biblioitem_columns
2666 if ( $condition->{value} =~ /\|/ ) {
2667 my @values = split /\|/, $condition->{value};
2668 $query .= qq| AND $condition->{field} IN (|
2669 . join( ',', ('?') x scalar @values )
2671 push @params, @values;
2673 $query .= qq| AND $condition->{field} = ?|;
2674 push @params, $condition->{value};
2678 if ( defined $age ) {
2679 $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
2682 my $sth = $dbh->prepare($query);
2683 $sth->execute( @params );
2684 while ( my $values = $sth->fetchrow_hashref ) {
2685 my $biblionumber = $values->{biblionumber};
2686 my $itemnumber = $values->{itemnumber};
2687 my $item = C4::Items::GetItem( $itemnumber );
2688 for my $substitution ( @$substitutions ) {
2689 next unless $substitution->{field};
2690 C4::Items::ModItem( {$substitution->{field} => $substitution->{value}}, $biblionumber, $itemnumber )
2691 unless $report_only;
2692 push @{ $report->{$itemnumber} }, $substitution;