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
32 use List
::MoreUtils qw
/any/;
34 use DateTime
::Format
::MySQL
;
35 use Data
::Dumper
; # used as part of logging item record changes, not just for
36 # debugging; so please don't remove this
37 use Koha
::DateUtils qw
/dt_from_string/;
41 use Koha
::SearchEngine
;
42 use Koha
::SearchEngine
::Search
;
44 use vars
qw(@ISA @EXPORT);
49 @ISA = qw( Exporter );
72 GetItemsByBiblioitemnumber
76 GetItemnumbersForBiblio
78 get_hostitemnumbers_of
79 GetItemnumberFromBarcode
80 GetBarcodeFromItemnumber
95 PrepareItemrecordDisplay
102 C4::Items - item management functions
106 This module contains an API for manipulating item
107 records in Koha, and is used by cataloguing, circulation,
108 acquisitions, and serials management.
110 A Koha item record is stored in two places: the
111 items table and embedded in a MARC tag in the XML
112 version of the associated bib record in C<biblioitems.marcxml>.
113 This is done to allow the item information to be readily
114 indexed (e.g., by Zebra), but means that each item
115 modification transaction must keep the items table
116 and the MARC XML in sync at all times.
118 Consequently, all code that creates, modifies, or deletes
119 item records B<must> use an appropriate function from
120 C<C4::Items>. If no existing function is suitable, it is
121 better to add one to C<C4::Items> than to use add
122 one-off SQL statements to add or modify items.
124 The items table will be considered authoritative. In other
125 words, if there is ever a discrepancy between the items
126 table and the MARC XML, the items table should be considered
129 =head1 HISTORICAL NOTE
131 Most of the functions in C<C4::Items> were originally in
132 the C<C4::Biblio> module.
134 =head1 CORE EXPORTED FUNCTIONS
136 The following functions are meant for use by users
143 $item = GetItem($itemnumber,$barcode,$serial);
145 Return item information, for a given itemnumber or barcode.
146 The return value is a hashref mapping item column
147 names to values. If C<$serial> is true, include serial publication data.
152 my ($itemnumber,$barcode, $serial) = @_;
153 my $dbh = C4
::Context
->dbh;
157 my $sth = $dbh->prepare("
159 WHERE itemnumber = ?");
160 $sth->execute($itemnumber);
161 $data = $sth->fetchrow_hashref;
163 my $sth = $dbh->prepare("
167 $sth->execute($barcode);
168 $data = $sth->fetchrow_hashref;
171 return unless ( $data );
174 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
175 $ssth->execute($data->{'itemnumber'}) ;
176 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
178 #if we don't have an items.itype, use biblioitems.itemtype.
179 # FIXME this should respect the itypes systempreference
180 # if (C4::Context->preference('item-level_itypes')) {
181 if( ! $data->{'itype'} ) {
182 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
183 $sth->execute($data->{'biblionumber'});
184 ($data->{'itype'}) = $sth->fetchrow_array;
191 CartToShelf($itemnumber);
193 Set the current shelving location of the item record
194 to its stored permanent shelving location. This is
195 primarily used to indicate when an item whose current
196 location is a special processing ('PROC') or shelving cart
197 ('CART') location is back in the stacks.
202 my ( $itemnumber ) = @_;
204 unless ( $itemnumber ) {
205 croak
"FAILED CartToShelf() - no itemnumber supplied";
208 my $item = GetItem
($itemnumber);
209 if ( $item->{location
} eq 'CART' ) {
210 $item->{location
} = $item->{permanent_location
};
211 ModItem
($item, undef, $itemnumber);
217 ShelfToCart($itemnumber);
219 Set the current shelving location of the item
220 to shelving cart ('CART').
225 my ( $itemnumber ) = @_;
227 unless ( $itemnumber ) {
228 croak
"FAILED ShelfToCart() - no itemnumber supplied";
231 my $item = GetItem
($itemnumber);
232 $item->{'location'} = 'CART';
233 ModItem
($item, undef, $itemnumber);
236 =head2 AddItemFromMarc
238 my ($biblionumber, $biblioitemnumber, $itemnumber)
239 = AddItemFromMarc($source_item_marc, $biblionumber);
241 Given a MARC::Record object containing an embedded item
242 record and a biblionumber, create a new item record.
246 sub AddItemFromMarc
{
247 my ( $source_item_marc, $biblionumber ) = @_;
248 my $dbh = C4
::Context
->dbh;
250 # parse item hash from MARC
251 my $frameworkcode = C4
::Biblio
::GetFrameworkCode
( $biblionumber );
252 my ($itemtag,$itemsubfield)=C4
::Biblio
::GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
256 my $localitemmarc=MARC
::Record
->new;
257 $localitemmarc->append_fields($source_item_marc->field($itemtag));
258 my $item = &TransformMarcToKoha
( $localitemmarc, $frameworkcode ,'items');
259 my $unlinked_item_subfields = _get_unlinked_item_subfields
($localitemmarc, $frameworkcode);
260 return AddItem
($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
265 my ($biblionumber, $biblioitemnumber, $itemnumber)
266 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
268 Given a hash containing item column names as keys,
269 create a new Koha item record.
271 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
272 do not need to be supplied for general use; they exist
273 simply to allow them to be picked up from AddItemFromMarc.
275 The final optional parameter, C<$unlinked_item_subfields>, contains
276 an arrayref containing subfields present in the original MARC
277 representation of the item (e.g., from the item editor) that are
278 not mapped to C<items> columns directly but should instead
279 be stored in C<items.more_subfields_xml> and included in
280 the biblio items tag for display and indexing.
286 my $biblionumber = shift;
288 my $dbh = @_ ?
shift : C4
::Context
->dbh;
289 my $frameworkcode = @_ ?
shift : C4
::Biblio
::GetFrameworkCode
($biblionumber);
291 my $unlinked_item_subfields;
293 $unlinked_item_subfields = shift;
296 # needs old biblionumber and biblioitemnumber
297 $item->{'biblionumber'} = $biblionumber;
298 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
299 $sth->execute( $item->{'biblionumber'} );
300 ( $item->{'biblioitemnumber'} ) = $sth->fetchrow;
302 _set_defaults_for_add
($item);
303 _set_derived_columns_for_add
($item);
304 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
306 # FIXME - checks here
307 unless ( $item->{itype
} ) { # default to biblioitem.itemtype if no itype
308 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
309 $itype_sth->execute( $item->{'biblionumber'} );
310 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
313 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
316 $item->{'itemnumber'} = $itemnumber;
318 ModZebra
( $item->{biblionumber
}, "specialUpdate", "biblioserver" );
320 logaction
( "CATALOGUING", "ADD", $itemnumber, "item" )
321 if C4
::Context
->preference("CataloguingLog");
323 return ( $item->{biblionumber
}, $item->{biblioitemnumber
}, $itemnumber );
326 =head2 AddItemBatchFromMarc
328 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
329 $biblionumber, $biblioitemnumber, $frameworkcode);
331 Efficiently create item records from a MARC biblio record with
332 embedded item fields. This routine is suitable for batch jobs.
334 This API assumes that the bib record has already been
335 saved to the C<biblio> and C<biblioitems> tables. It does
336 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
337 are populated, but it will do so via a call to ModBibiloMarc.
339 The goal of this API is to have a similar effect to using AddBiblio
340 and AddItems in succession, but without inefficient repeated
341 parsing of the MARC XML bib record.
343 This function returns an arrayref of new itemsnumbers and an arrayref of item
344 errors encountered during the processing. Each entry in the errors
345 list is a hashref containing the following keys:
351 Sequence number of original item tag in the MARC record.
355 Item barcode, provide to assist in the construction of
356 useful error messages.
360 Code representing the error condition. Can be 'duplicate_barcode',
361 'invalid_homebranch', or 'invalid_holdingbranch'.
363 =item error_information
365 Additional information appropriate to the error condition.
371 sub AddItemBatchFromMarc
{
372 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
374 my @itemnumbers = ();
376 my $dbh = C4
::Context
->dbh;
378 # We modify the record, so lets work on a clone so we don't change the
380 $record = $record->clone();
381 # loop through the item tags and start creating items
382 my @bad_item_fields = ();
383 my ($itemtag, $itemsubfield) = C4
::Biblio
::GetMarcFromKohaField
("items.itemnumber",'');
385 my $item_sequence_num = 0;
386 ITEMFIELD
: foreach my $item_field ($record->field($itemtag)) {
387 $item_sequence_num++;
388 # we take the item field and stick it into a new
389 # MARC record -- this is required so far because (FIXME)
390 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
391 # and there is no TransformMarcFieldToKoha
392 my $temp_item_marc = MARC
::Record
->new();
393 $temp_item_marc->append_fields($item_field);
395 # add biblionumber and biblioitemnumber
396 my $item = TransformMarcToKoha
( $temp_item_marc, $frameworkcode, 'items' );
397 my $unlinked_item_subfields = _get_unlinked_item_subfields
($temp_item_marc, $frameworkcode);
398 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
399 $item->{'biblionumber'} = $biblionumber;
400 $item->{'biblioitemnumber'} = $biblioitemnumber;
402 # check for duplicate barcode
403 my %item_errors = CheckItemPreSave
($item);
405 push @errors, _repack_item_errors
($item_sequence_num, $item, \
%item_errors);
406 push @bad_item_fields, $item_field;
410 _set_defaults_for_add
($item);
411 _set_derived_columns_for_add
($item);
412 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
413 warn $error if $error;
414 push @itemnumbers, $itemnumber; # FIXME not checking error
415 $item->{'itemnumber'} = $itemnumber;
417 logaction
("CATALOGUING", "ADD", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
419 my $new_item_marc = _marc_from_item_hash
($item, $frameworkcode, $unlinked_item_subfields);
420 $item_field->replace_with($new_item_marc->field($itemtag));
423 # remove any MARC item fields for rejected items
424 foreach my $item_field (@bad_item_fields) {
425 $record->delete_field($item_field);
428 # update the MARC biblio
429 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
431 return (\
@itemnumbers, \
@errors);
434 =head2 ModItemFromMarc
436 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
438 This function updates an item record based on a supplied
439 C<MARC::Record> object containing an embedded item field.
440 This API is meant for the use of C<additem.pl>; for
441 other purposes, C<ModItem> should be used.
443 This function uses the hash %default_values_for_mod_from_marc,
444 which contains default values for item fields to
445 apply when modifying an item. This is needed because
446 if an item field's value is cleared, TransformMarcToKoha
447 does not include the column in the
448 hash that's passed to ModItem, which without
449 use of this hash makes it impossible to clear
450 an item field's value. See bug 2466.
452 Note that only columns that can be directly
453 changed from the cataloging and serials
454 item editors are included in this hash.
460 sub _build_default_values_for_mod_marc
{
461 my ($frameworkcode) = @_;
463 my $cache = Koha
::Cache
->get_instance();
464 my $cache_key = "default_value_for_mod_marc-$frameworkcode";
465 my $cached = $cache->get_from_cache($cache_key);
466 return $cached if $cached;
468 my $default_values = {
470 booksellerid
=> undef,
472 'items.cn_source' => undef,
473 coded_location_qualifier
=> undef,
477 holdingbranch
=> undef,
479 itemcallnumber
=> undef,
482 itemnotes_nonpublic
=> undef,
485 permanent_location
=> undef,
489 # paidfor => undef, # commented, see bug 12817
491 replacementprice
=> undef,
492 replacementpricedate
=> undef,
495 stocknumber
=> undef,
499 my %default_values_for_mod_from_marc;
500 while ( my ( $field, $default_value ) = each %$default_values ) {
501 my $kohafield = $field;
502 $kohafield =~ s
|^([^\
.]+)$|items
.$1|;
503 $default_values_for_mod_from_marc{$field} =
505 if C4
::Koha
::IsKohaFieldLinked
(
506 { kohafield
=> $kohafield, frameworkcode
=> $frameworkcode } );
509 $cache->set_in_cache($cache_key, \
%default_values_for_mod_from_marc);
510 return \
%default_values_for_mod_from_marc;
513 sub ModItemFromMarc
{
514 my $item_marc = shift;
515 my $biblionumber = shift;
516 my $itemnumber = shift;
518 my $dbh = C4
::Context
->dbh;
519 my $frameworkcode = C4
::Biblio
::GetFrameworkCode
($biblionumber);
520 my ( $itemtag, $itemsubfield ) = C4
::Biblio
::GetMarcFromKohaField
( "items.itemnumber", $frameworkcode );
522 my $localitemmarc = MARC
::Record
->new;
523 $localitemmarc->append_fields( $item_marc->field($itemtag) );
524 my $item = &TransformMarcToKoha
( $localitemmarc, $frameworkcode, 'items' );
525 my $default_values = _build_default_values_for_mod_marc
($frameworkcode);
526 foreach my $item_field ( keys %$default_values ) {
527 $item->{$item_field} = $default_values->{$item_field}
528 unless exists $item->{$item_field};
530 my $unlinked_item_subfields = _get_unlinked_item_subfields
( $localitemmarc, $frameworkcode );
532 ModItem
($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
538 ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
540 Change one or more columns in an item record and update
541 the MARC representation of the item.
543 The first argument is a hashref mapping from item column
544 names to the new values. The second and third arguments
545 are the biblionumber and itemnumber, respectively.
547 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
548 an arrayref containing subfields present in the original MARC
549 representation of the item (e.g., from the item editor) that are
550 not mapped to C<items> columns directly but should instead
551 be stored in C<items.more_subfields_xml> and included in
552 the biblio items tag for display and indexing.
554 If one of the changed columns is used to calculate
555 the derived value of a column such as C<items.cn_sort>,
556 this routine will perform the necessary calculation
563 my $biblionumber = shift;
564 my $itemnumber = shift;
566 # if $biblionumber is undefined, get it from the current item
567 unless (defined $biblionumber) {
568 $biblionumber = _get_single_item_column
('biblionumber', $itemnumber);
571 my $dbh = @_ ?
shift : C4
::Context
->dbh;
572 my $frameworkcode = @_ ?
shift : C4
::Biblio
::GetFrameworkCode
( $biblionumber );
575 my $unlinked_item_subfields;
577 $unlinked_item_subfields = shift;
578 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
581 $item->{'itemnumber'} = $itemnumber or return;
583 my @fields = qw( itemlost withdrawn );
585 # Only call GetItem if we need to set an "on" date field
586 if ( $item->{itemlost
} || $item->{withdrawn
} ) {
587 my $pre_mod_item = GetItem
( $item->{'itemnumber'} );
588 for my $field (@fields) {
589 if ( defined( $item->{$field} )
590 and not $pre_mod_item->{$field}
591 and $item->{$field} )
593 $item->{ $field . '_on' } =
594 DateTime
::Format
::MySQL
->format_datetime( dt_from_string
() );
599 # If the field is defined but empty, we are removing and,
600 # and thus need to clear out the 'on' field as well
601 for my $field (@fields) {
602 if ( defined( $item->{$field} ) && !$item->{$field} ) {
603 $item->{ $field . '_on' } = undef;
608 _set_derived_columns_for_mod
($item);
609 _do_column_fixes_for_mod
($item);
612 # attempt to change itemnumber
613 # attempt to change biblionumber (if we want
614 # an API to relink an item to a different bib,
615 # it should be a separate function)
618 _koha_modify_item
($item);
620 # request that bib be reindexed so that searching on current
621 # item status is possible
622 ModZebra
( $biblionumber, "specialUpdate", "biblioserver" );
624 logaction
("CATALOGUING", "MODIFY", $itemnumber, "item ".Dumper
($item)) if C4
::Context
->preference("CataloguingLog");
627 =head2 ModItemTransfer
629 ModItemTransfer($itenumber, $frombranch, $tobranch);
631 Marks an item as being transferred from one branch
636 sub ModItemTransfer
{
637 my ( $itemnumber, $frombranch, $tobranch ) = @_;
639 my $dbh = C4
::Context
->dbh;
641 # Remove the 'shelving cart' location status if it is being used.
642 CartToShelf
( $itemnumber ) if ( C4
::Context
->preference("ReturnToShelvingCart") );
644 #new entry in branchtransfers....
645 my $sth = $dbh->prepare(
646 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
647 VALUES (?, ?, NOW(), ?)");
648 $sth->execute($itemnumber, $frombranch, $tobranch);
650 ModItem
({ holdingbranch
=> $tobranch }, undef, $itemnumber);
651 ModDateLastSeen
($itemnumber);
655 =head2 ModDateLastSeen
657 ModDateLastSeen($itemnum);
659 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
660 C<$itemnum> is the item number
664 sub ModDateLastSeen
{
665 my ($itemnumber) = @_;
667 my $today = output_pref
({ dt
=> dt_from_string
, dateformat
=> 'iso', dateonly
=> 1 });
668 ModItem
({ itemlost
=> 0, datelastseen
=> $today }, undef, $itemnumber);
673 DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
675 Exported function (core API) for deleting an item record in Koha.
682 my $itemnumber = $params->{itemnumber
};
683 my $biblionumber = $params->{biblionumber
};
685 unless ($biblionumber) {
686 $biblionumber = C4
::Biblio
::GetBiblionumberFromItemnumber
($itemnumber);
689 # If there is no biblionumber for the given itemnumber, there is nothing to delete
690 return 0 unless $biblionumber;
692 # FIXME check the item has no current issues
693 my $deleted = _koha_delete_item
( $itemnumber );
695 # get the MARC record
696 my $record = C4
::Biblio
::GetMarcBiblio
($biblionumber);
697 ModZebra
( $biblionumber, "specialUpdate", "biblioserver" );
699 #search item field code
700 logaction
("CATALOGUING", "DELETE", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
704 =head2 CheckItemPreSave
706 my $item_ref = TransformMarcToKoha($marc, 'items');
708 my %errors = CheckItemPreSave($item_ref);
709 if (exists $errors{'duplicate_barcode'}) {
710 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
711 } elsif (exists $errors{'invalid_homebranch'}) {
712 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
713 } elsif (exists $errors{'invalid_holdingbranch'}) {
714 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
719 Given a hashref containing item fields, determine if it can be
720 inserted or updated in the database. Specifically, checks for
721 database integrity issues, and returns a hash containing any
722 of the following keys, if applicable.
726 =item duplicate_barcode
728 Barcode, if it duplicates one already found in the database.
730 =item invalid_homebranch
732 Home branch, if not defined in branches table.
734 =item invalid_holdingbranch
736 Holding branch, if not defined in branches table.
740 This function does NOT implement any policy-related checks,
741 e.g., whether current operator is allowed to save an
742 item that has a given branch code.
746 sub CheckItemPreSave
{
747 my $item_ref = shift;
752 # check for duplicate barcode
753 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
754 my $existing_itemnumber = GetItemnumberFromBarcode
($item_ref->{'barcode'});
755 if ($existing_itemnumber) {
756 if (!exists $item_ref->{'itemnumber'} # new item
757 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
758 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
763 # check for valid home branch
764 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
765 my $branch_name = C4
::Branch
::GetBranchName
($item_ref->{'homebranch'});
766 unless (defined $branch_name) {
767 # relies on fact that branches.branchname is a non-NULL column,
768 # so GetBranchName returns undef only if branch does not exist
769 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
773 # check for valid holding branch
774 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
775 my $branch_name = C4
::Branch
::GetBranchName
($item_ref->{'holdingbranch'});
776 unless (defined $branch_name) {
777 # relies on fact that branches.branchname is a non-NULL column,
778 # so GetBranchName returns undef only if branch does not exist
779 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
787 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
789 The following functions provide various ways of
790 getting an item record, a set of item records, or
791 lists of authorized values for certain item fields.
793 Some of the functions in this group are candidates
794 for refactoring -- for example, some of the code
795 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
796 has copy-and-paste work.
802 $itemstatushash = GetItemStatus($fwkcode);
804 Returns a list of valid values for the
805 C<items.notforloan> field.
807 NOTE: does B<not> return an individual item's
810 Can be MARC dependent.
812 But basically could be can be loan or not
813 Create a status selector with the following code
815 =head3 in PERL SCRIPT
817 my $itemstatushash = getitemstatus;
819 foreach my $thisstatus (keys %$itemstatushash) {
820 my %row =(value => $thisstatus,
821 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
823 push @itemstatusloop, \%row;
825 $template->param(statusloop=>\@itemstatusloop);
829 <select name="statusloop" id="statusloop">
830 <option value="">Default</option>
831 [% FOREACH statusloo IN statusloop %]
832 [% IF ( statusloo.selected ) %]
833 <option value="[% statusloo.value %]" selected="selected">[% statusloo.statusname %]</option>
835 <option value="[% statusloo.value %]">[% statusloo.statusname %]</option>
844 # returns a reference to a hash of references to status...
847 my $dbh = C4
::Context
->dbh;
849 $fwk = '' unless ($fwk);
850 my ( $tag, $subfield ) =
851 GetMarcFromKohaField
( "items.notforloan", $fwk );
852 if ( $tag and $subfield ) {
855 "SELECT authorised_value
856 FROM marc_subfield_structure
862 $sth->execute( $tag, $subfield, $fwk );
863 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
866 "SELECT authorised_value,lib
867 FROM authorised_values
872 $authvalsth->execute($authorisedvaluecat);
873 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
874 $itemstatus{$authorisedvalue} = $lib;
887 $itemstatus{"1"} = "Not For Loan";
891 =head2 GetItemLocation
893 $itemlochash = GetItemLocation($fwk);
895 Returns a list of valid values for the
896 C<items.location> field.
898 NOTE: does B<not> return an individual item's
901 where fwk stands for an optional framework code.
902 Create a location selector with the following code
904 =head3 in PERL SCRIPT
906 my $itemlochash = getitemlocation;
908 foreach my $thisloc (keys %$itemlochash) {
909 my $selected = 1 if $thisbranch eq $branch;
910 my %row =(locval => $thisloc,
911 selected => $selected,
912 locname => $itemlochash->{$thisloc},
914 push @itemlocloop, \%row;
916 $template->param(itemlocationloop => \@itemlocloop);
920 <select name="location">
921 <option value="">Default</option>
922 <!-- TMPL_LOOP name="itemlocationloop" -->
923 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
929 sub GetItemLocation
{
931 # returns a reference to a hash of references to location...
934 my $dbh = C4
::Context
->dbh;
936 $fwk = '' unless ($fwk);
937 my ( $tag, $subfield ) =
938 GetMarcFromKohaField
( "items.location", $fwk );
939 if ( $tag and $subfield ) {
942 "SELECT authorised_value
943 FROM marc_subfield_structure
948 $sth->execute( $tag, $subfield, $fwk );
949 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
952 "SELECT authorised_value,lib
953 FROM authorised_values
957 $authvalsth->execute($authorisedvaluecat);
958 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
959 $itemlocation{$authorisedvalue} = $lib;
961 return \
%itemlocation;
972 $itemlocation{"1"} = "Not For Loan";
973 return \
%itemlocation;
978 $items = GetLostItems( $where );
980 This function gets a list of lost items.
986 C<$where> is a hashref. it containts a field of the items table as key
987 and the value to match as value. For example:
989 { barcode => 'abc123',
990 homebranch => 'CPL', }
994 C<$items> is a reference to an array full of hashrefs with columns
995 from the "items" table as keys.
997 =item usage in the perl script:
999 my $where = { barcode => '0001548' };
1000 my $items = GetLostItems( $where );
1001 $template->param( itemsloop => $items );
1008 # Getting input args.
1010 my $dbh = C4
::Context
->dbh;
1013 SELECT title, author, lib, itemlost, authorised_value, barcode, datelastseen, price, replacementprice, homebranch,
1014 itype, itemtype, holdingbranch, location, itemnotes, items.biblionumber as biblionumber, itemcallnumber
1016 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
1017 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
1018 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
1020 authorised_values.category = 'LOST'
1021 AND itemlost IS NOT NULL
1024 my @query_parameters;
1025 foreach my $key (keys %$where) {
1026 $query .= " AND $key LIKE ?";
1027 push @query_parameters, "%$where->{$key}%";
1030 my $sth = $dbh->prepare($query);
1031 $sth->execute( @query_parameters );
1033 while ( my $row = $sth->fetchrow_hashref ){
1039 =head2 GetItemsForInventory
1041 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
1042 minlocation => $minlocation,
1043 maxlocation => $maxlocation,
1044 location => $location,
1045 itemtype => $itemtype,
1046 ignoreissued => $ignoreissued,
1047 datelastseen => $datelastseen,
1048 branchcode => $branchcode,
1052 statushash => $statushash,
1053 interface => $interface,
1056 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1058 The sub returns a reference to a list of hashes, each containing
1059 itemnumber, author, title, barcode, item callnumber, and date last
1060 seen. It is ordered by callnumber then title.
1062 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1063 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1064 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1065 $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.
1067 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
1071 sub GetItemsForInventory
{
1072 my ( $parameters ) = @_;
1073 my $minlocation = $parameters->{'minlocation'} // '';
1074 my $maxlocation = $parameters->{'maxlocation'} // '';
1075 my $location = $parameters->{'location'} // '';
1076 my $itemtype = $parameters->{'itemtype'} // '';
1077 my $ignoreissued = $parameters->{'ignoreissued'} // '';
1078 my $datelastseen = $parameters->{'datelastseen'} // '';
1079 my $branchcode = $parameters->{'branchcode'} // '';
1080 my $branch = $parameters->{'branch'} // '';
1081 my $offset = $parameters->{'offset'} // '';
1082 my $size = $parameters->{'size'} // '';
1083 my $statushash = $parameters->{'statushash'} // '';
1084 my $interface = $parameters->{'interface'} // '';
1086 my $dbh = C4
::Context
->dbh;
1087 my ( @bind_params, @where_strings );
1089 my $select_columns = q{
1090 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
1092 my $select_count = q{SELECT COUNT(*)};
1095 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1096 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1099 for my $authvfield (keys %$statushash){
1100 if ( scalar @
{$statushash->{$authvfield}} > 0 ){
1101 my $joinedvals = join ',', @
{$statushash->{$authvfield}};
1102 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1108 push @where_strings, 'itemcallnumber >= ?';
1109 push @bind_params, $minlocation;
1113 push @where_strings, 'itemcallnumber <= ?';
1114 push @bind_params, $maxlocation;
1117 if ($datelastseen) {
1118 $datelastseen = output_pref
({ str
=> $datelastseen, dateformat
=> 'iso', dateonly
=> 1 });
1119 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1120 push @bind_params, $datelastseen;
1124 push @where_strings, 'items.location = ?';
1125 push @bind_params, $location;
1128 if ( $branchcode ) {
1129 if($branch eq "homebranch"){
1130 push @where_strings, 'items.homebranch = ?';
1132 push @where_strings, 'items.holdingbranch = ?';
1134 push @bind_params, $branchcode;
1138 push @where_strings, 'biblioitems.itemtype = ?';
1139 push @bind_params, $itemtype;
1142 if ( $ignoreissued) {
1143 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1144 push @where_strings, 'issues.date_due IS NULL';
1147 if ( @where_strings ) {
1149 $query .= join ' AND ', @where_strings;
1151 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1152 my $count_query = $select_count . $query;
1153 $query .= " LIMIT $offset, $size" if ($offset and $size);
1154 $query = $select_columns . $query;
1155 my $sth = $dbh->prepare($query);
1156 $sth->execute( @bind_params );
1159 my $tmpresults = $sth->fetchall_arrayref({});
1160 $sth = $dbh->prepare( $count_query );
1161 $sth->execute( @bind_params );
1162 my ($iTotalRecords) = $sth->fetchrow_array();
1164 my $avmapping = C4
::Koha
::GetKohaAuthorisedValuesMapping
( {
1165 interface
=> $interface
1167 foreach my $row (@
$tmpresults) {
1170 foreach (keys %$row) {
1171 if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
1172 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
1175 push @results, $row;
1178 return (\
@results, $iTotalRecords);
1181 =head2 GetItemsCount
1183 $count = &GetItemsCount( $biblionumber);
1185 This function return count of item with $biblionumber
1190 my ( $biblionumber ) = @_;
1191 my $dbh = C4
::Context
->dbh;
1192 my $query = "SELECT count(*)
1194 WHERE biblionumber=?";
1195 my $sth = $dbh->prepare($query);
1196 $sth->execute($biblionumber);
1197 my $count = $sth->fetchrow;
1201 =head2 GetItemInfosOf
1203 GetItemInfosOf(@itemnumbers);
1207 sub GetItemInfosOf
{
1208 my @itemnumbers = @_;
1210 my $itemnumber_values = @itemnumbers ?
join( ',', @itemnumbers ) : "''";
1215 WHERE itemnumber IN ($itemnumber_values)
1217 return get_infos_of
( $query, 'itemnumber' );
1220 =head2 GetItemsByBiblioitemnumber
1222 GetItemsByBiblioitemnumber($biblioitemnumber);
1224 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1225 Called by C<C4::XISBN>
1229 sub GetItemsByBiblioitemnumber
{
1230 my ( $bibitem ) = @_;
1231 my $dbh = C4
::Context
->dbh;
1232 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1233 # Get all items attached to a biblioitem
1236 $sth->execute($bibitem) || die $sth->errstr;
1237 while ( my $data = $sth->fetchrow_hashref ) {
1238 # Foreach item, get circulation information
1239 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1240 WHERE itemnumber = ?
1241 AND issues.borrowernumber = borrowers.borrowernumber"
1243 $sth2->execute( $data->{'itemnumber'} );
1244 if ( my $data2 = $sth2->fetchrow_hashref ) {
1245 # if item is out, set the due date and who it is out too
1246 $data->{'date_due'} = $data2->{'date_due'};
1247 $data->{'cardnumber'} = $data2->{'cardnumber'};
1248 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1251 # set date_due to blank, so in the template we check itemlost, and withdrawn
1252 $data->{'date_due'} = '';
1254 # Find the last 3 people who borrowed this item.
1255 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1256 AND old_issues.borrowernumber = borrowers.borrowernumber
1257 ORDER BY returndate desc,timestamp desc LIMIT 3";
1258 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1259 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1261 while ( my $data2 = $sth2->fetchrow_hashref ) {
1262 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1263 $data->{"card$i2"} = $data2->{'cardnumber'};
1264 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1267 push(@results,$data);
1274 @results = GetItemsInfo($biblionumber);
1276 Returns information about items with the given biblionumber.
1278 C<GetItemsInfo> returns a list of references-to-hash. Each element
1279 contains a number of keys. Most of them are attributes from the
1280 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1281 Koha database. Other keys include:
1285 =item C<$data-E<gt>{branchname}>
1287 The name (not the code) of the branch to which the book belongs.
1289 =item C<$data-E<gt>{datelastseen}>
1291 This is simply C<items.datelastseen>, except that while the date is
1292 stored in YYYY-MM-DD format in the database, here it is converted to
1293 DD/MM/YYYY format. A NULL date is returned as C<//>.
1295 =item C<$data-E<gt>{datedue}>
1297 =item C<$data-E<gt>{class}>
1299 This is the concatenation of C<biblioitems.classification>, the book's
1300 Dewey code, and C<biblioitems.subclass>.
1302 =item C<$data-E<gt>{ocount}>
1304 I think this is the number of copies of the book available.
1306 =item C<$data-E<gt>{order}>
1308 If this is set, it is set to C<One Order>.
1315 my ( $biblionumber ) = @_;
1316 my $dbh = C4
::Context
->dbh;
1317 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1318 require C4
::Languages
;
1319 my $language = C4
::Languages
::getlanguage
();
1325 biblioitems.itemtype,
1328 biblioitems.publicationyear,
1329 biblioitems.publishercode,
1330 biblioitems.volumedate,
1331 biblioitems.volumedesc,
1334 items.notforloan as itemnotforloan,
1335 issues.borrowernumber,
1336 issues.date_due as datedue,
1337 issues.onsite_checkout,
1338 borrowers.cardnumber,
1340 borrowers.firstname,
1341 borrowers.branchcode as bcode,
1343 serial.publisheddate,
1344 itemtypes.description,
1345 COALESCE( localization.translation, itemtypes.description ) AS translated_description,
1346 itemtypes.notforloan as notforloan_per_itemtype,
1349 holding.opac_info as holding_branch_opac_info,
1350 home.opac_info as home_branch_opac_info
1354 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1355 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1356 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1357 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1358 LEFT JOIN issues USING (itemnumber)
1359 LEFT JOIN borrowers USING (borrowernumber)
1360 LEFT JOIN serialitems USING (itemnumber)
1361 LEFT JOIN serial USING (serialid)
1362 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1363 . (C4
::Context
->preference('item-level_itypes') ?
'items.itype' : 'biblioitems.itemtype');
1365 LEFT JOIN localization ON itemtypes
.itemtype
= localization
.code
1366 AND localization
.entity
= 'itemtypes'
1367 AND localization
.lang
= ?
1370 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1371 my $sth = $dbh->prepare($query);
1372 $sth->execute($language, $biblionumber);
1377 my $userenv = C4
::Context
->userenv;
1378 my $want_not_same_branch = C4
::Context
->preference("IndependentBranches") && !C4
::Context
->IsSuperLibrarian();
1379 while ( my $data = $sth->fetchrow_hashref ) {
1380 if ( $data->{borrowernumber
} && $want_not_same_branch) {
1381 $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch
};
1384 $serial ||= $data->{'serial'};
1386 # get notforloan complete status if applicable
1387 if ( my $code = C4
::Koha
::GetAuthValCode
( 'items.notforloan', $data->{frameworkcode
} ) ) {
1388 $data->{notforloanvalue
} = C4
::Koha
::GetKohaAuthorisedValueLib
( $code, $data->{itemnotforloan
} );
1389 $data->{notforloanvalueopac
} = C4
::Koha
::GetKohaAuthorisedValueLib
( $code, $data->{itemnotforloan
}, 1 );
1392 # get restricted status and description if applicable
1393 if ( my $code = C4
::Koha
::GetAuthValCode
( 'items.restricted', $data->{frameworkcode
} ) ) {
1394 $data->{restrictedopac
} = C4
::Koha
::GetKohaAuthorisedValueLib
( $code, $data->{restricted
}, 1 );
1395 $data->{restricted
} = C4
::Koha
::GetKohaAuthorisedValueLib
( $code, $data->{restricted
} );
1398 # my stack procedures
1399 if ( my $code = C4
::Koha
::GetAuthValCode
( 'items.stack', $data->{frameworkcode
} ) ) {
1400 $data->{stack
} = C4
::Koha
::GetKohaAuthorisedValueLib
( $code, $data->{stack
} );
1403 # Find the last 3 people who borrowed this item.
1404 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1405 WHERE itemnumber = ?
1406 AND old_issues.borrowernumber = borrowers.borrowernumber
1407 ORDER BY returndate DESC
1409 $sth2->execute($data->{'itemnumber'});
1411 while (my $data2 = $sth2->fetchrow_hashref()) {
1412 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1413 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1414 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1418 $results[$i] = $data;
1423 ?
sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
1427 =head2 GetItemsLocationInfo
1429 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1431 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1433 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1437 =item C<$data-E<gt>{homebranch}>
1439 Branch Name of the item's homebranch
1441 =item C<$data-E<gt>{holdingbranch}>
1443 Branch Name of the item's holdingbranch
1445 =item C<$data-E<gt>{location}>
1447 Item's shelving location code
1449 =item C<$data-E<gt>{location_intranet}>
1451 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1453 =item C<$data-E<gt>{location_opac}>
1455 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1458 =item C<$data-E<gt>{itemcallnumber}>
1460 Item's itemcallnumber
1462 =item C<$data-E<gt>{cn_sort}>
1464 Item's call number normalized for sorting
1470 sub GetItemsLocationInfo
{
1471 my $biblionumber = shift;
1474 my $dbh = C4
::Context
->dbh;
1475 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1476 location, itemcallnumber, cn_sort
1477 FROM items, branches as a, branches as b
1478 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1479 AND biblionumber = ?
1480 ORDER BY cn_sort ASC";
1481 my $sth = $dbh->prepare($query);
1482 $sth->execute($biblionumber);
1484 while ( my $data = $sth->fetchrow_hashref ) {
1485 $data->{location_intranet
} = GetKohaAuthorisedValueLib
('LOC', $data->{location
});
1486 $data->{location_opac
}= GetKohaAuthorisedValueLib
('LOC', $data->{location
}, 1);
1487 push @results, $data;
1492 =head2 GetHostItemsInfo
1494 $hostiteminfo = GetHostItemsInfo($hostfield);
1495 Returns the iteminfo for items linked to records via a host field
1499 sub GetHostItemsInfo
{
1501 my @returnitemsInfo;
1503 if (C4
::Context
->preference('marcflavour') eq 'MARC21' ||
1504 C4
::Context
->preference('marcflavour') eq 'NORMARC'){
1505 foreach my $hostfield ( $record->field('773') ) {
1506 my $hostbiblionumber = $hostfield->subfield("0");
1507 my $linkeditemnumber = $hostfield->subfield("9");
1508 my @hostitemInfos = GetItemsInfo
($hostbiblionumber);
1509 foreach my $hostitemInfo (@hostitemInfos){
1510 if ($hostitemInfo->{itemnumber
} eq $linkeditemnumber){
1511 push (@returnitemsInfo,$hostitemInfo);
1516 } elsif ( C4
::Context
->preference('marcflavour') eq 'UNIMARC'){
1517 foreach my $hostfield ( $record->field('461') ) {
1518 my $hostbiblionumber = $hostfield->subfield("0");
1519 my $linkeditemnumber = $hostfield->subfield("9");
1520 my @hostitemInfos = GetItemsInfo
($hostbiblionumber);
1521 foreach my $hostitemInfo (@hostitemInfos){
1522 if ($hostitemInfo->{itemnumber
} eq $linkeditemnumber){
1523 push (@returnitemsInfo,$hostitemInfo);
1529 return @returnitemsInfo;
1533 =head2 GetLastAcquisitions
1535 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1536 'itemtypes' => ('BK','BD')}, 10);
1540 sub GetLastAcquisitions
{
1541 my ($data,$max) = @_;
1543 my $itemtype = C4
::Context
->preference('item-level_itypes') ?
'itype' : 'itemtype';
1545 my $number_of_branches = @
{$data->{branches
}};
1546 my $number_of_itemtypes = @
{$data->{itemtypes
}};
1549 my @where = ('WHERE 1 ');
1550 $number_of_branches and push @where
1551 , 'AND holdingbranch IN ('
1552 , join(',', ('?') x
$number_of_branches )
1556 $number_of_itemtypes and push @where
1557 , "AND $itemtype IN ("
1558 , join(',', ('?') x
$number_of_itemtypes )
1562 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1563 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1564 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1566 GROUP BY biblio.biblionumber
1567 ORDER BY dateaccessioned DESC LIMIT $max";
1569 my $dbh = C4
::Context
->dbh;
1570 my $sth = $dbh->prepare($query);
1572 $sth->execute((@
{$data->{branches
}}, @
{$data->{itemtypes
}}));
1575 while( my $row = $sth->fetchrow_hashref){
1576 push @results, {date
=> $row->{dateaccessioned
}
1577 , biblionumber
=> $row->{biblionumber
}
1578 , title
=> $row->{title
}};
1584 =head2 GetItemnumbersForBiblio
1586 my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
1588 Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
1592 sub GetItemnumbersForBiblio
{
1593 my $biblionumber = shift;
1595 my $dbh = C4
::Context
->dbh;
1596 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1597 $sth->execute($biblionumber);
1598 while (my $result = $sth->fetchrow_hashref) {
1599 push @items, $result->{'itemnumber'};
1604 =head2 get_itemnumbers_of
1606 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1608 Given a list of biblionumbers, return the list of corresponding itemnumbers
1609 for each biblionumber.
1611 Return a reference on a hash where keys are biblionumbers and values are
1612 references on array of itemnumbers.
1616 sub get_itemnumbers_of
{
1617 my @biblionumbers = @_;
1619 my $dbh = C4
::Context
->dbh;
1625 WHERE biblionumber IN (?' . ( ',?' x
scalar @biblionumbers - 1 ) . ')
1627 my $sth = $dbh->prepare($query);
1628 $sth->execute(@biblionumbers);
1632 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1633 push @
{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1636 return \
%itemnumbers_of;
1639 =head2 get_hostitemnumbers_of
1641 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1643 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1645 Return a reference on a hash where key is a biblionumber and values are
1646 references on array of itemnumbers.
1651 sub get_hostitemnumbers_of
{
1652 my ($biblionumber) = @_;
1653 my $marcrecord = C4
::Biblio
::GetMarcBiblio
($biblionumber);
1655 my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1657 my $marcflavor = C4
::Context
->preference('marcflavour');
1658 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1662 } elsif ($marcflavor eq 'UNIMARC') {
1668 foreach my $hostfield ( $marcrecord->field($tag) ) {
1669 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1670 my $linkeditemnumber = $hostfield->subfield($item_s);
1672 if (my $itemnumbers = get_itemnumbers_of
($hostbiblionumber)->{$hostbiblionumber})
1674 @itemnumbers = @
$itemnumbers;
1676 foreach my $itemnumber (@itemnumbers){
1677 if ($itemnumber eq $linkeditemnumber){
1678 push (@returnhostitemnumbers,$itemnumber);
1683 return @returnhostitemnumbers;
1687 =head2 GetItemnumberFromBarcode
1689 $result = GetItemnumberFromBarcode($barcode);
1693 sub GetItemnumberFromBarcode
{
1695 my $dbh = C4
::Context
->dbh;
1698 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1699 $rq->execute($barcode);
1700 my ($result) = $rq->fetchrow;
1704 =head2 GetBarcodeFromItemnumber
1706 $result = GetBarcodeFromItemnumber($itemnumber);
1710 sub GetBarcodeFromItemnumber
{
1711 my ($itemnumber) = @_;
1712 my $dbh = C4
::Context
->dbh;
1715 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1716 $rq->execute($itemnumber);
1717 my ($result) = $rq->fetchrow;
1721 =head2 GetHiddenItemnumbers
1723 my @itemnumbers_to_hide = GetHiddenItemnumbers(@items);
1725 Given a list of items it checks which should be hidden from the OPAC given
1726 the current configuration. Returns a list of itemnumbers corresponding to
1727 those that should be hidden.
1731 sub GetHiddenItemnumbers
{
1735 my $yaml = C4
::Context
->preference('OpacHiddenItems');
1736 return () if (! $yaml =~ /\S/ );
1737 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1740 $hidingrules = YAML
::Load
($yaml);
1743 warn "Unable to parse OpacHiddenItems syspref : $@";
1746 my $dbh = C4
::Context
->dbh;
1749 foreach my $item (@items) {
1751 # We check each rule
1752 foreach my $field (keys %$hidingrules) {
1754 if (exists $item->{$field}) {
1755 $val = $item->{$field};
1758 my $query = "SELECT $field from items where itemnumber = ?";
1759 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1761 $val = '' unless defined $val;
1763 # If the results matches the values in the yaml file
1764 if (any
{ $val eq $_ } @
{$hidingrules->{$field}}) {
1766 # We add the itemnumber to the list
1767 push @resultitems, $item->{'itemnumber'};
1769 # If at least one rule matched for an item, no need to test the others
1774 return @resultitems;
1777 =head1 LIMITED USE FUNCTIONS
1779 The following functions, while part of the public API,
1780 are not exported. This is generally because they are
1781 meant to be used by only one script for a specific
1782 purpose, and should not be used in any other context
1783 without careful thought.
1789 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1791 Returns MARC::Record of the item passed in parameter.
1792 This function is meant for use only in C<cataloguing/additem.pl>,
1793 where it is needed to support that script's MARC-like
1799 my ( $biblionumber, $itemnumber ) = @_;
1801 # GetMarcItem has been revised so that it does the following:
1802 # 1. Gets the item information from the items table.
1803 # 2. Converts it to a MARC field for storage in the bib record.
1805 # The previous behavior was:
1806 # 1. Get the bib record.
1807 # 2. Return the MARC tag corresponding to the item record.
1809 # The difference is that one treats the items row as authoritative,
1810 # while the other treats the MARC representation as authoritative
1811 # under certain circumstances.
1813 my $itemrecord = GetItem
($itemnumber);
1815 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1816 # Also, don't emit a subfield if the underlying field is blank.
1819 return Item2Marc
($itemrecord,$biblionumber);
1823 my ($itemrecord,$biblionumber)=@_;
1826 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ?
("items.$_" => $itemrecord->{$_}) : ()
1827 } keys %{ $itemrecord }
1830 my $itemmarc = C4
::Biblio
::TransformKohaToMarc
($mungeditem);
1831 my ( $itemtag, $itemsubfield ) = C4
::Biblio
::GetMarcFromKohaField
("items.itemnumber",C4
::Biblio
::GetFrameworkCode
($biblionumber)||'');
1833 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml
($mungeditem->{'items.more_subfields_xml'});
1834 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1835 foreach my $field ($itemmarc->field($itemtag)){
1836 $field->add_subfields(@
$unlinked_item_subfields);
1842 =head1 PRIVATE FUNCTIONS AND VARIABLES
1844 The following functions are not meant to be called
1845 directly, but are documented in order to explain
1846 the inner workings of C<C4::Items>.
1850 =head2 %derived_columns
1852 This hash keeps track of item columns that
1853 are strictly derived from other columns in
1854 the item record and are not meant to be set
1857 Each key in the hash should be the name of a
1858 column (as named by TransformMarcToKoha). Each
1859 value should be hashref whose keys are the
1860 columns on which the derived column depends. The
1861 hashref should also contain a 'BUILDER' key
1862 that is a reference to a sub that calculates
1867 my %derived_columns = (
1868 'items.cn_sort' => {
1869 'itemcallnumber' => 1,
1870 'items.cn_source' => 1,
1871 'BUILDER' => \
&_calc_items_cn_sort
,
1875 =head2 _set_derived_columns_for_add
1877 _set_derived_column_for_add($item);
1879 Given an item hash representing a new item to be added,
1880 calculate any derived columns. Currently the only
1881 such column is C<items.cn_sort>.
1885 sub _set_derived_columns_for_add
{
1888 foreach my $column (keys %derived_columns) {
1889 my $builder = $derived_columns{$column}->{'BUILDER'};
1890 my $source_values = {};
1891 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1892 next if $source_column eq 'BUILDER';
1893 $source_values->{$source_column} = $item->{$source_column};
1895 $builder->($item, $source_values);
1899 =head2 _set_derived_columns_for_mod
1901 _set_derived_column_for_mod($item);
1903 Given an item hash representing a new item to be modified.
1904 calculate any derived columns. Currently the only
1905 such column is C<items.cn_sort>.
1907 This routine differs from C<_set_derived_columns_for_add>
1908 in that it needs to handle partial item records. In other
1909 words, the caller of C<ModItem> may have supplied only one
1910 or two columns to be changed, so this function needs to
1911 determine whether any of the columns to be changed affect
1912 any of the derived columns. Also, if a derived column
1913 depends on more than one column, but the caller is not
1914 changing all of then, this routine retrieves the unchanged
1915 values from the database in order to ensure a correct
1920 sub _set_derived_columns_for_mod
{
1923 foreach my $column (keys %derived_columns) {
1924 my $builder = $derived_columns{$column}->{'BUILDER'};
1925 my $source_values = {};
1926 my %missing_sources = ();
1927 my $must_recalc = 0;
1928 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1929 next if $source_column eq 'BUILDER';
1930 if (exists $item->{$source_column}) {
1932 $source_values->{$source_column} = $item->{$source_column};
1934 $missing_sources{$source_column} = 1;
1938 foreach my $source_column (keys %missing_sources) {
1939 $source_values->{$source_column} = _get_single_item_column
($source_column, $item->{'itemnumber'});
1941 $builder->($item, $source_values);
1946 =head2 _do_column_fixes_for_mod
1948 _do_column_fixes_for_mod($item);
1950 Given an item hashref containing one or more
1951 columns to modify, fix up certain values.
1952 Specifically, set to 0 any passed value
1953 of C<notforloan>, C<damaged>, C<itemlost>, or
1954 C<withdrawn> that is either undefined or
1955 contains the empty string.
1959 sub _do_column_fixes_for_mod
{
1962 if (exists $item->{'notforloan'} and
1963 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1964 $item->{'notforloan'} = 0;
1966 if (exists $item->{'damaged'} and
1967 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1968 $item->{'damaged'} = 0;
1970 if (exists $item->{'itemlost'} and
1971 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1972 $item->{'itemlost'} = 0;
1974 if (exists $item->{'withdrawn'} and
1975 (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
1976 $item->{'withdrawn'} = 0;
1978 if (exists $item->{location
}
1979 and $item->{location
} ne 'CART'
1980 and $item->{location
} ne 'PROC'
1981 and not $item->{permanent_location
}
1983 $item->{'permanent_location'} = $item->{'location'};
1985 if (exists $item->{'timestamp'}) {
1986 delete $item->{'timestamp'};
1990 =head2 _get_single_item_column
1992 _get_single_item_column($column, $itemnumber);
1994 Retrieves the value of a single column from an C<items>
1995 row specified by C<$itemnumber>.
1999 sub _get_single_item_column
{
2001 my $itemnumber = shift;
2003 my $dbh = C4
::Context
->dbh;
2004 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
2005 $sth->execute($itemnumber);
2006 my ($value) = $sth->fetchrow();
2010 =head2 _calc_items_cn_sort
2012 _calc_items_cn_sort($item, $source_values);
2014 Helper routine to calculate C<items.cn_sort>.
2018 sub _calc_items_cn_sort
{
2020 my $source_values = shift;
2022 $item->{'items.cn_sort'} = GetClassSort
($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2025 =head2 _set_defaults_for_add
2027 _set_defaults_for_add($item_hash);
2029 Given an item hash representing an item to be added, set
2030 correct default values for columns whose default value
2031 is not handled by the DBMS. This includes the following
2038 C<items.dateaccessioned>
2060 sub _set_defaults_for_add
{
2062 $item->{dateaccessioned
} ||= output_pref
({ dt
=> dt_from_string
, dateformat
=> 'iso', dateonly
=> 1 });
2063 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
2066 =head2 _koha_new_item
2068 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2070 Perform the actual insert into the C<items> table.
2074 sub _koha_new_item
{
2075 my ( $item, $barcode ) = @_;
2076 my $dbh=C4
::Context
->dbh;
2078 $item->{permanent_location
} //= $item->{location
};
2079 _mod_item_dates
( $item );
2081 "INSERT INTO items SET
2083 biblioitemnumber = ?,
2085 dateaccessioned = ?,
2089 replacementprice = ?,
2090 replacementpricedate = ?,
2091 datelastborrowed = ?,
2099 coded_location_qualifier = ?,
2102 itemnotes_nonpublic = ?,
2106 permanent_location = ?,
2118 more_subfields_xml = ?,
2123 my $sth = $dbh->prepare($query);
2124 my $today = output_pref
({ dt
=> dt_from_string
, dateformat
=> 'iso', dateonly
=> 1 });
2126 $item->{'biblionumber'},
2127 $item->{'biblioitemnumber'},
2129 $item->{'dateaccessioned'},
2130 $item->{'booksellerid'},
2131 $item->{'homebranch'},
2133 $item->{'replacementprice'},
2134 $item->{'replacementpricedate'} || $today,
2135 $item->{datelastborrowed
},
2136 $item->{datelastseen
} || $today,
2138 $item->{'notforloan'},
2140 $item->{'itemlost'},
2141 $item->{'withdrawn'},
2142 $item->{'itemcallnumber'},
2143 $item->{'coded_location_qualifier'},
2144 $item->{'restricted'},
2145 $item->{'itemnotes'},
2146 $item->{'itemnotes_nonpublic'},
2147 $item->{'holdingbranch'},
2149 $item->{'location'},
2150 $item->{'permanent_location'},
2153 $item->{'renewals'},
2154 $item->{'reserves'},
2155 $item->{'items.cn_source'},
2156 $item->{'items.cn_sort'},
2159 $item->{'materials'},
2161 $item->{'enumchron'},
2162 $item->{'more_subfields_xml'},
2163 $item->{'copynumber'},
2164 $item->{'stocknumber'},
2165 $item->{'new_status'},
2169 if ( defined $sth->errstr ) {
2170 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2173 $itemnumber = $dbh->{'mysql_insertid'};
2176 return ( $itemnumber, $error );
2179 =head2 MoveItemFromBiblio
2181 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2183 Moves an item from a biblio to another
2185 Returns undef if the move failed or the biblionumber of the destination record otherwise
2189 sub MoveItemFromBiblio
{
2190 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2191 my $dbh = C4
::Context
->dbh;
2192 my ( $tobiblioitem ) = $dbh->selectrow_array(q
|
2193 SELECT biblioitemnumber
2195 WHERE biblionumber
= ?
2196 |, undef, $tobiblio );
2197 my $return = $dbh->do(q
|
2199 SET biblioitemnumber
= ?
,
2201 WHERE itemnumber
= ?
2202 AND biblionumber
= ?
2203 |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
2205 ModZebra
( $tobiblio, "specialUpdate", "biblioserver" );
2206 ModZebra
( $frombiblio, "specialUpdate", "biblioserver" );
2207 # Checking if the item we want to move is in an order
2208 require C4
::Acquisition
;
2209 my $order = C4
::Acquisition
::GetOrderFromItemnumber
($itemnumber);
2211 # Replacing the biblionumber within the order if necessary
2212 $order->{'biblionumber'} = $tobiblio;
2213 C4
::Acquisition
::ModOrder
($order);
2216 # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
2217 for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
2220 SET biblionumber
= ?
2221 WHERE itemnumber
= ?
2222 |, undef, $tobiblio, $itemnumber );
2231 DelItemCheck($dbh, $biblionumber, $itemnumber);
2233 Exported function (core API) for deleting an item record in Koha if there no current issue.
2238 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2240 $dbh ||= C4
::Context
->dbh;
2244 my $countanalytics=GetAnalyticsCount
($itemnumber);
2247 # check that there is no issue on this item before deletion.
2248 my $sth = $dbh->prepare(q{
2249 SELECT COUNT(*) FROM issues
2250 WHERE itemnumber = ?
2252 $sth->execute($itemnumber);
2253 my ($onloan) = $sth->fetchrow;
2255 my $item = GetItem
($itemnumber);
2258 $error = "book_on_loan"
2260 elsif ( defined C4
::Context
->userenv
2261 and !C4
::Context
->IsSuperLibrarian()
2262 and C4
::Context
->preference("IndependentBranches")
2263 and ( C4
::Context
->userenv->{branch
} ne $item->{'homebranch'} ) )
2265 $error = "not_same_branch";
2268 # check it doesn't have a waiting reserve
2269 $sth = $dbh->prepare(q{
2270 SELECT COUNT(*) FROM reserves
2271 WHERE (found = 'W' OR found = 'T')
2274 $sth->execute($itemnumber);
2275 my ($reserve) = $sth->fetchrow;
2277 $error = "book_reserved";
2278 } elsif ($countanalytics > 0){
2279 $error = "linked_analytics";
2283 biblionumber
=> $biblionumber,
2284 itemnumber
=> $itemnumber
2293 =head2 _koha_modify_item
2295 my ($itemnumber,$error) =_koha_modify_item( $item );
2297 Perform the actual update of the C<items> row. Note that this
2298 routine accepts a hashref specifying the columns to update.
2302 sub _koha_modify_item
{
2304 my $dbh=C4
::Context
->dbh;
2307 my $query = "UPDATE items SET ";
2309 _mod_item_dates
( $item );
2310 for my $key ( keys %$item ) {
2311 next if ( $key eq 'itemnumber' );
2313 push @bind, $item->{$key};
2316 $query .= " WHERE itemnumber=?";
2317 push @bind, $item->{'itemnumber'};
2318 my $sth = $dbh->prepare($query);
2319 $sth->execute(@bind);
2321 $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
2324 return ($item->{'itemnumber'},$error);
2327 sub _mod_item_dates
{ # date formatting for date fields in item hash
2329 return if !$item || ref($item) ne 'HASH';
2332 { $_ =~ /^onloan$|^date|date$|datetime$/ }
2334 # Incl. dateaccessioned,replacementpricedate,datelastborrowed,datelastseen
2335 # NOTE: We do not (yet) have items fields ending with datetime
2336 # Fields with _on$ have been handled already
2338 foreach my $key ( @keys ) {
2339 next if !defined $item->{$key}; # skip undefs
2340 my $dt = eval { dt_from_string
( $item->{$key} ) };
2341 # eval: dt_from_string will die on us if we pass illegal dates
2344 if( defined $dt && ref($dt) eq 'DateTime' ) {
2345 if( $key =~ /datetime/ ) {
2346 $newstr = DateTime
::Format
::MySQL
->format_datetime($dt);
2348 $newstr = DateTime
::Format
::MySQL
->format_date($dt);
2351 $item->{$key} = $newstr; # might be undef to clear garbage
2355 =head2 _koha_delete_item
2357 _koha_delete_item( $itemnum );
2359 Internal function to delete an item record from the koha tables
2363 sub _koha_delete_item
{
2364 my ( $itemnum ) = @_;
2366 my $dbh = C4
::Context
->dbh;
2367 # save the deleted item to deleteditems table
2368 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2369 $sth->execute($itemnum);
2370 my $data = $sth->fetchrow_hashref();
2372 # There is no item to delete
2373 return 0 unless $data;
2375 my $query = "INSERT INTO deleteditems SET ";
2377 foreach my $key ( keys %$data ) {
2378 next if ( $key eq 'timestamp' ); # timestamp will be set by db
2379 $query .= "$key = ?,";
2380 push( @bind, $data->{$key} );
2383 $sth = $dbh->prepare($query);
2384 $sth->execute(@bind);
2386 # delete from items table
2387 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2388 my $deleted = $sth->execute($itemnum);
2389 return ( $deleted == 1 ) ?
1 : 0;
2392 =head2 _marc_from_item_hash
2394 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2396 Given an item hash representing a complete item record,
2397 create a C<MARC::Record> object containing an embedded
2398 tag representing that item.
2400 The third, optional parameter C<$unlinked_item_subfields> is
2401 an arrayref of subfields (not mapped to C<items> fields per the
2402 framework) to be added to the MARC representation
2407 sub _marc_from_item_hash
{
2409 my $frameworkcode = shift;
2410 my $unlinked_item_subfields;
2412 $unlinked_item_subfields = shift;
2415 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2416 # Also, don't emit a subfield if the underlying field is blank.
2417 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2418 (/^items\./ ?
($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2419 : () } keys %{ $item } };
2421 my $item_marc = MARC
::Record
->new();
2422 foreach my $item_field ( keys %{$mungeditem} ) {
2423 my ( $tag, $subfield ) = C4
::Biblio
::GetMarcFromKohaField
( $item_field, $frameworkcode );
2424 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2425 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2426 foreach my $value (@values){
2427 if ( my $field = $item_marc->field($tag) ) {
2428 $field->add_subfields( $subfield => $value );
2430 my $add_subfields = [];
2431 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2432 $add_subfields = $unlinked_item_subfields;
2434 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @
$add_subfields );
2442 =head2 _repack_item_errors
2444 Add an error message hash generated by C<CheckItemPreSave>
2445 to a list of errors.
2449 sub _repack_item_errors
{
2450 my $item_sequence_num = shift;
2451 my $item_ref = shift;
2452 my $error_ref = shift;
2454 my @repacked_errors = ();
2456 foreach my $error_code (sort keys %{ $error_ref }) {
2457 my $repacked_error = {};
2458 $repacked_error->{'item_sequence'} = $item_sequence_num;
2459 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ?
$item_ref->{'barcode'} : '';
2460 $repacked_error->{'error_code'} = $error_code;
2461 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2462 push @repacked_errors, $repacked_error;
2465 return @repacked_errors;
2468 =head2 _get_unlinked_item_subfields
2470 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2474 sub _get_unlinked_item_subfields
{
2475 my $original_item_marc = shift;
2476 my $frameworkcode = shift;
2478 my $marcstructure = GetMarcStructure
(1, $frameworkcode);
2480 # assume that this record has only one field, and that that
2481 # field contains only the item information
2483 my @fields = $original_item_marc->fields();
2484 if ($#fields > -1) {
2485 my $field = $fields[0];
2486 my $tag = $field->tag();
2487 foreach my $subfield ($field->subfields()) {
2488 if (defined $subfield->[1] and
2489 $subfield->[1] ne '' and
2490 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2491 push @
$subfields, $subfield->[0] => $subfield->[1];
2498 =head2 _get_unlinked_subfields_xml
2500 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2504 sub _get_unlinked_subfields_xml
{
2505 my $unlinked_item_subfields = shift;
2508 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2509 my $marc = MARC
::Record
->new();
2510 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2511 # used in the framework
2512 $marc->append_fields(MARC
::Field
->new('999', ' ', ' ', @
$unlinked_item_subfields));
2513 $marc->encoding("UTF-8");
2514 $xml = $marc->as_xml("USMARC");
2520 =head2 _parse_unlinked_item_subfields_from_xml
2522 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2526 sub _parse_unlinked_item_subfields_from_xml
{
2528 require C4
::Charset
;
2529 return unless defined $xml and $xml ne "";
2530 my $marc = MARC
::Record
->new_from_xml(C4
::Charset
::StripNonXmlChars
($xml),'UTF-8');
2531 my $unlinked_subfields = [];
2532 my @fields = $marc->fields();
2533 if ($#fields > -1) {
2534 foreach my $subfield ($fields[0]->subfields()) {
2535 push @
$unlinked_subfields, $subfield->[0] => $subfield->[1];
2538 return $unlinked_subfields;
2541 =head2 GetAnalyticsCount
2543 $count= &GetAnalyticsCount($itemnumber)
2545 counts Usage of itemnumber in Analytical bibliorecords.
2549 sub GetAnalyticsCount
{
2550 my ($itemnumber) = @_;
2552 ### ZOOM search here
2554 $query= "hi=".$itemnumber;
2555 my $searcher = Koha
::SearchEngine
::Search
->new({index => $Koha::SearchEngine
::BIBLIOS_INDEX
});
2556 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
2562 $holds = &GetItemHolds($biblionumber, $itemnumber);
2564 This function return the count of holds with $biblionumber and $itemnumber
2569 my ($biblionumber, $itemnumber) = @_;
2571 my $dbh = C4
::Context
->dbh;
2572 my $query = "SELECT count(*)
2574 WHERE biblionumber=? AND itemnumber=?";
2575 my $sth = $dbh->prepare($query);
2576 $sth->execute($biblionumber, $itemnumber);
2577 $holds = $sth->fetchrow;
2581 =head2 SearchItemsByField
2583 my $items = SearchItemsByField($field, $value);
2585 SearchItemsByField will search for items on a specific given field.
2586 For instance you can search all items with a specific stocknumber like this:
2588 my $items = SearchItemsByField('stocknumber', $stocknumber);
2592 sub SearchItemsByField
{
2593 my ($field, $value) = @_;
2600 my ($results) = SearchItems
($filters);
2604 sub _SearchItems_build_where_fragment
{
2607 my $dbh = C4
::Context
->dbh;
2610 if (exists($filter->{conjunction
})) {
2611 my (@where_strs, @where_args);
2612 foreach my $f (@
{ $filter->{filters
} }) {
2613 my $fragment = _SearchItems_build_where_fragment
($f);
2615 push @where_strs, $fragment->{str
};
2616 push @where_args, @
{ $fragment->{args
} };
2621 $where_str = '(' . join (' ' . $filter->{conjunction
} . ' ', @where_strs) . ')';
2624 args
=> \
@where_args,
2628 my @columns = Koha
::Database
->new()->schema()->resultset('Item')->result_source->columns;
2629 push @columns, Koha
::Database
->new()->schema()->resultset('Biblio')->result_source->columns;
2630 push @columns, Koha
::Database
->new()->schema()->resultset('Biblioitem')->result_source->columns;
2631 my @operators = qw(= != > < >= <= like);
2632 my $field = $filter->{field
};
2633 if ( (0 < grep /^$field$/, @columns) or (substr($field, 0, 5) eq 'marc:') ) {
2634 my $op = $filter->{operator
};
2635 my $query = $filter->{query
};
2637 if (!$op or (0 == grep /^$op$/, @operators)) {
2638 $op = '='; # default operator
2642 if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
2644 my $marcsubfield = $2;
2645 my ($kohafield) = $dbh->selectrow_array(q
|
2646 SELECT kohafield FROM marc_subfield_structure
2647 WHERE tagfield
=? AND tagsubfield
=? AND frameworkcode
=''
2648 |, undef, $marcfield, $marcsubfield);
2651 $column = $kohafield;
2653 # MARC field is not linked to a DB field so we need to use
2654 # ExtractValue on biblioitems.marcxml or
2655 # items.more_subfields_xml, depending on the MARC field.
2658 my ($itemfield) = C4
::Biblio
::GetMarcFromKohaField
('items.itemnumber');
2660 if ($marcfield eq $itemfield) {
2661 $sqlfield = 'more_subfields_xml';
2662 $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
2664 $sqlfield = 'marcxml';
2665 if ($marcfield < 10) {
2666 $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
2668 $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
2671 $column = "ExtractValue($sqlfield, '$xpath')";
2677 if (ref $query eq 'ARRAY') {
2680 } elsif ($op eq '!=') {
2684 str
=> "$column $op (" . join (',', ('?') x @
$query) . ")",
2689 str
=> "$column $op ?",
2696 return $where_fragment;
2701 my ($items, $total) = SearchItems($filter, $params);
2703 Perform a search among items
2705 $filter is a reference to a hash which can be a filter, or a combination of filters.
2707 A filter has the following keys:
2711 =item * field: the name of a SQL column in table items
2713 =item * query: the value to search in this column
2715 =item * operator: comparison operator. Can be one of = != > < >= <= like
2719 A combination of filters hash the following keys:
2723 =item * conjunction: 'AND' or 'OR'
2725 =item * filters: array ref of filters
2729 $params is a reference to a hash that can contain the following parameters:
2733 =item * rows: Number of items to return. 0 returns everything (default: 0)
2735 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2738 =item * sortby: A SQL column name in items table to sort on
2740 =item * sortorder: 'ASC' or 'DESC'
2747 my ($filter, $params) = @_;
2751 return unless ref $filter eq 'HASH';
2752 return unless ref $params eq 'HASH';
2754 # Default parameters
2755 $params->{rows
} ||= 0;
2756 $params->{page
} ||= 1;
2757 $params->{sortby
} ||= 'itemnumber';
2758 $params->{sortorder
} ||= 'ASC';
2760 my ($where_str, @where_args);
2761 my $where_fragment = _SearchItems_build_where_fragment
($filter);
2762 if ($where_fragment) {
2763 $where_str = $where_fragment->{str
};
2764 @where_args = @
{ $where_fragment->{args
} };
2767 my $dbh = C4
::Context
->dbh;
2769 SELECT SQL_CALC_FOUND_ROWS items.*
2771 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2772 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
2774 if (defined $where_str and $where_str ne '') {
2775 $query .= qq{ WHERE
$where_str };
2778 my @columns = Koha
::Database
->new()->schema()->resultset('Item')->result_source->columns;
2779 push @columns, Koha
::Database
->new()->schema()->resultset('Biblio')->result_source->columns;
2780 push @columns, Koha
::Database
->new()->schema()->resultset('Biblioitem')->result_source->columns;
2781 my $sortby = (0 < grep {$params->{sortby
} eq $_} @columns)
2782 ?
$params->{sortby
} : 'itemnumber';
2783 my $sortorder = (uc($params->{sortorder
}) eq 'ASC') ?
'ASC' : 'DESC';
2784 $query .= qq{ ORDER BY
$sortby $sortorder };
2786 my $rows = $params->{rows
};
2789 my $offset = $rows * ($params->{page
}-1);
2790 $query .= qq { LIMIT ?
, ?
};
2791 push @limit_args, $offset, $rows;
2794 my $sth = $dbh->prepare($query);
2795 my $rv = $sth->execute(@where_args, @limit_args);
2797 return unless ($rv);
2798 my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2800 return ($sth->fetchall_arrayref({}), $total_rows);
2804 =head1 OTHER FUNCTIONS
2808 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2810 Find the given $subfield in the given $tag in the given
2811 MARC::Record $record. If the subfield is found, returns
2812 the (indicators, value) pair; otherwise, (undef, undef) is
2816 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2817 I suggest we export it from this module.
2822 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2825 if ( $tagfield < 10 ) {
2826 if ( $record->field($tagfield) ) {
2827 push @result, $record->field($tagfield)->data();
2832 foreach my $field ( $record->field($tagfield) ) {
2833 my @subfields = $field->subfields();
2834 foreach my $subfield (@subfields) {
2835 if ( @
$subfield[0] eq $insubfield ) {
2836 push @result, @
$subfield[1];
2837 $indicator = $field->indicator(1) . $field->indicator(2);
2842 return ( $indicator, @result );
2846 =head2 PrepareItemrecordDisplay
2848 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2850 Returns a hash with all the fields for Display a given item data in a template
2852 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2856 sub PrepareItemrecordDisplay
{
2858 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2860 my $dbh = C4
::Context
->dbh;
2861 $frameworkcode = C4
::Biblio
::GetFrameworkCode
($bibnum) if $bibnum;
2862 my ( $itemtagfield, $itemtagsubfield ) = C4
::Biblio
::GetMarcFromKohaField
( "items.itemnumber", $frameworkcode );
2863 my $tagslib = &GetMarcStructure
( 1, $frameworkcode );
2865 # return nothing if we don't have found an existing framework.
2866 return q{} unless $tagslib;
2869 $itemrecord = C4
::Items
::GetMarcItem
( $bibnum, $itemnum );
2873 my $branch_limit = C4
::Context
->userenv ? C4
::Context
->userenv->{"branch"} : "";
2875 SELECT authorised_value
,lib FROM authorised_values
2878 LEFT JOIN authorised_values_branches ON
( id
= av_id
)
2883 $query .= qq{ AND
( branchcode
= ? OR branchcode IS NULL
)} if $branch_limit;
2884 $query .= qq{ ORDER BY lib
};
2885 my $authorised_values_sth = $dbh->prepare( $query );
2886 foreach my $tag ( sort keys %{$tagslib} ) {
2887 my $previous_tag = '';
2890 # loop through each subfield
2892 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2893 next if IsMarcStructureInternal
($tagslib->{$tag}{$subfield});
2894 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2896 $subfield_data{tag
} = $tag;
2897 $subfield_data{subfield
} = $subfield;
2898 $subfield_data{countsubfield
} = $cntsubf++;
2899 $subfield_data{kohafield
} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2900 $subfield_data{id
} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2902 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2903 $subfield_data{marc_lib
} = $tagslib->{$tag}->{$subfield}->{lib
};
2904 $subfield_data{mandatory
} = $tagslib->{$tag}->{$subfield}->{mandatory
};
2905 $subfield_data{repeatable
} = $tagslib->{$tag}->{$subfield}->{repeatable
};
2906 $subfield_data{hidden
} = "display:none"
2907 if ( ( $tagslib->{$tag}->{$subfield}->{hidden
} > 4 )
2908 || ( $tagslib->{$tag}->{$subfield}->{hidden
} < -4 ) );
2909 my ( $x, $defaultvalue );
2911 ( $x, $defaultvalue ) = _find_value
( $tag, $subfield, $itemrecord );
2913 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue
} unless $defaultvalue;
2914 if ( !defined $defaultvalue ) {
2915 $defaultvalue = q
||;
2917 $defaultvalue =~ s/"/"/g;
2920 # search for itemcallnumber if applicable
2921 if ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.itemcallnumber'
2922 && C4
::Context
->preference('itemcallnumber') ) {
2923 my $CNtag = substr( C4
::Context
->preference('itemcallnumber'), 0, 3 );
2924 my $CNsubfield = substr( C4
::Context
->preference('itemcallnumber'), 3, 1 );
2925 if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2926 $defaultvalue = $field->subfield($CNsubfield);
2929 if ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.itemcallnumber'
2931 && $defaultvalues->{'callnumber'} ) {
2932 if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ){
2933 # if the item record exists, only use default value if the item has no callnumber
2934 $defaultvalue = $defaultvalues->{callnumber
};
2935 } elsif ( !$itemrecord and $defaultvalues ) {
2936 # if the item record *doesn't* exists, always use the default value
2937 $defaultvalue = $defaultvalues->{callnumber
};
2940 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.homebranch' )
2942 && $defaultvalues->{'branchcode'} ) {
2943 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2944 $defaultvalue = $defaultvalues->{branchcode
};
2947 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.location' )
2949 && $defaultvalues->{'location'} ) {
2951 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2952 # if the item record exists, only use default value if the item has no locationr
2953 $defaultvalue = $defaultvalues->{location
};
2954 } elsif ( !$itemrecord and $defaultvalues ) {
2955 # if the item record *doesn't* exists, always use the default value
2956 $defaultvalue = $defaultvalues->{location
};
2959 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} ) {
2960 my @authorised_values;
2963 # builds list, depending on authorised value...
2965 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2966 if ( ( C4
::Context
->preference("IndependentBranches") )
2967 && !C4
::Context
->IsSuperLibrarian() ) {
2968 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2969 $sth->execute( C4
::Context
->userenv->{branch
} );
2970 push @authorised_values, ""
2971 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2972 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2973 push @authorised_values, $branchcode;
2974 $authorised_lib{$branchcode} = $branchname;
2977 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2979 push @authorised_values, ""
2980 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2981 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2982 push @authorised_values, $branchcode;
2983 $authorised_lib{$branchcode} = $branchname;
2987 $defaultvalue = C4
::Context
->userenv ? C4
::Context
->userenv->{branch
} : undef;
2988 if ( $defaultvalues and $defaultvalues->{branchcode
} ) {
2989 $defaultvalue = $defaultvalues->{branchcode
};
2993 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "itemtypes" ) {
2994 my $itemtypes = GetItemTypes
( style
=> 'array' );
2995 push @authorised_values, ""
2996 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2997 for my $itemtype ( @
$itemtypes ) {
2998 push @authorised_values, $itemtype->{itemtype
};
2999 $authorised_lib{$itemtype->{itemtype
}} = $itemtype->{translated_description
};
3002 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "cn_source" ) {
3003 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
3005 my $class_sources = GetClassSources
();
3006 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
3008 foreach my $class_source (sort keys %$class_sources) {
3009 next unless $class_sources->{$class_source}->{'used'} or
3010 ($class_source eq $default_source);
3011 push @authorised_values, $class_source;
3012 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
3015 $defaultvalue = $default_source;
3017 #---- "true" authorised value
3019 $authorised_values_sth->execute(
3020 $tagslib->{$tag}->{$subfield}->{authorised_value
},
3021 $branch_limit ?
$branch_limit : ()
3023 push @authorised_values, ""
3024 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
3025 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
3026 push @authorised_values, $value;
3027 $authorised_lib{$value} = $lib;
3030 $subfield_data{marc_value
} = {
3032 values => \
@authorised_values,
3033 default => "$defaultvalue",
3034 labels
=> \
%authorised_lib,
3036 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder
} ) {
3038 require Koha
::FrameworkPlugin
;
3039 my $plugin = Koha
::FrameworkPlugin
->new({
3040 name
=> $tagslib->{$tag}->{$subfield}->{value_builder
},
3043 my $pars = { dbh
=> $dbh, record
=> undef, tagslib
=>$tagslib, id
=> $subfield_data{id
}, tabloop
=> undef };
3044 $plugin->build( $pars );
3045 if ( $itemrecord and my $field = $itemrecord->field($tag) ) {
3046 $defaultvalue = $field->subfield($subfield);
3048 if( !$plugin->errstr ) {
3049 #TODO Move html to template; see report 12176/13397
3050 my $tab= $plugin->noclick?
'-1': '';
3051 my $class= $plugin->noclick?
' disabled': '';
3052 my $title= $plugin->noclick?
'No popup': 'Tag editor';
3053 $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;
3055 warn $plugin->errstr;
3056 $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
3059 elsif ( $tag eq '' ) { # it's an hidden field
3060 $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" />);
3062 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
3063 $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" />);
3065 elsif ( length($defaultvalue) > 100
3066 or (C4
::Context
->preference("marcflavour") eq "UNIMARC" and
3067 300 <= $tag && $tag < 400 && $subfield eq 'a' )
3068 or (C4
::Context
->preference("marcflavour") eq "MARC21" and
3069 500 <= $tag && $tag < 600 )
3071 # oversize field (textarea)
3072 $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");
3074 $subfield_data{marc_value} = "<input type
=\"text
\" name
=\"field_value
\" value
=\"$defaultvalue\" size
=\"50\" maxlength
=\"255\" />";
3076 push( @loop_data, \%subfield_data );
3081 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
3082 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
3085 'itemtagfield' => $itemtagfield,
3086 'itemtagsubfield' => $itemtagsubfield,
3087 'itemnumber' => $itemnumber,
3088 'iteminformation' => \@loop_data
3094 my @columns = C4::Items::columns();
3096 Returns an array of items' table columns on success,
3097 and an empty array on failure.
3102 my $rs = Koha::Database->new->schema->resultset('Item');
3103 return $rs->result_source->columns;
3106 =head2 biblioitems_columns
3108 my @columns = C4::Items::biblioitems_columns();
3110 Returns an array of biblioitems' table columns on success,
3111 and an empty array on failure.
3115 sub biblioitems_columns {
3116 my $rs = Koha::Database->new->schema->resultset('Biblioitem');
3117 return $rs->result_source->columns;
3120 sub ToggleNewStatus {
3121 my ( $params ) = @_;
3122 my @rules = @{ $params->{rules} };
3123 my $report_only = $params->{report_only};
3125 my $dbh = C4::Context->dbh;
3127 my @item_columns = map { "items
.$_" } C4::Items::columns;
3128 my @biblioitem_columns = map { "biblioitems
.$_" } C4::Items::biblioitems_columns;
3130 for my $rule ( @rules ) {
3131 my $age = $rule->{age};
3132 my $conditions = $rule->{conditions};
3133 my $substitutions = $rule->{substitutions};
3137 SELECT items.biblionumber, items.itemnumber
3139 LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
3142 for my $condition ( @$conditions ) {
3144 grep {/^$condition->{field}$/} @item_columns
3145 or grep {/^$condition->{field}$/} @biblioitem_columns
3147 if ( $condition->{value} =~ /\|/ ) {
3148 my @values = split /\|/, $condition->{value};
3149 $query .= qq| AND $condition->{field} IN (|
3150 . join( ',', ('?') x scalar @values )
3152 push @params, @values;
3154 $query .= qq| AND $condition->{field} = ?|;
3155 push @params, $condition->{value};
3159 if ( defined $age ) {
3160 $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
3163 my $sth = $dbh->prepare($query);
3164 $sth->execute( @params );
3165 while ( my $values = $sth->fetchrow_hashref ) {
3166 my $biblionumber = $values->{biblionumber};
3167 my $itemnumber = $values->{itemnumber};
3168 my $item = C4::Items::GetItem( $itemnumber );
3169 for my $substitution ( @$substitutions ) {
3170 next unless $substitution->{field};
3171 C4::Items::ModItem( {$substitution->{field} => $substitution->{value}}, $biblionumber, $itemnumber )
3172 unless $report_only;
3173 push @{ $report->{$itemnumber} }, $substitution;