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 = 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 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 and update
515 the MARC representation of the item.
517 The first argument is a hashref mapping from item column
518 names to the new values. The second and third arguments
519 are the biblionumber and itemnumber, respectively.
520 The fourth, optional parameter (additional_params) may contain the keys
521 unlinked_item_subfields and log_action.
523 C<$unlinked_item_subfields> contains an arrayref containing
524 subfields present in the original MARC
525 representation of the item (e.g., from the item editor) that are
526 not mapped to C<items> columns directly but should instead
527 be stored in C<items.more_subfields_xml> and included in
528 the biblio items tag for display and indexing.
530 If one of the changed columns is used to calculate
531 the derived value of a column such as C<items.cn_sort>,
532 this routine will perform the necessary calculation
535 If log_action is set to false, the action will not be logged.
536 If log_action is true or undefined, the action will be logged.
541 my ( $item, $biblionumber, $itemnumber, $additional_params ) = @_;
542 my $log_action = $additional_params->{log_action
} // 1;
543 my $unlinked_item_subfields = $additional_params->{unlinked_item_subfields
};
545 return unless %$item;
546 $item->{'itemnumber'} = $itemnumber or return;
548 # if $biblionumber is undefined, get it from the current item
549 unless (defined $biblionumber) {
550 $biblionumber = _get_single_item_column
('biblionumber', $itemnumber);
553 if ($unlinked_item_subfields) {
554 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
557 my @fields = qw( itemlost withdrawn damaged );
559 # Only call GetItem if we need to set an "on" date field
560 if ( $item->{itemlost
} || $item->{withdrawn
} || $item->{damaged
} ) {
561 my $pre_mod_item = GetItem
( $item->{'itemnumber'} );
562 for my $field (@fields) {
563 if ( defined( $item->{$field} )
564 and not $pre_mod_item->{$field}
565 and $item->{$field} )
567 $item->{ $field . '_on' } =
568 DateTime
::Format
::MySQL
->format_datetime( dt_from_string
() );
573 # If the field is defined but empty, we are removing and,
574 # and thus need to clear out the 'on' field as well
575 for my $field (@fields) {
576 if ( defined( $item->{$field} ) && !$item->{$field} ) {
577 $item->{ $field . '_on' } = undef;
582 _set_derived_columns_for_mod
($item);
583 _do_column_fixes_for_mod
($item);
586 # attempt to change itemnumber
587 # attempt to change biblionumber (if we want
588 # an API to relink an item to a different bib,
589 # it should be a separate function)
592 _koha_modify_item
($item);
594 # request that bib be reindexed so that searching on current
595 # item status is possible
596 ModZebra
( $biblionumber, "specialUpdate", "biblioserver" );
598 logaction
( "CATALOGUING", "MODIFY", $itemnumber, "item " . Dumper
($item) )
599 if $log_action && C4
::Context
->preference("CataloguingLog");
602 =head2 ModItemTransfer
604 ModItemTransfer($itenumber, $frombranch, $tobranch);
606 Marks an item as being transferred from one branch
611 sub ModItemTransfer
{
612 my ( $itemnumber, $frombranch, $tobranch ) = @_;
614 my $dbh = C4
::Context
->dbh;
616 # Remove the 'shelving cart' location status if it is being used.
617 CartToShelf
( $itemnumber ) if ( C4
::Context
->preference("ReturnToShelvingCart") );
619 $dbh->do("UPDATE branchtransfers SET datearrived = NOW(), comments = ? WHERE itemnumber = ? AND datearrived IS NULL", undef, "Canceled, new transfer from $frombranch to $tobranch created", $itemnumber);
621 #new entry in branchtransfers....
622 my $sth = $dbh->prepare(
623 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
624 VALUES (?, ?, NOW(), ?)");
625 $sth->execute($itemnumber, $frombranch, $tobranch);
627 ModItem
({ holdingbranch
=> $tobranch }, undef, $itemnumber);
628 ModDateLastSeen
($itemnumber);
632 =head2 ModDateLastSeen
634 ModDateLastSeen( $itemnumber, $leave_item_lost );
636 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
637 C<$itemnumber> is the item number
638 C<$leave_item_lost> determines if a lost item will be found or remain lost
642 sub ModDateLastSeen
{
643 my ( $itemnumber, $leave_item_lost ) = @_;
645 my $today = output_pref
({ dt
=> dt_from_string
, dateformat
=> 'iso', dateonly
=> 1 });
648 $params->{datelastseen
} = $today;
649 $params->{itemlost
} = 0 unless $leave_item_lost;
651 ModItem
( $params, undef, $itemnumber, { log_action
=> 0 } );
656 DelItem({ itemnumber => $itemnumber, [ biblionumber => $biblionumber ] } );
658 Exported function (core API) for deleting an item record in Koha.
665 my $itemnumber = $params->{itemnumber
};
666 my $biblionumber = $params->{biblionumber
};
668 unless ($biblionumber) {
669 my $item = Koha
::Items
->find( $itemnumber );
670 $biblionumber = $item ?
$item->biblio->biblionumber : undef;
673 # If there is no biblionumber for the given itemnumber, there is nothing to delete
674 return 0 unless $biblionumber;
676 # FIXME check the item has no current issues
677 my $deleted = _koha_delete_item
( $itemnumber );
679 ModZebra
( $biblionumber, "specialUpdate", "biblioserver" );
681 #search item field code
682 logaction
("CATALOGUING", "DELETE", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
686 =head2 CheckItemPreSave
688 my $item_ref = TransformMarcToKoha($marc, 'items');
690 my %errors = CheckItemPreSave($item_ref);
691 if (exists $errors{'duplicate_barcode'}) {
692 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
693 } elsif (exists $errors{'invalid_homebranch'}) {
694 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
695 } elsif (exists $errors{'invalid_holdingbranch'}) {
696 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
701 Given a hashref containing item fields, determine if it can be
702 inserted or updated in the database. Specifically, checks for
703 database integrity issues, and returns a hash containing any
704 of the following keys, if applicable.
708 =item duplicate_barcode
710 Barcode, if it duplicates one already found in the database.
712 =item invalid_homebranch
714 Home branch, if not defined in branches table.
716 =item invalid_holdingbranch
718 Holding branch, if not defined in branches table.
722 This function does NOT implement any policy-related checks,
723 e.g., whether current operator is allowed to save an
724 item that has a given branch code.
728 sub CheckItemPreSave
{
729 my $item_ref = shift;
733 # check for duplicate barcode
734 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
735 my $existing_item= Koha
::Items
->find({barcode
=> $item_ref->{'barcode'}});
736 if ($existing_item) {
737 if (!exists $item_ref->{'itemnumber'} # new item
738 or $item_ref->{'itemnumber'} != $existing_item->itemnumber) { # existing item
739 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
744 # check for valid home branch
745 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
746 my $home_library = Koha
::Libraries
->find( $item_ref->{homebranch
} );
747 unless (defined $home_library) {
748 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
752 # check for valid holding branch
753 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
754 my $holding_library = Koha
::Libraries
->find( $item_ref->{holdingbranch
} );
755 unless (defined $holding_library) {
756 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
764 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
766 The following functions provide various ways of
767 getting an item record, a set of item records, or
768 lists of authorized values for certain item fields.
772 =head2 GetItemsForInventory
774 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
775 minlocation => $minlocation,
776 maxlocation => $maxlocation,
777 location => $location,
778 itemtype => $itemtype,
779 ignoreissued => $ignoreissued,
780 datelastseen => $datelastseen,
781 branchcode => $branchcode,
785 statushash => $statushash,
788 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
790 The sub returns a reference to a list of hashes, each containing
791 itemnumber, author, title, barcode, item callnumber, and date last
792 seen. It is ordered by callnumber then title.
794 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
795 the datelastseen can be used to specify that you want to see items not seen since a past date only.
796 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
797 $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.
799 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
803 sub GetItemsForInventory
{
804 my ( $parameters ) = @_;
805 my $minlocation = $parameters->{'minlocation'} // '';
806 my $maxlocation = $parameters->{'maxlocation'} // '';
807 my $location = $parameters->{'location'} // '';
808 my $itemtype = $parameters->{'itemtype'} // '';
809 my $ignoreissued = $parameters->{'ignoreissued'} // '';
810 my $datelastseen = $parameters->{'datelastseen'} // '';
811 my $branchcode = $parameters->{'branchcode'} // '';
812 my $branch = $parameters->{'branch'} // '';
813 my $offset = $parameters->{'offset'} // '';
814 my $size = $parameters->{'size'} // '';
815 my $statushash = $parameters->{'statushash'} // '';
816 my $ignore_waiting_holds = $parameters->{'ignore_waiting_holds'} // '';
818 my $dbh = C4
::Context
->dbh;
819 my ( @bind_params, @where_strings );
821 my $select_columns = q{
822 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber
824 my $select_count = q{SELECT COUNT(*)};
827 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
828 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
831 for my $authvfield (keys %$statushash){
832 if ( scalar @
{$statushash->{$authvfield}} > 0 ){
833 my $joinedvals = join ',', @
{$statushash->{$authvfield}};
834 push @where_strings, "$authvfield in (" . $joinedvals . ")";
840 push @where_strings, 'itemcallnumber >= ?';
841 push @bind_params, $minlocation;
845 push @where_strings, 'itemcallnumber <= ?';
846 push @bind_params, $maxlocation;
850 $datelastseen = output_pref
({ str
=> $datelastseen, dateformat
=> 'iso', dateonly
=> 1 });
851 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
852 push @bind_params, $datelastseen;
856 push @where_strings, 'items.location = ?';
857 push @bind_params, $location;
861 if($branch eq "homebranch"){
862 push @where_strings, 'items.homebranch = ?';
864 push @where_strings, 'items.holdingbranch = ?';
866 push @bind_params, $branchcode;
870 push @where_strings, 'biblioitems.itemtype = ?';
871 push @bind_params, $itemtype;
874 if ( $ignoreissued) {
875 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
876 push @where_strings, 'issues.date_due IS NULL';
879 if ( $ignore_waiting_holds ) {
880 $query .= "LEFT JOIN reserves ON items.itemnumber = reserves.itemnumber ";
881 push( @where_strings, q{(reserves.found != 'W' OR reserves.found IS NULL)} );
884 if ( @where_strings ) {
886 $query .= join ' AND ', @where_strings;
888 my $count_query = $select_count . $query;
889 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
890 $query .= " LIMIT $offset, $size" if ($offset and $size);
891 $query = $select_columns . $query;
892 my $sth = $dbh->prepare($query);
893 $sth->execute( @bind_params );
896 my $tmpresults = $sth->fetchall_arrayref({});
897 $sth = $dbh->prepare( $count_query );
898 $sth->execute( @bind_params );
899 my ($iTotalRecords) = $sth->fetchrow_array();
901 my @avs = Koha
::AuthorisedValues
->search(
902 { 'marc_subfield_structures.kohafield' => { '>' => '' },
903 'me.authorised_value' => { '>' => '' },
905 { join => { category
=> 'marc_subfield_structures' },
906 distinct
=> ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'],
907 '+select' => [ 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', 'me.lib' ],
908 '+as' => [ 'kohafield', 'frameworkcode', 'authorised_value', 'lib' ],
912 my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs };
914 foreach my $row (@
$tmpresults) {
917 foreach (keys %$row) {
918 if (defined($avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}})) {
919 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
925 return (\
@results, $iTotalRecords);
930 @results = GetItemsInfo($biblionumber);
932 Returns information about items with the given biblionumber.
934 C<GetItemsInfo> returns a list of references-to-hash. Each element
935 contains a number of keys. Most of them are attributes from the
936 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
937 Koha database. Other keys include:
941 =item C<$data-E<gt>{branchname}>
943 The name (not the code) of the branch to which the book belongs.
945 =item C<$data-E<gt>{datelastseen}>
947 This is simply C<items.datelastseen>, except that while the date is
948 stored in YYYY-MM-DD format in the database, here it is converted to
949 DD/MM/YYYY format. A NULL date is returned as C<//>.
951 =item C<$data-E<gt>{datedue}>
953 =item C<$data-E<gt>{class}>
955 This is the concatenation of C<biblioitems.classification>, the book's
956 Dewey code, and C<biblioitems.subclass>.
958 =item C<$data-E<gt>{ocount}>
960 I think this is the number of copies of the book available.
962 =item C<$data-E<gt>{order}>
964 If this is set, it is set to C<One Order>.
971 my ( $biblionumber ) = @_;
972 my $dbh = C4
::Context
->dbh;
973 require C4
::Languages
;
974 my $language = C4
::Languages
::getlanguage
();
980 biblioitems.itemtype,
983 biblioitems.publicationyear,
984 biblioitems.publishercode,
985 biblioitems.volumedate,
986 biblioitems.volumedesc,
989 items.notforloan as itemnotforloan,
990 issues.borrowernumber,
991 issues.date_due as datedue,
992 issues.onsite_checkout,
993 borrowers.cardnumber,
996 borrowers.branchcode as bcode,
998 serial.publisheddate,
999 itemtypes.description,
1000 COALESCE( localization.translation, itemtypes.description ) AS translated_description,
1001 itemtypes.notforloan as notforloan_per_itemtype,
1005 holding.opac_info as holding_branch_opac_info,
1006 home.opac_info as home_branch_opac_info
1010 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1011 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1012 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1013 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1014 LEFT JOIN issues USING (itemnumber)
1015 LEFT JOIN borrowers USING (borrowernumber)
1016 LEFT JOIN serialitems USING (itemnumber)
1017 LEFT JOIN serial USING (serialid)
1018 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1019 . (C4
::Context
->preference('item-level_itypes') ?
'items.itype' : 'biblioitems.itemtype');
1021 LEFT JOIN localization ON itemtypes
.itemtype
= localization
.code
1022 AND localization
.entity
= 'itemtypes'
1023 AND localization
.lang
= ?
1026 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
1027 my $sth = $dbh->prepare($query);
1028 $sth->execute($language, $biblionumber);
1033 my $userenv = C4
::Context
->userenv;
1034 my $want_not_same_branch = C4
::Context
->preference("IndependentBranches") && !C4
::Context
->IsSuperLibrarian();
1035 while ( my $data = $sth->fetchrow_hashref ) {
1036 if ( $data->{borrowernumber
} && $want_not_same_branch) {
1037 $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch
};
1040 $serial ||= $data->{'serial'};
1043 # get notforloan complete status if applicable
1044 $descriptions = Koha
::AuthorisedValues
->get_description_by_koha_field({frameworkcode
=> $data->{frameworkcode
}, kohafield
=> 'items.notforloan', authorised_value
=> $data->{itemnotforloan
} });
1045 $data->{notforloanvalue
} = $descriptions->{lib
} // '';
1046 $data->{notforloanvalueopac
} = $descriptions->{opac_description
} // '';
1048 # get restricted status and description if applicable
1049 $descriptions = Koha
::AuthorisedValues
->get_description_by_koha_field({frameworkcode
=> $data->{frameworkcode
}, kohafield
=> 'items.restricted', authorised_value
=> $data->{restricted
} });
1050 $data->{restricted
} = $descriptions->{lib
} // '';
1051 $data->{restrictedopac
} = $descriptions->{opac_description
} // '';
1053 # my stack procedures
1054 $descriptions = Koha
::AuthorisedValues
->get_description_by_koha_field({frameworkcode
=> $data->{frameworkcode
}, kohafield
=> 'items.stack', authorised_value
=> $data->{stack
} });
1055 $data->{stack
} = $descriptions->{lib
} // '';
1057 # Find the last 3 people who borrowed this item.
1058 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1059 WHERE itemnumber = ?
1060 AND old_issues.borrowernumber = borrowers.borrowernumber
1061 ORDER BY returndate DESC
1063 $sth2->execute($data->{'itemnumber'});
1065 while (my $data2 = $sth2->fetchrow_hashref()) {
1066 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1067 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1068 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1072 $results[$i] = $data;
1077 ?
sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results
1081 =head2 GetItemsLocationInfo
1083 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1085 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1087 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1091 =item C<$data-E<gt>{homebranch}>
1093 Branch Name of the item's homebranch
1095 =item C<$data-E<gt>{holdingbranch}>
1097 Branch Name of the item's holdingbranch
1099 =item C<$data-E<gt>{location}>
1101 Item's shelving location code
1103 =item C<$data-E<gt>{location_intranet}>
1105 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1107 =item C<$data-E<gt>{location_opac}>
1109 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1112 =item C<$data-E<gt>{itemcallnumber}>
1114 Item's itemcallnumber
1116 =item C<$data-E<gt>{cn_sort}>
1118 Item's call number normalized for sorting
1124 sub GetItemsLocationInfo
{
1125 my $biblionumber = shift;
1128 my $dbh = C4
::Context
->dbh;
1129 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1130 location, itemcallnumber, cn_sort
1131 FROM items, branches as a, branches as b
1132 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1133 AND biblionumber = ?
1134 ORDER BY cn_sort ASC";
1135 my $sth = $dbh->prepare($query);
1136 $sth->execute($biblionumber);
1138 while ( my $data = $sth->fetchrow_hashref ) {
1139 my $av = Koha
::AuthorisedValues
->search({ category
=> 'LOC', authorised_value
=> $data->{location
} });
1140 $av = $av->count ?
$av->next : undef;
1141 $data->{location_intranet
} = $av ?
$av->lib : '';
1142 $data->{location_opac
} = $av ?
$av->opac_description : '';
1143 push @results, $data;
1148 =head2 GetHostItemsInfo
1150 $hostiteminfo = GetHostItemsInfo($hostfield);
1151 Returns the iteminfo for items linked to records via a host field
1155 sub GetHostItemsInfo
{
1157 my @returnitemsInfo;
1159 if( !C4
::Context
->preference('EasyAnalyticalRecords') ) {
1160 return @returnitemsInfo;
1164 if( C4
::Context
->preference('marcflavour') eq 'MARC21' ||
1165 C4
::Context
->preference('marcflavour') eq 'NORMARC') {
1166 @fields = $record->field('773');
1167 } elsif( C4
::Context
->preference('marcflavour') eq 'UNIMARC') {
1168 @fields = $record->field('461');
1171 foreach my $hostfield ( @fields ) {
1172 my $hostbiblionumber = $hostfield->subfield("0");
1173 my $linkeditemnumber = $hostfield->subfield("9");
1174 my @hostitemInfos = GetItemsInfo
($hostbiblionumber);
1175 foreach my $hostitemInfo (@hostitemInfos) {
1176 if( $hostitemInfo->{itemnumber
} eq $linkeditemnumber ) {
1177 push @returnitemsInfo, $hostitemInfo;
1182 return @returnitemsInfo;
1185 =head2 get_hostitemnumbers_of
1187 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1189 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1191 Return a reference on a hash where key is a biblionumber and values are
1192 references on array of itemnumbers.
1197 sub get_hostitemnumbers_of
{
1198 my ($biblionumber) = @_;
1199 my $marcrecord = C4
::Biblio
::GetMarcBiblio
({ biblionumber
=> $biblionumber });
1201 return unless $marcrecord;
1203 my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
1205 my $marcflavor = C4
::Context
->preference('marcflavour');
1206 if ( $marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC' ) {
1211 elsif ( $marcflavor eq 'UNIMARC' ) {
1217 foreach my $hostfield ( $marcrecord->field($tag) ) {
1218 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1219 next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield
1220 my $linkeditemnumber = $hostfield->subfield($item_s);
1221 if ( ! $linkeditemnumber ) {
1222 warn "ERROR biblionumber $biblionumber has 773^0, but doesn't have 9";
1225 my $is_from_biblio = Koha
::Items
->search({ itemnumber
=> $linkeditemnumber, biblionumber
=> $hostbiblionumber });
1226 push @returnhostitemnumbers, $linkeditemnumber
1230 return @returnhostitemnumbers;
1233 =head2 GetHiddenItemnumbers
1235 my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
1237 Given a list of items it checks which should be hidden from the OPAC given
1238 the current configuration. Returns a list of itemnumbers corresponding to
1239 those that should be hidden. Optionally takes a borcat parameter for certain borrower types
1244 sub GetHiddenItemnumbers
{
1246 my $items = $params->{items
};
1247 if (my $exceptions = C4
::Context
->preference('OpacHiddenItemsExceptions') and $params->{'borcat'}){
1248 foreach my $except (split(/\|/, $exceptions)){
1249 if ($params->{'borcat'} eq $except){
1250 return; # we don't hide anything for this borrower category
1256 my $yaml = C4
::Context
->preference('OpacHiddenItems');
1257 return () if (! $yaml =~ /\S/ );
1258 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1261 $hidingrules = YAML
::Load
($yaml);
1264 warn "Unable to parse OpacHiddenItems syspref : $@";
1267 my $dbh = C4
::Context
->dbh;
1270 foreach my $item (@
$items) {
1272 # We check each rule
1273 foreach my $field (keys %$hidingrules) {
1275 if (exists $item->{$field}) {
1276 $val = $item->{$field};
1279 my $query = "SELECT $field from items where itemnumber = ?";
1280 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1282 $val = '' unless defined $val;
1284 # If the results matches the values in the yaml file
1285 if (any
{ $val eq $_ } @
{$hidingrules->{$field}}) {
1287 # We add the itemnumber to the list
1288 push @resultitems, $item->{'itemnumber'};
1290 # If at least one rule matched for an item, no need to test the others
1295 return @resultitems;
1298 =head1 LIMITED USE FUNCTIONS
1300 The following functions, while part of the public API,
1301 are not exported. This is generally because they are
1302 meant to be used by only one script for a specific
1303 purpose, and should not be used in any other context
1304 without careful thought.
1310 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1312 Returns MARC::Record of the item passed in parameter.
1313 This function is meant for use only in C<cataloguing/additem.pl>,
1314 where it is needed to support that script's MARC-like
1320 my ( $biblionumber, $itemnumber ) = @_;
1322 # GetMarcItem has been revised so that it does the following:
1323 # 1. Gets the item information from the items table.
1324 # 2. Converts it to a MARC field for storage in the bib record.
1326 # The previous behavior was:
1327 # 1. Get the bib record.
1328 # 2. Return the MARC tag corresponding to the item record.
1330 # The difference is that one treats the items row as authoritative,
1331 # while the other treats the MARC representation as authoritative
1332 # under certain circumstances.
1334 my $itemrecord = GetItem
($itemnumber);
1336 # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
1337 # Also, don't emit a subfield if the underlying field is blank.
1340 return Item2Marc
($itemrecord,$biblionumber);
1344 my ($itemrecord,$biblionumber)=@_;
1347 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ?
("items.$_" => $itemrecord->{$_}) : ()
1348 } keys %{ $itemrecord }
1350 my $framework = C4
::Biblio
::GetFrameworkCode
( $biblionumber );
1351 my $itemmarc = C4
::Biblio
::TransformKohaToMarc
(
1352 $mungeditem, { no_split
=> 1},
1354 my ( $itemtag, $itemsubfield ) = C4
::Biblio
::GetMarcFromKohaField
(
1355 "items.itemnumber", $framework,
1358 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml
($mungeditem->{'items.more_subfields_xml'});
1359 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1360 foreach my $field ($itemmarc->field($itemtag)){
1361 $field->add_subfields(@
$unlinked_item_subfields);
1367 =head1 PRIVATE FUNCTIONS AND VARIABLES
1369 The following functions are not meant to be called
1370 directly, but are documented in order to explain
1371 the inner workings of C<C4::Items>.
1375 =head2 %derived_columns
1377 This hash keeps track of item columns that
1378 are strictly derived from other columns in
1379 the item record and are not meant to be set
1382 Each key in the hash should be the name of a
1383 column (as named by TransformMarcToKoha). Each
1384 value should be hashref whose keys are the
1385 columns on which the derived column depends. The
1386 hashref should also contain a 'BUILDER' key
1387 that is a reference to a sub that calculates
1392 my %derived_columns = (
1393 'items.cn_sort' => {
1394 'itemcallnumber' => 1,
1395 'items.cn_source' => 1,
1396 'BUILDER' => \
&_calc_items_cn_sort
,
1400 =head2 _set_derived_columns_for_add
1402 _set_derived_column_for_add($item);
1404 Given an item hash representing a new item to be added,
1405 calculate any derived columns. Currently the only
1406 such column is C<items.cn_sort>.
1410 sub _set_derived_columns_for_add
{
1413 foreach my $column (keys %derived_columns) {
1414 my $builder = $derived_columns{$column}->{'BUILDER'};
1415 my $source_values = {};
1416 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1417 next if $source_column eq 'BUILDER';
1418 $source_values->{$source_column} = $item->{$source_column};
1420 $builder->($item, $source_values);
1424 =head2 _set_derived_columns_for_mod
1426 _set_derived_column_for_mod($item);
1428 Given an item hash representing a new item to be modified.
1429 calculate any derived columns. Currently the only
1430 such column is C<items.cn_sort>.
1432 This routine differs from C<_set_derived_columns_for_add>
1433 in that it needs to handle partial item records. In other
1434 words, the caller of C<ModItem> may have supplied only one
1435 or two columns to be changed, so this function needs to
1436 determine whether any of the columns to be changed affect
1437 any of the derived columns. Also, if a derived column
1438 depends on more than one column, but the caller is not
1439 changing all of then, this routine retrieves the unchanged
1440 values from the database in order to ensure a correct
1445 sub _set_derived_columns_for_mod
{
1448 foreach my $column (keys %derived_columns) {
1449 my $builder = $derived_columns{$column}->{'BUILDER'};
1450 my $source_values = {};
1451 my %missing_sources = ();
1452 my $must_recalc = 0;
1453 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1454 next if $source_column eq 'BUILDER';
1455 if (exists $item->{$source_column}) {
1457 $source_values->{$source_column} = $item->{$source_column};
1459 $missing_sources{$source_column} = 1;
1463 foreach my $source_column (keys %missing_sources) {
1464 $source_values->{$source_column} = _get_single_item_column
($source_column, $item->{'itemnumber'});
1466 $builder->($item, $source_values);
1471 =head2 _do_column_fixes_for_mod
1473 _do_column_fixes_for_mod($item);
1475 Given an item hashref containing one or more
1476 columns to modify, fix up certain values.
1477 Specifically, set to 0 any passed value
1478 of C<notforloan>, C<damaged>, C<itemlost>, or
1479 C<withdrawn> that is either undefined or
1480 contains the empty string.
1484 sub _do_column_fixes_for_mod
{
1487 if (exists $item->{'notforloan'} and
1488 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1489 $item->{'notforloan'} = 0;
1491 if (exists $item->{'damaged'} and
1492 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1493 $item->{'damaged'} = 0;
1495 if (exists $item->{'itemlost'} and
1496 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1497 $item->{'itemlost'} = 0;
1499 if (exists $item->{'withdrawn'} and
1500 (not defined $item->{'withdrawn'} or $item->{'withdrawn'} eq '')) {
1501 $item->{'withdrawn'} = 0;
1503 if (exists $item->{location
}
1504 and $item->{location
} ne 'CART'
1505 and $item->{location
} ne 'PROC'
1506 and not $item->{permanent_location
}
1508 $item->{'permanent_location'} = $item->{'location'};
1510 if (exists $item->{'timestamp'}) {
1511 delete $item->{'timestamp'};
1515 =head2 _get_single_item_column
1517 _get_single_item_column($column, $itemnumber);
1519 Retrieves the value of a single column from an C<items>
1520 row specified by C<$itemnumber>.
1524 sub _get_single_item_column
{
1526 my $itemnumber = shift;
1528 my $dbh = C4
::Context
->dbh;
1529 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1530 $sth->execute($itemnumber);
1531 my ($value) = $sth->fetchrow();
1535 =head2 _calc_items_cn_sort
1537 _calc_items_cn_sort($item, $source_values);
1539 Helper routine to calculate C<items.cn_sort>.
1543 sub _calc_items_cn_sort
{
1545 my $source_values = shift;
1547 $item->{'items.cn_sort'} = GetClassSort
($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1550 =head2 _set_defaults_for_add
1552 _set_defaults_for_add($item_hash);
1554 Given an item hash representing an item to be added, set
1555 correct default values for columns whose default value
1556 is not handled by the DBMS. This includes the following
1563 C<items.dateaccessioned>
1585 sub _set_defaults_for_add
{
1587 $item->{dateaccessioned
} ||= output_pref
({ dt
=> dt_from_string
, dateformat
=> 'iso', dateonly
=> 1 });
1588 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost withdrawn));
1591 =head2 _koha_new_item
1593 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1595 Perform the actual insert into the C<items> table.
1599 sub _koha_new_item
{
1600 my ( $item, $barcode ) = @_;
1601 my $dbh=C4
::Context
->dbh;
1603 $item->{permanent_location
} //= $item->{location
};
1604 _mod_item_dates
( $item );
1606 "INSERT INTO items SET
1608 biblioitemnumber = ?,
1610 dateaccessioned = ?,
1614 replacementprice = ?,
1615 replacementpricedate = ?,
1616 datelastborrowed = ?,
1624 coded_location_qualifier = ?,
1627 itemnotes_nonpublic = ?,
1631 permanent_location = ?,
1643 more_subfields_xml = ?,
1648 my $sth = $dbh->prepare($query);
1649 my $today = output_pref
({ dt
=> dt_from_string
, dateformat
=> 'iso', dateonly
=> 1 });
1651 $item->{'biblionumber'},
1652 $item->{'biblioitemnumber'},
1654 $item->{'dateaccessioned'},
1655 $item->{'booksellerid'},
1656 $item->{'homebranch'},
1658 $item->{'replacementprice'},
1659 $item->{'replacementpricedate'} || $today,
1660 $item->{datelastborrowed
},
1661 $item->{datelastseen
} || $today,
1663 $item->{'notforloan'},
1665 $item->{'itemlost'},
1666 $item->{'withdrawn'},
1667 $item->{'itemcallnumber'},
1668 $item->{'coded_location_qualifier'},
1669 $item->{'restricted'},
1670 $item->{'itemnotes'},
1671 $item->{'itemnotes_nonpublic'},
1672 $item->{'holdingbranch'},
1674 $item->{'location'},
1675 $item->{'permanent_location'},
1678 $item->{'renewals'},
1679 $item->{'reserves'},
1680 $item->{'items.cn_source'},
1681 $item->{'items.cn_sort'},
1684 $item->{'materials'},
1686 $item->{'enumchron'},
1687 $item->{'more_subfields_xml'},
1688 $item->{'copynumber'},
1689 $item->{'stocknumber'},
1690 $item->{'new_status'},
1694 if ( defined $sth->errstr ) {
1695 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1698 $itemnumber = $dbh->{'mysql_insertid'};
1701 return ( $itemnumber, $error );
1704 =head2 MoveItemFromBiblio
1706 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
1708 Moves an item from a biblio to another
1710 Returns undef if the move failed or the biblionumber of the destination record otherwise
1714 sub MoveItemFromBiblio
{
1715 my ($itemnumber, $frombiblio, $tobiblio) = @_;
1716 my $dbh = C4
::Context
->dbh;
1717 my ( $tobiblioitem ) = $dbh->selectrow_array(q
|
1718 SELECT biblioitemnumber
1720 WHERE biblionumber
= ?
1721 |, undef, $tobiblio );
1722 my $return = $dbh->do(q
|
1724 SET biblioitemnumber
= ?
,
1726 WHERE itemnumber
= ?
1727 AND biblionumber
= ?
1728 |, undef, $tobiblioitem, $tobiblio, $itemnumber, $frombiblio );
1730 ModZebra
( $tobiblio, "specialUpdate", "biblioserver" );
1731 ModZebra
( $frombiblio, "specialUpdate", "biblioserver" );
1732 # Checking if the item we want to move is in an order
1733 require C4
::Acquisition
;
1734 my $order = C4
::Acquisition
::GetOrderFromItemnumber
($itemnumber);
1736 # Replacing the biblionumber within the order if necessary
1737 $order->{'biblionumber'} = $tobiblio;
1738 C4
::Acquisition
::ModOrder
($order);
1741 # Update reserves, hold_fill_targets, tmp_holdsqueue and linktracker tables
1742 for my $table_name ( qw( reserves hold_fill_targets tmp_holdsqueue linktracker ) ) {
1745 SET biblionumber
= ?
1746 WHERE itemnumber
= ?
1747 |, undef, $tobiblio, $itemnumber );
1754 =head2 ItemSafeToDelete
1756 ItemSafeToDelete( $biblionumber, $itemnumber);
1758 Exported function (core API) for checking whether an item record is safe to delete.
1760 returns 1 if the item is safe to delete,
1762 "book_on_loan" if the item is checked out,
1764 "not_same_branch" if the item is blocked by independent branches,
1766 "book_reserved" if the there are holds aganst the item, or
1768 "linked_analytics" if the item has linked analytic records.
1772 sub ItemSafeToDelete
{
1773 my ( $biblionumber, $itemnumber ) = @_;
1775 my $dbh = C4
::Context
->dbh;
1779 my $countanalytics = GetAnalyticsCount
($itemnumber);
1781 # check that there is no issue on this item before deletion.
1782 my $sth = $dbh->prepare(
1784 SELECT COUNT(*) FROM issues
1785 WHERE itemnumber = ?
1788 $sth->execute($itemnumber);
1789 my ($onloan) = $sth->fetchrow;
1791 my $item = GetItem
($itemnumber);
1794 $status = "book_on_loan";
1796 elsif ( defined C4
::Context
->userenv
1797 and !C4
::Context
->IsSuperLibrarian()
1798 and C4
::Context
->preference("IndependentBranches")
1799 and ( C4
::Context
->userenv->{branch
} ne $item->{'homebranch'} ) )
1801 $status = "not_same_branch";
1804 # check it doesn't have a waiting reserve
1805 $sth = $dbh->prepare(
1807 SELECT COUNT(*) FROM reserves
1808 WHERE (found = 'W' OR found = 'T')
1812 $sth->execute($itemnumber);
1813 my ($reserve) = $sth->fetchrow;
1815 $status = "book_reserved";
1817 elsif ( $countanalytics > 0 ) {
1818 $status = "linked_analytics";
1829 DelItemCheck( $biblionumber, $itemnumber);
1831 Exported function (core API) for deleting an item record in Koha if there no current issue.
1833 DelItemCheck wraps ItemSafeToDelete around DelItem.
1838 my ( $biblionumber, $itemnumber ) = @_;
1839 my $status = ItemSafeToDelete
( $biblionumber, $itemnumber );
1841 if ( $status == 1 ) {
1844 biblionumber
=> $biblionumber,
1845 itemnumber
=> $itemnumber
1852 =head2 _koha_modify_item
1854 my ($itemnumber,$error) =_koha_modify_item( $item );
1856 Perform the actual update of the C<items> row. Note that this
1857 routine accepts a hashref specifying the columns to update.
1861 sub _koha_modify_item
{
1863 my $dbh=C4
::Context
->dbh;
1866 my $query = "UPDATE items SET ";
1868 _mod_item_dates
( $item );
1869 for my $key ( keys %$item ) {
1870 next if ( $key eq 'itemnumber' );
1872 push @bind, $item->{$key};
1875 $query .= " WHERE itemnumber=?";
1876 push @bind, $item->{'itemnumber'};
1877 my $sth = $dbh->prepare($query);
1878 $sth->execute(@bind);
1880 $error.="ERROR in _koha_modify_item $query: ".$sth->errstr;
1883 return ($item->{'itemnumber'},$error);
1886 sub _mod_item_dates
{ # date formatting for date fields in item hash
1888 return if !$item || ref($item) ne 'HASH';
1891 { $_ =~ /^onloan$|^date|date$|datetime$/ }
1893 # Incl. dateaccessioned,replacementpricedate,datelastborrowed,datelastseen
1894 # NOTE: We do not (yet) have items fields ending with datetime
1895 # Fields with _on$ have been handled already
1897 foreach my $key ( @keys ) {
1898 next if !defined $item->{$key}; # skip undefs
1899 my $dt = eval { dt_from_string
( $item->{$key} ) };
1900 # eval: dt_from_string will die on us if we pass illegal dates
1903 if( defined $dt && ref($dt) eq 'DateTime' ) {
1904 if( $key =~ /datetime/ ) {
1905 $newstr = DateTime
::Format
::MySQL
->format_datetime($dt);
1907 $newstr = DateTime
::Format
::MySQL
->format_date($dt);
1910 $item->{$key} = $newstr; # might be undef to clear garbage
1914 =head2 _koha_delete_item
1916 _koha_delete_item( $itemnum );
1918 Internal function to delete an item record from the koha tables
1922 sub _koha_delete_item
{
1923 my ( $itemnum ) = @_;
1925 my $dbh = C4
::Context
->dbh;
1926 # save the deleted item to deleteditems table
1927 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1928 $sth->execute($itemnum);
1929 my $data = $sth->fetchrow_hashref();
1931 # There is no item to delete
1932 return 0 unless $data;
1934 my $query = "INSERT INTO deleteditems SET ";
1936 foreach my $key ( keys %$data ) {
1937 next if ( $key eq 'timestamp' ); # timestamp will be set by db
1938 $query .= "$key = ?,";
1939 push( @bind, $data->{$key} );
1942 $sth = $dbh->prepare($query);
1943 $sth->execute(@bind);
1945 # delete from items table
1946 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1947 my $deleted = $sth->execute($itemnum);
1948 return ( $deleted == 1 ) ?
1 : 0;
1951 =head2 _marc_from_item_hash
1953 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1955 Given an item hash representing a complete item record,
1956 create a C<MARC::Record> object containing an embedded
1957 tag representing that item.
1959 The third, optional parameter C<$unlinked_item_subfields> is
1960 an arrayref of subfields (not mapped to C<items> fields per the
1961 framework) to be added to the MARC representation
1966 sub _marc_from_item_hash
{
1968 my $frameworkcode = shift;
1969 my $unlinked_item_subfields;
1971 $unlinked_item_subfields = shift;
1974 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1975 # Also, don't emit a subfield if the underlying field is blank.
1976 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1977 (/^items\./ ?
($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1978 : () } keys %{ $item } };
1980 my $item_marc = MARC
::Record
->new();
1981 foreach my $item_field ( keys %{$mungeditem} ) {
1982 my ( $tag, $subfield ) = C4
::Biblio
::GetMarcFromKohaField
( $item_field, $frameworkcode );
1983 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1984 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
1985 foreach my $value (@values){
1986 if ( my $field = $item_marc->field($tag) ) {
1987 $field->add_subfields( $subfield => $value );
1989 my $add_subfields = [];
1990 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1991 $add_subfields = $unlinked_item_subfields;
1993 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @
$add_subfields );
2001 =head2 _repack_item_errors
2003 Add an error message hash generated by C<CheckItemPreSave>
2004 to a list of errors.
2008 sub _repack_item_errors
{
2009 my $item_sequence_num = shift;
2010 my $item_ref = shift;
2011 my $error_ref = shift;
2013 my @repacked_errors = ();
2015 foreach my $error_code (sort keys %{ $error_ref }) {
2016 my $repacked_error = {};
2017 $repacked_error->{'item_sequence'} = $item_sequence_num;
2018 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ?
$item_ref->{'barcode'} : '';
2019 $repacked_error->{'error_code'} = $error_code;
2020 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2021 push @repacked_errors, $repacked_error;
2024 return @repacked_errors;
2027 =head2 _get_unlinked_item_subfields
2029 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2033 sub _get_unlinked_item_subfields
{
2034 my $original_item_marc = shift;
2035 my $frameworkcode = shift;
2037 my $marcstructure = GetMarcStructure
(1, $frameworkcode, { unsafe
=> 1 });
2039 # assume that this record has only one field, and that that
2040 # field contains only the item information
2042 my @fields = $original_item_marc->fields();
2043 if ($#fields > -1) {
2044 my $field = $fields[0];
2045 my $tag = $field->tag();
2046 foreach my $subfield ($field->subfields()) {
2047 if (defined $subfield->[1] and
2048 $subfield->[1] ne '' and
2049 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2050 push @
$subfields, $subfield->[0] => $subfield->[1];
2057 =head2 _get_unlinked_subfields_xml
2059 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2063 sub _get_unlinked_subfields_xml
{
2064 my $unlinked_item_subfields = shift;
2067 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2068 my $marc = MARC
::Record
->new();
2069 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2070 # used in the framework
2071 $marc->append_fields(MARC
::Field
->new('999', ' ', ' ', @
$unlinked_item_subfields));
2072 $marc->encoding("UTF-8");
2073 $xml = $marc->as_xml("USMARC");
2079 =head2 _parse_unlinked_item_subfields_from_xml
2081 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2085 sub _parse_unlinked_item_subfields_from_xml
{
2087 require C4
::Charset
;
2088 return unless defined $xml and $xml ne "";
2089 my $marc = MARC
::Record
->new_from_xml(C4
::Charset
::StripNonXmlChars
($xml),'UTF-8');
2090 my $unlinked_subfields = [];
2091 my @fields = $marc->fields();
2092 if ($#fields > -1) {
2093 foreach my $subfield ($fields[0]->subfields()) {
2094 push @
$unlinked_subfields, $subfield->[0] => $subfield->[1];
2097 return $unlinked_subfields;
2100 =head2 GetAnalyticsCount
2102 $count= &GetAnalyticsCount($itemnumber)
2104 counts Usage of itemnumber in Analytical bibliorecords.
2108 sub GetAnalyticsCount
{
2109 my ($itemnumber) = @_;
2111 ### ZOOM search here
2113 $query= "hi=".$itemnumber;
2114 my $searcher = Koha
::SearchEngine
::Search
->new({index => $Koha::SearchEngine
::BIBLIOS_INDEX
});
2115 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
2119 =head2 SearchItemsByField
2121 my $items = SearchItemsByField($field, $value);
2123 SearchItemsByField will search for items on a specific given field.
2124 For instance you can search all items with a specific stocknumber like this:
2126 my $items = SearchItemsByField('stocknumber', $stocknumber);
2130 sub SearchItemsByField
{
2131 my ($field, $value) = @_;
2138 my ($results) = SearchItems
($filters);
2142 sub _SearchItems_build_where_fragment
{
2145 my $dbh = C4
::Context
->dbh;
2148 if (exists($filter->{conjunction
})) {
2149 my (@where_strs, @where_args);
2150 foreach my $f (@
{ $filter->{filters
} }) {
2151 my $fragment = _SearchItems_build_where_fragment
($f);
2153 push @where_strs, $fragment->{str
};
2154 push @where_args, @
{ $fragment->{args
} };
2159 $where_str = '(' . join (' ' . $filter->{conjunction
} . ' ', @where_strs) . ')';
2162 args
=> \
@where_args,
2166 my @columns = Koha
::Database
->new()->schema()->resultset('Item')->result_source->columns;
2167 push @columns, Koha
::Database
->new()->schema()->resultset('Biblio')->result_source->columns;
2168 push @columns, Koha
::Database
->new()->schema()->resultset('Biblioitem')->result_source->columns;
2169 my @operators = qw(= != > < >= <= like);
2170 my $field = $filter->{field
};
2171 if ( (0 < grep /^$field$/, @columns) or (substr($field, 0, 5) eq 'marc:') ) {
2172 my $op = $filter->{operator
};
2173 my $query = $filter->{query
};
2175 if (!$op or (0 == grep /^$op$/, @operators)) {
2176 $op = '='; # default operator
2180 if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
2182 my $marcsubfield = $2;
2183 my ($kohafield) = $dbh->selectrow_array(q
|
2184 SELECT kohafield FROM marc_subfield_structure
2185 WHERE tagfield
=? AND tagsubfield
=? AND frameworkcode
=''
2186 |, undef, $marcfield, $marcsubfield);
2189 $column = $kohafield;
2191 # MARC field is not linked to a DB field so we need to use
2192 # ExtractValue on marcxml from biblio_metadata or
2193 # items.more_subfields_xml, depending on the MARC field.
2196 my ($itemfield) = C4
::Biblio
::GetMarcFromKohaField
('items.itemnumber');
2197 if ($marcfield eq $itemfield) {
2198 $sqlfield = 'more_subfields_xml';
2199 $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
2201 $sqlfield = 'metadata'; # From biblio_metadata
2202 if ($marcfield < 10) {
2203 $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
2205 $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
2208 $column = "ExtractValue($sqlfield, '$xpath')";
2214 if (ref $query eq 'ARRAY') {
2217 } elsif ($op eq '!=') {
2221 str
=> "$column $op (" . join (',', ('?') x @
$query) . ")",
2226 str
=> "$column $op ?",
2233 return $where_fragment;
2238 my ($items, $total) = SearchItems($filter, $params);
2240 Perform a search among items
2242 $filter is a reference to a hash which can be a filter, or a combination of filters.
2244 A filter has the following keys:
2248 =item * field: the name of a SQL column in table items
2250 =item * query: the value to search in this column
2252 =item * operator: comparison operator. Can be one of = != > < >= <= like
2256 A combination of filters hash the following keys:
2260 =item * conjunction: 'AND' or 'OR'
2262 =item * filters: array ref of filters
2266 $params is a reference to a hash that can contain the following parameters:
2270 =item * rows: Number of items to return. 0 returns everything (default: 0)
2272 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
2275 =item * sortby: A SQL column name in items table to sort on
2277 =item * sortorder: 'ASC' or 'DESC'
2284 my ($filter, $params) = @_;
2288 return unless ref $filter eq 'HASH';
2289 return unless ref $params eq 'HASH';
2291 # Default parameters
2292 $params->{rows
} ||= 0;
2293 $params->{page
} ||= 1;
2294 $params->{sortby
} ||= 'itemnumber';
2295 $params->{sortorder
} ||= 'ASC';
2297 my ($where_str, @where_args);
2298 my $where_fragment = _SearchItems_build_where_fragment
($filter);
2299 if ($where_fragment) {
2300 $where_str = $where_fragment->{str
};
2301 @where_args = @
{ $where_fragment->{args
} };
2304 my $dbh = C4
::Context
->dbh;
2306 SELECT SQL_CALC_FOUND_ROWS items.*
2308 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2309 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
2310 LEFT JOIN biblio_metadata ON biblio_metadata.biblionumber = biblio.biblionumber
2313 if (defined $where_str and $where_str ne '') {
2314 $query .= qq{ AND
$where_str };
2317 $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.marcflavour = ? };
2318 push @where_args, C4
::Context
->preference('marcflavour');
2320 my @columns = Koha
::Database
->new()->schema()->resultset('Item')->result_source->columns;
2321 push @columns, Koha
::Database
->new()->schema()->resultset('Biblio')->result_source->columns;
2322 push @columns, Koha
::Database
->new()->schema()->resultset('Biblioitem')->result_source->columns;
2323 my $sortby = (0 < grep {$params->{sortby
} eq $_} @columns)
2324 ?
$params->{sortby
} : 'itemnumber';
2325 my $sortorder = (uc($params->{sortorder
}) eq 'ASC') ?
'ASC' : 'DESC';
2326 $query .= qq{ ORDER BY
$sortby $sortorder };
2328 my $rows = $params->{rows
};
2331 my $offset = $rows * ($params->{page
}-1);
2332 $query .= qq { LIMIT ?
, ?
};
2333 push @limit_args, $offset, $rows;
2336 my $sth = $dbh->prepare($query);
2337 my $rv = $sth->execute(@where_args, @limit_args);
2339 return unless ($rv);
2340 my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
2342 return ($sth->fetchall_arrayref({}), $total_rows);
2346 =head1 OTHER FUNCTIONS
2350 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2352 Find the given $subfield in the given $tag in the given
2353 MARC::Record $record. If the subfield is found, returns
2354 the (indicators, value) pair; otherwise, (undef, undef) is
2358 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2359 I suggest we export it from this module.
2364 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2367 if ( $tagfield < 10 ) {
2368 if ( $record->field($tagfield) ) {
2369 push @result, $record->field($tagfield)->data();
2374 foreach my $field ( $record->field($tagfield) ) {
2375 my @subfields = $field->subfields();
2376 foreach my $subfield (@subfields) {
2377 if ( @
$subfield[0] eq $insubfield ) {
2378 push @result, @
$subfield[1];
2379 $indicator = $field->indicator(1) . $field->indicator(2);
2384 return ( $indicator, @result );
2388 =head2 PrepareItemrecordDisplay
2390 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2392 Returns a hash with all the fields for Display a given item data in a template
2394 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2398 sub PrepareItemrecordDisplay
{
2400 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2402 my $dbh = C4
::Context
->dbh;
2403 $frameworkcode = C4
::Biblio
::GetFrameworkCode
($bibnum) if $bibnum;
2404 my ( $itemtagfield, $itemtagsubfield ) = C4
::Biblio
::GetMarcFromKohaField
( "items.itemnumber", $frameworkcode );
2406 # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
2407 # a shared data structure. No plugin (including custom ones) should change
2408 # its contents. See also GetMarcStructure.
2409 my $tagslib = GetMarcStructure
( 1, $frameworkcode, { unsafe
=> 1 } );
2411 # return nothing if we don't have found an existing framework.
2412 return q{} unless $tagslib;
2415 $itemrecord = C4
::Items
::GetMarcItem
( $bibnum, $itemnum );
2419 my $branch_limit = C4
::Context
->userenv ? C4
::Context
->userenv->{"branch"} : "";
2421 SELECT authorised_value
,lib FROM authorised_values
2424 LEFT JOIN authorised_values_branches ON
( id
= av_id
)
2429 $query .= qq{ AND
( branchcode
= ? OR branchcode IS NULL
)} if $branch_limit;
2430 $query .= qq{ ORDER BY lib
};
2431 my $authorised_values_sth = $dbh->prepare( $query );
2432 foreach my $tag ( sort keys %{$tagslib} ) {
2435 # loop through each subfield
2437 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2438 next if IsMarcStructureInternal
($tagslib->{$tag}{$subfield});
2439 next unless ( $tagslib->{$tag}->{$subfield}->{'tab'} );
2440 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2442 $subfield_data{tag
} = $tag;
2443 $subfield_data{subfield
} = $subfield;
2444 $subfield_data{countsubfield
} = $cntsubf++;
2445 $subfield_data{kohafield
} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2446 $subfield_data{id
} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2448 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2449 $subfield_data{marc_lib
} = $tagslib->{$tag}->{$subfield}->{lib
};
2450 $subfield_data{mandatory
} = $tagslib->{$tag}->{$subfield}->{mandatory
};
2451 $subfield_data{repeatable
} = $tagslib->{$tag}->{$subfield}->{repeatable
};
2452 $subfield_data{hidden
} = "display:none"
2453 if ( ( $tagslib->{$tag}->{$subfield}->{hidden
} > 4 )
2454 || ( $tagslib->{$tag}->{$subfield}->{hidden
} < -4 ) );
2455 my ( $x, $defaultvalue );
2457 ( $x, $defaultvalue ) = _find_value
( $tag, $subfield, $itemrecord );
2459 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue
} unless $defaultvalue;
2460 if ( !defined $defaultvalue ) {
2461 $defaultvalue = q
||;
2463 $defaultvalue =~ s/"/"/g;
2466 # search for itemcallnumber if applicable
2467 if ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.itemcallnumber'
2468 && C4
::Context
->preference('itemcallnumber') ) {
2469 my $CNtag = substr( C4
::Context
->preference('itemcallnumber'), 0, 3 );
2470 my $CNsubfield = substr( C4
::Context
->preference('itemcallnumber'), 3, 1 );
2471 if ( $itemrecord and my $field = $itemrecord->field($CNtag) ) {
2472 $defaultvalue = $field->subfield($CNsubfield);
2475 if ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.itemcallnumber'
2477 && $defaultvalues->{'callnumber'} ) {
2478 if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ){
2479 # if the item record exists, only use default value if the item has no callnumber
2480 $defaultvalue = $defaultvalues->{callnumber
};
2481 } elsif ( !$itemrecord and $defaultvalues ) {
2482 # if the item record *doesn't* exists, always use the default value
2483 $defaultvalue = $defaultvalues->{callnumber
};
2486 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.homebranch' )
2488 && $defaultvalues->{'branchcode'} ) {
2489 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2490 $defaultvalue = $defaultvalues->{branchcode
};
2493 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield
} eq 'items.location' )
2495 && $defaultvalues->{'location'} ) {
2497 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
2498 # if the item record exists, only use default value if the item has no locationr
2499 $defaultvalue = $defaultvalues->{location
};
2500 } elsif ( !$itemrecord and $defaultvalues ) {
2501 # if the item record *doesn't* exists, always use the default value
2502 $defaultvalue = $defaultvalues->{location
};
2505 if ( $tagslib->{$tag}->{$subfield}->{authorised_value
} ) {
2506 my @authorised_values;
2509 # builds list, depending on authorised value...
2511 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2512 if ( ( C4
::Context
->preference("IndependentBranches") )
2513 && !C4
::Context
->IsSuperLibrarian() ) {
2514 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2515 $sth->execute( C4
::Context
->userenv->{branch
} );
2516 push @authorised_values, ""
2517 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2518 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2519 push @authorised_values, $branchcode;
2520 $authorised_lib{$branchcode} = $branchname;
2523 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2525 push @authorised_values, ""
2526 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2527 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2528 push @authorised_values, $branchcode;
2529 $authorised_lib{$branchcode} = $branchname;
2533 $defaultvalue = C4
::Context
->userenv ? C4
::Context
->userenv->{branch
} : undef;
2534 if ( $defaultvalues and $defaultvalues->{branchcode
} ) {
2535 $defaultvalue = $defaultvalues->{branchcode
};
2539 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "itemtypes" ) {
2540 my $itemtypes = Koha
::ItemTypes
->search_with_localization;
2541 push @authorised_values, ""
2542 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2543 while ( my $itemtype = $itemtypes->next ) {
2544 push @authorised_values, $itemtype->itemtype;
2545 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
2547 if ($defaultvalues && $defaultvalues->{'itemtype'}) {
2548 $defaultvalue = $defaultvalues->{'itemtype'};
2552 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value
} eq "cn_source" ) {
2553 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2555 my $class_sources = GetClassSources
();
2556 my $default_source = C4
::Context
->preference("DefaultClassificationSource");
2558 foreach my $class_source (sort keys %$class_sources) {
2559 next unless $class_sources->{$class_source}->{'used'} or
2560 ($class_source eq $default_source);
2561 push @authorised_values, $class_source;
2562 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2565 $defaultvalue = $default_source;
2567 #---- "true" authorised value
2569 $authorised_values_sth->execute(
2570 $tagslib->{$tag}->{$subfield}->{authorised_value
},
2571 $branch_limit ?
$branch_limit : ()
2573 push @authorised_values, ""
2574 unless ( $tagslib->{$tag}->{$subfield}->{mandatory
} );
2575 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2576 push @authorised_values, $value;
2577 $authorised_lib{$value} = $lib;
2580 $subfield_data{marc_value
} = {
2582 values => \
@authorised_values,
2583 default => "$defaultvalue",
2584 labels
=> \
%authorised_lib,
2586 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder
} ) {
2588 require Koha
::FrameworkPlugin
;
2589 my $plugin = Koha
::FrameworkPlugin
->new({
2590 name
=> $tagslib->{$tag}->{$subfield}->{value_builder
},
2593 my $pars = { dbh
=> $dbh, record
=> undef, tagslib
=>$tagslib, id
=> $subfield_data{id
}, tabloop
=> undef };
2594 $plugin->build( $pars );
2595 if ( $itemrecord and my $field = $itemrecord->field($tag) ) {
2596 $defaultvalue = $field->subfield($subfield);
2598 if( !$plugin->errstr ) {
2599 #TODO Move html to template; see report 12176/13397
2600 my $tab= $plugin->noclick?
'-1': '';
2601 my $class= $plugin->noclick?
' disabled': '';
2602 my $title= $plugin->noclick?
'No popup': 'Tag editor';
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" /><a href="#" id="buttonDot_$subfield_data{id}" tabindex="$tab" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
2605 warn $plugin->errstr;
2606 $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
2609 elsif ( $tag eq '' ) { # it's an hidden field
2610 $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" />);
2612 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2613 $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" />);
2615 elsif ( length($defaultvalue) > 100
2616 or (C4
::Context
->preference("marcflavour") eq "UNIMARC" and
2617 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2618 or (C4
::Context
->preference("marcflavour") eq "MARC21" and
2619 500 <= $tag && $tag < 600 )
2621 # oversize field (textarea)
2622 $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");
2624 $subfield_data{marc_value} = "<input type
=\"text
\" name
=\"field_value
\" value
=\"$defaultvalue\" size
=\"50\" maxlength
=\"255\" />";
2626 push( @loop_data, \%subfield_data );
2631 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2632 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2635 'itemtagfield' => $itemtagfield,
2636 'itemtagsubfield' => $itemtagsubfield,
2637 'itemnumber' => $itemnumber,
2638 'iteminformation' => \@loop_data
2642 sub ToggleNewStatus {
2643 my ( $params ) = @_;
2644 my @rules = @{ $params->{rules} };
2645 my $report_only = $params->{report_only};
2647 my $dbh = C4::Context->dbh;
2649 my @item_columns = map { "items
.$_" } Koha::Items->columns;
2650 my @biblioitem_columns = map { "biblioitems
.$_" } Koha::Biblioitems->columns;
2652 for my $rule ( @rules ) {
2653 my $age = $rule->{age};
2654 my $conditions = $rule->{conditions};
2655 my $substitutions = $rule->{substitutions};
2659 SELECT items.biblionumber, items.itemnumber
2661 LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
2664 for my $condition ( @$conditions ) {
2666 grep {/^$condition->{field}$/} @item_columns
2667 or grep {/^$condition->{field}$/} @biblioitem_columns
2669 if ( $condition->{value} =~ /\|/ ) {
2670 my @values = split /\|/, $condition->{value};
2671 $query .= qq| AND $condition->{field} IN (|
2672 . join( ',', ('?') x scalar @values )
2674 push @params, @values;
2676 $query .= qq| AND $condition->{field} = ?|;
2677 push @params, $condition->{value};
2681 if ( defined $age ) {
2682 $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
2685 my $sth = $dbh->prepare($query);
2686 $sth->execute( @params );
2687 while ( my $values = $sth->fetchrow_hashref ) {
2688 my $biblionumber = $values->{biblionumber};
2689 my $itemnumber = $values->{itemnumber};
2690 my $item = C4::Items::GetItem( $itemnumber );
2691 for my $substitution ( @$substitutions ) {
2692 next unless $substitution->{field};
2693 C4::Items::ModItem( {$substitution->{field} => $substitution->{value}}, $biblionumber, $itemnumber )
2694 unless $report_only;
2695 push @{ $report->{$itemnumber} }, $substitution;