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>.
23 our (@ISA, @EXPORT_OK);
40 get_hostitemnumbers_of
46 PrepareItemrecordDisplay
54 use C4::Biblio qw( GetMarcStructure TransformMarcToKoha );
55 use Koha::DateUtils qw( dt_from_string output_pref );
57 use C4::ClassSource qw( GetClassSort GetClassSources GetClassSource );
58 use C4::Log qw( logaction );
59 use List::MoreUtils qw( any );
60 use DateTime::Format::MySQL;
61 # debugging; so please don't remove this
63 use Koha::AuthorisedValues;
64 use Koha::DateUtils qw( dt_from_string output_pref );
67 use Koha::Biblioitems;
70 use Koha::SearchEngine;
71 use Koha::SearchEngine::Indexer;
72 use Koha::SearchEngine::Search;
77 C4::Items - item management functions
81 This module contains an API for manipulating item
82 records in Koha, and is used by cataloguing, circulation,
83 acquisitions, and serials management.
85 # FIXME This POD is not up-to-date
86 A Koha item record is stored in two places: the
87 items table and embedded in a MARC tag in the XML
88 version of the associated bib record in C<biblioitems.marcxml>.
89 This is done to allow the item information to be readily
90 indexed (e.g., by Zebra), but means that each item
91 modification transaction must keep the items table
92 and the MARC XML in sync at all times.
94 The items table will be considered authoritative. In other
95 words, if there is ever a discrepancy between the items
96 table and the MARC XML, the items table should be considered
99 =head1 HISTORICAL NOTE
101 Most of the functions in C<C4::Items> were originally in
102 the C<C4::Biblio> module.
104 =head1 CORE EXPORTED FUNCTIONS
106 The following functions are meant for use by users
113 CartToShelf($itemnumber);
115 Set the current shelving location of the item record
116 to its stored permanent shelving location. This is
117 primarily used to indicate when an item whose current
118 location is a special processing ('PROC') or shelving cart
119 ('CART') location is back in the stacks.
124 my ( $itemnumber ) = @_;
126 unless ( $itemnumber ) {
127 croak "FAILED CartToShelf() - no itemnumber supplied";
130 my $item = Koha::Items->find($itemnumber);
131 if ( $item->location eq 'CART' ) {
132 $item->location($item->permanent_location)->store;
136 =head2 AddItemFromMarc
138 my ($biblionumber, $biblioitemnumber, $itemnumber)
139 = AddItemFromMarc($source_item_marc, $biblionumber[, $params]);
141 Given a MARC::Record object containing an embedded item
142 record and a biblionumber, create a new item record.
144 The final optional parameter, C<$params>, expected to contain
145 'skip_record_index' key, which relayed down to Koha::Item/store,
146 there it prevents calling of index_records,
147 which takes most of the time in batch adds/deletes: index_records
148 to be called later in C<additem.pl> after the whole loop.
151 skip_record_index => 1|0
155 sub AddItemFromMarc {
156 my $source_item_marc = shift;
157 my $biblionumber = shift;
158 my $params = @_ ? shift : {};
160 my $dbh = C4::Context->dbh;
162 # parse item hash from MARC
163 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
164 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
166 my $localitemmarc = MARC::Record->new;
167 $localitemmarc->append_fields( $source_item_marc->field($itemtag) );
169 my $item_values = C4::Biblio::TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
170 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
171 $item_values->{more_subfields_xml} = _get_unlinked_subfields_xml($unlinked_item_subfields);
172 $item_values->{biblionumber} = $biblionumber;
173 $item_values->{cn_source} = delete $item_values->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate
174 $item_values->{cn_sort} = delete $item_values->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate
175 my $item = Koha::Item->new( $item_values )->store({ skip_record_index => $params->{skip_record_index} });
176 return ( $item->biblionumber, $item->biblioitemnumber, $item->itemnumber );
179 =head2 AddItemBatchFromMarc
181 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
182 $biblionumber, $biblioitemnumber, $frameworkcode);
184 Efficiently create item records from a MARC biblio record with
185 embedded item fields. This routine is suitable for batch jobs.
187 This API assumes that the bib record has already been
188 saved to the C<biblio> and C<biblioitems> tables. It does
189 not expect that C<biblio_metadata.metadata> is populated, but it
190 will do so via a call to ModBibiloMarc.
192 The goal of this API is to have a similar effect to using AddBiblio
193 and AddItems in succession, but without inefficient repeated
194 parsing of the MARC XML bib record.
196 This function returns an arrayref of new itemsnumbers and an arrayref of item
197 errors encountered during the processing. Each entry in the errors
198 list is a hashref containing the following keys:
204 Sequence number of original item tag in the MARC record.
208 Item barcode, provide to assist in the construction of
209 useful error messages.
213 Code representing the error condition. Can be 'duplicate_barcode',
214 'invalid_homebranch', or 'invalid_holdingbranch'.
216 =item error_information
218 Additional information appropriate to the error condition.
224 sub AddItemBatchFromMarc {
225 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
226 my @itemnumbers = ();
228 my $dbh = C4::Context->dbh;
230 # We modify the record, so lets work on a clone so we don't change the
232 $record = $record->clone();
233 # loop through the item tags and start creating items
234 my @bad_item_fields = ();
235 my ($itemtag, $itemsubfield) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
236 my $item_sequence_num = 0;
237 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
238 $item_sequence_num++;
239 # we take the item field and stick it into a new
240 # MARC record -- this is required so far because (FIXME)
241 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
242 # and there is no TransformMarcFieldToKoha
243 my $temp_item_marc = MARC::Record->new();
244 $temp_item_marc->append_fields($item_field);
246 # add biblionumber and biblioitemnumber
247 my $item = TransformMarcToKoha( $temp_item_marc, $frameworkcode, 'items' );
248 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
249 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
250 $item->{'biblionumber'} = $biblionumber;
251 $item->{'biblioitemnumber'} = $biblioitemnumber;
252 $item->{cn_source} = delete $item->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate
253 $item->{cn_sort} = delete $item->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate
255 # check for duplicate barcode
256 my %item_errors = CheckItemPreSave($item);
258 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
259 push @bad_item_fields, $item_field;
263 my $item_object = Koha::Item->new($item)->store;
264 push @itemnumbers, $item_object->itemnumber; # FIXME not checking error
266 logaction("CATALOGUING", "ADD", $item_object->itemnumber, "item") if C4::Context->preference("CataloguingLog");
268 my $new_item_marc = _marc_from_item_hash($item_object->unblessed, $frameworkcode, $unlinked_item_subfields);
269 $item_field->replace_with($new_item_marc->field($itemtag));
272 # remove any MARC item fields for rejected items
273 foreach my $item_field (@bad_item_fields) {
274 $record->delete_field($item_field);
277 return (\@itemnumbers, \@errors);
280 =head2 ModItemFromMarc
282 my $item = ModItemFromMarc($item_marc, $biblionumber, $itemnumber[, $params]);
284 The final optional parameter, C<$params>, expected to contain
285 'skip_record_index' key, which relayed down to Koha::Item/store,
286 there it prevents calling of index_records,
287 which takes most of the time in batch adds/deletes: index_records better
288 to be called later in C<additem.pl> after the whole loop.
291 skip_record_index => 1|0
295 sub ModItemFromMarc {
296 my ( $item_marc, $biblionumber, $itemnumber, $params ) = @_;
298 my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber);
299 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
301 my $localitemmarc = MARC::Record->new;
302 $localitemmarc->append_fields( $item_marc->field($itemtag) );
303 my $item_object = Koha::Items->find($itemnumber);
304 my $item = TransformMarcToKoha( $localitemmarc, $frameworkcode, 'items' );
306 my ( $perm_loc_tag, $perm_loc_subfield ) = C4::Biblio::GetMarcFromKohaField( "items.permanent_location" );
307 my $has_permanent_location = defined $perm_loc_tag && defined $item_marc->subfield( $perm_loc_tag, $perm_loc_subfield );
309 # Retrieving the values for the fields that are not linked
310 my @mapped_fields = Koha::MarcSubfieldStructures->search(
312 frameworkcode => $frameworkcode,
313 kohafield => { -like => "items.%" }
315 )->get_column('kohafield');
316 for my $c ( $item_object->_result->result_source->columns ) {
317 next if grep { "items.$c" eq $_ } @mapped_fields;
318 $item->{$c} = $item_object->$c;
321 $item->{cn_source} = delete $item->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate
322 delete $item->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate
323 $item->{itemnumber} = $itemnumber;
324 $item->{biblionumber} = $biblionumber;
326 my $existing_cn_sort = $item_object->cn_sort; # set_or_blank will reset cn_sort to undef as we are not passing it
327 # We rely on Koha::Item->store to modify it if itemcallnumber or cn_source is modified
328 $item_object = $item_object->set_or_blank($item);
329 $item_object->cn_sort($existing_cn_sort); # Resetting to the existing value
331 $item_object->make_column_dirty('permanent_location') if $has_permanent_location;
333 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
334 $item_object->more_subfields_xml(_get_unlinked_subfields_xml($unlinked_item_subfields));
335 $item_object->store({ skip_record_index => $params->{skip_record_index} });
337 return $item_object->unblessed;
340 =head2 ModItemTransfer
342 ModItemTransfer($itemnumber, $frombranch, $tobranch, $trigger, [$params]);
344 Marks an item as being transferred from one branch to another and records the trigger.
346 The last optional parameter allows for passing skip_record_index through to the items store call.
350 sub ModItemTransfer {
351 my ( $itemnumber, $frombranch, $tobranch, $trigger, $params ) = @_;
353 my $dbh = C4::Context->dbh;
354 my $item = Koha::Items->find( $itemnumber );
356 # NOTE: This retains the existing hard coded behaviour by ignoring transfer limits
357 # and always replacing any existing transfers. (In theory, calls to ModItemTransfer
358 # will have been preceded by a check of branch transfer limits)
359 my $to_library = Koha::Libraries->find($tobranch);
360 my $transfer = $item->request_transfer(
369 # Immediately set the item to in transit if it is checked in
370 if ( !$item->checkout ) {
371 $item->holdingbranch($frombranch)->store(
374 skip_record_index => $params->{skip_record_index}
383 =head2 ModDateLastSeen
385 ModDateLastSeen( $itemnumber, $leave_item_lost, $params );
387 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
388 C<$itemnumber> is the item number
389 C<$leave_item_lost> determines if a lost item will be found or remain lost
391 The last optional parameter allows for passing skip_record_index through to the items store call.
395 sub ModDateLastSeen {
396 my ( $itemnumber, $leave_item_lost, $params ) = @_;
398 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
400 my $item = Koha::Items->find($itemnumber);
401 $item->datelastseen($today);
402 $item->itemlost(0) unless $leave_item_lost;
403 $item->store({ log_action => 0, skip_record_index => $params->{skip_record_index} });
406 =head2 CheckItemPreSave
408 my $item_ref = TransformMarcToKoha($marc, 'items');
410 my %errors = CheckItemPreSave($item_ref);
411 if (exists $errors{'duplicate_barcode'}) {
412 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
413 } elsif (exists $errors{'invalid_homebranch'}) {
414 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
415 } elsif (exists $errors{'invalid_holdingbranch'}) {
416 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
421 Given a hashref containing item fields, determine if it can be
422 inserted or updated in the database. Specifically, checks for
423 database integrity issues, and returns a hash containing any
424 of the following keys, if applicable.
428 =item duplicate_barcode
430 Barcode, if it duplicates one already found in the database.
432 =item invalid_homebranch
434 Home branch, if not defined in branches table.
436 =item invalid_holdingbranch
438 Holding branch, if not defined in branches table.
442 This function does NOT implement any policy-related checks,
443 e.g., whether current operator is allowed to save an
444 item that has a given branch code.
448 sub CheckItemPreSave {
449 my $item_ref = shift;
453 # check for duplicate barcode
454 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
455 my $existing_item= Koha::Items->find({barcode => $item_ref->{'barcode'}});
456 if ($existing_item) {
457 if (!exists $item_ref->{'itemnumber'} # new item
458 or $item_ref->{'itemnumber'} != $existing_item->itemnumber) { # existing item
459 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
464 # check for valid home branch
465 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
466 my $home_library = Koha::Libraries->find( $item_ref->{homebranch} );
467 unless (defined $home_library) {
468 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
472 # check for valid holding branch
473 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
474 my $holding_library = Koha::Libraries->find( $item_ref->{holdingbranch} );
475 unless (defined $holding_library) {
476 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
484 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
486 The following functions provide various ways of
487 getting an item record, a set of item records, or
488 lists of authorized values for certain item fields.
492 =head2 GetItemsForInventory
494 ($itemlist, $iTotalRecords) = GetItemsForInventory( {
495 minlocation => $minlocation,
496 maxlocation => $maxlocation,
497 location => $location,
498 ignoreissued => $ignoreissued,
499 datelastseen => $datelastseen,
500 branchcode => $branchcode,
504 statushash => $statushash,
505 itemtypes => \@itemsarray,
508 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
510 The sub returns a reference to a list of hashes, each containing
511 itemnumber, author, title, barcode, item callnumber, and date last
512 seen. It is ordered by callnumber then title.
514 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
515 the datelastseen can be used to specify that you want to see items not seen since a past date only.
516 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
517 $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.
519 $iTotalRecords is the number of rows that would have been returned without the $offset, $size limit clause
523 sub GetItemsForInventory {
524 my ( $parameters ) = @_;
525 my $minlocation = $parameters->{'minlocation'} // '';
526 my $maxlocation = $parameters->{'maxlocation'} // '';
527 my $class_source = $parameters->{'class_source'} // C4::Context->preference('DefaultClassificationSource');
528 my $location = $parameters->{'location'} // '';
529 my $itemtype = $parameters->{'itemtype'} // '';
530 my $ignoreissued = $parameters->{'ignoreissued'} // '';
531 my $datelastseen = $parameters->{'datelastseen'} // '';
532 my $branchcode = $parameters->{'branchcode'} // '';
533 my $branch = $parameters->{'branch'} // '';
534 my $offset = $parameters->{'offset'} // '';
535 my $size = $parameters->{'size'} // '';
536 my $statushash = $parameters->{'statushash'} // '';
537 my $ignore_waiting_holds = $parameters->{'ignore_waiting_holds'} // '';
538 my $itemtypes = $parameters->{'itemtypes'} || [];
540 my $dbh = C4::Context->dbh;
541 my ( @bind_params, @where_strings );
543 my $min_cnsort = GetClassSort($class_source,undef,$minlocation);
544 my $max_cnsort = GetClassSort($class_source,undef,$maxlocation);
546 my $select_columns = q{
547 SELECT DISTINCT(items.itemnumber), barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber, items.cn_sort
549 my $select_count = q{SELECT COUNT(DISTINCT(items.itemnumber))};
552 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
553 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
556 for my $authvfield (keys %$statushash){
557 if ( scalar @{$statushash->{$authvfield}} > 0 ){
558 my $joinedvals = join ',', @{$statushash->{$authvfield}};
559 push @where_strings, "$authvfield in (" . $joinedvals . ")";
565 push @where_strings, 'items.cn_sort >= ?';
566 push @bind_params, $min_cnsort;
570 push @where_strings, 'items.cn_sort <= ?';
571 push @bind_params, $max_cnsort;
575 $datelastseen = output_pref({ str => $datelastseen, dateformat => 'iso', dateonly => 1 });
576 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
577 push @bind_params, $datelastseen;
581 push @where_strings, 'items.location = ?';
582 push @bind_params, $location;
586 if($branch eq "homebranch"){
587 push @where_strings, 'items.homebranch = ?';
589 push @where_strings, 'items.holdingbranch = ?';
591 push @bind_params, $branchcode;
595 push @where_strings, 'biblioitems.itemtype = ?';
596 push @bind_params, $itemtype;
598 if ( $ignoreissued) {
599 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
600 push @where_strings, 'issues.date_due IS NULL';
603 if ( $ignore_waiting_holds ) {
604 $query .= "LEFT JOIN reserves ON items.itemnumber = reserves.itemnumber ";
605 push( @where_strings, q{(reserves.found != 'W' OR reserves.found IS NULL)} );
609 my $itemtypes_str = join ', ', @$itemtypes;
610 push @where_strings, "( biblioitems.itemtype IN (" . $itemtypes_str . ") OR items.itype IN (" . $itemtypes_str . ") )";
613 if ( @where_strings ) {
615 $query .= join ' AND ', @where_strings;
617 my $count_query = $select_count . $query;
618 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
619 $query .= " LIMIT $offset, $size" if ($offset and $size);
620 $query = $select_columns . $query;
621 my $sth = $dbh->prepare($query);
622 $sth->execute( @bind_params );
625 my $tmpresults = $sth->fetchall_arrayref({});
626 $sth = $dbh->prepare( $count_query );
627 $sth->execute( @bind_params );
628 my ($iTotalRecords) = $sth->fetchrow_array();
630 my @avs = Koha::AuthorisedValues->search(
631 { 'marc_subfield_structures.kohafield' => { '>' => '' },
632 'me.authorised_value' => { '>' => '' },
634 { join => { category => 'marc_subfield_structures' },
635 distinct => ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'],
636 '+select' => [ 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', 'me.lib' ],
637 '+as' => [ 'kohafield', 'frameworkcode', 'authorised_value', 'lib' ],
641 my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs };
643 foreach my $row (@$tmpresults) {
646 foreach (keys %$row) {
649 $avmapping->{ "items.$_," . $row->{'frameworkcode'} . "," . ( $row->{$_} // q{} ) }
652 $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}};
658 return (\@results, $iTotalRecords);
663 @results = GetItemsInfo($biblionumber);
665 Returns information about items with the given biblionumber.
667 C<GetItemsInfo> returns a list of references-to-hash. Each element
668 contains a number of keys. Most of them are attributes from the
669 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
670 Koha database. Other keys include:
674 =item C<$data-E<gt>{branchname}>
676 The name (not the code) of the branch to which the book belongs.
678 =item C<$data-E<gt>{datelastseen}>
680 This is simply C<items.datelastseen>, except that while the date is
681 stored in YYYY-MM-DD format in the database, here it is converted to
682 DD/MM/YYYY format. A NULL date is returned as C<//>.
684 =item C<$data-E<gt>{datedue}>
686 =item C<$data-E<gt>{class}>
688 This is the concatenation of C<biblioitems.classification>, the book's
689 Dewey code, and C<biblioitems.subclass>.
691 =item C<$data-E<gt>{ocount}>
693 I think this is the number of copies of the book available.
695 =item C<$data-E<gt>{order}>
697 If this is set, it is set to C<One Order>.
704 my ( $biblionumber ) = @_;
705 my $dbh = C4::Context->dbh;
706 require C4::Languages;
707 my $language = C4::Languages::getlanguage();
713 biblioitems.itemtype,
716 biblioitems.publicationyear,
717 biblioitems.publishercode,
718 biblioitems.volumedate,
719 biblioitems.volumedesc,
722 items.notforloan as itemnotforloan,
723 issues.borrowernumber,
724 issues.date_due as datedue,
725 issues.onsite_checkout,
726 borrowers.cardnumber,
729 borrowers.branchcode as bcode,
731 serial.publisheddate,
732 itemtypes.description,
733 COALESCE( localization.translation, itemtypes.description ) AS translated_description,
734 itemtypes.notforloan as notforloan_per_itemtype,
738 holding.opac_info as holding_branch_opac_info,
739 home.opac_info as home_branch_opac_info,
740 IF(tmp_holdsqueue.itemnumber,1,0) AS has_pending_hold
742 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
743 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
744 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
745 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
746 LEFT JOIN issues USING (itemnumber)
747 LEFT JOIN borrowers USING (borrowernumber)
748 LEFT JOIN serialitems USING (itemnumber)
749 LEFT JOIN serial USING (serialid)
750 LEFT JOIN itemtypes ON itemtypes.itemtype = "
751 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
753 LEFT JOIN tmp_holdsqueue USING (itemnumber)
754 LEFT JOIN localization ON itemtypes.itemtype = localization.code
755 AND localization.entity = 'itemtypes'
756 AND localization.lang = ?
759 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname, items.enumchron, LPAD( items.copynumber, 8, '0' ), items.dateaccessioned DESC" ;
760 my $sth = $dbh->prepare($query);
761 $sth->execute($language, $biblionumber);
766 my $userenv = C4::Context->userenv;
767 my $want_not_same_branch = C4::Context->preference("IndependentBranches") && !C4::Context->IsSuperLibrarian();
768 while ( my $data = $sth->fetchrow_hashref ) {
769 if ( $data->{borrowernumber} && $want_not_same_branch) {
770 $data->{'NOTSAMEBRANCH'} = $data->{'bcode'} ne $userenv->{branch};
773 $serial ||= $data->{'serial'};
776 # get notforloan complete status if applicable
777 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.notforloan', authorised_value => $data->{itemnotforloan} });
778 $data->{notforloanvalue} = $descriptions->{lib} // '';
779 $data->{notforloanvalueopac} = $descriptions->{opac_description} // '';
781 # get restricted status and description if applicable
782 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.restricted', authorised_value => $data->{restricted} });
783 $data->{restrictedvalue} = $descriptions->{lib} // '';
784 $data->{restrictedvalueopac} = $descriptions->{opac_description} // '';
786 # my stack procedures
787 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => $data->{frameworkcode}, kohafield => 'items.stack', authorised_value => $data->{stack} });
788 $data->{stack} = $descriptions->{lib} // '';
790 # Find the last 3 people who borrowed this item.
791 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
793 AND old_issues.borrowernumber = borrowers.borrowernumber
794 ORDER BY returndate DESC
796 $sth2->execute($data->{'itemnumber'});
798 while (my $data2 = $sth2->fetchrow_hashref()) {
799 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
800 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
801 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
805 $results[$i] = $data;
810 ? sort { ($b->{'publisheddate'} || $b->{'enumchron'} || "") cmp ($a->{'publisheddate'} || $a->{'enumchron'} || "") } @results
814 =head2 GetItemsLocationInfo
816 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
818 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
820 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
824 =item C<$data-E<gt>{homebranch}>
826 Branch Name of the item's homebranch
828 =item C<$data-E<gt>{holdingbranch}>
830 Branch Name of the item's holdingbranch
832 =item C<$data-E<gt>{location}>
834 Item's shelving location code
836 =item C<$data-E<gt>{location_intranet}>
838 The intranet description for the Shelving Location as set in authorised_values 'LOC'
840 =item C<$data-E<gt>{location_opac}>
842 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
845 =item C<$data-E<gt>{itemcallnumber}>
847 Item's itemcallnumber
849 =item C<$data-E<gt>{cn_sort}>
851 Item's call number normalized for sorting
857 sub GetItemsLocationInfo {
858 my $biblionumber = shift;
861 my $dbh = C4::Context->dbh;
862 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
863 location, itemcallnumber, cn_sort
864 FROM items, branches as a, branches as b
865 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
867 ORDER BY cn_sort ASC";
868 my $sth = $dbh->prepare($query);
869 $sth->execute($biblionumber);
871 while ( my $data = $sth->fetchrow_hashref ) {
872 my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $data->{location} });
873 $av = $av->count ? $av->next : undef;
874 $data->{location_intranet} = $av ? $av->lib : '';
875 $data->{location_opac} = $av ? $av->opac_description : '';
876 push @results, $data;
881 =head2 GetHostItemsInfo
883 $hostiteminfo = GetHostItemsInfo($hostfield);
884 Returns the iteminfo for items linked to records via a host field
888 sub GetHostItemsInfo {
892 if( !C4::Context->preference('EasyAnalyticalRecords') ) {
893 return @returnitemsInfo;
897 if( C4::Context->preference('marcflavour') eq 'MARC21' ) {
898 @fields = $record->field('773');
899 } elsif( C4::Context->preference('marcflavour') eq 'UNIMARC') {
900 @fields = $record->field('461');
903 foreach my $hostfield ( @fields ) {
904 my $hostbiblionumber = $hostfield->subfield("0");
905 my $linkeditemnumber = $hostfield->subfield("9");
906 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
907 foreach my $hostitemInfo (@hostitemInfos) {
908 if( $hostitemInfo->{itemnumber} eq $linkeditemnumber ) {
909 push @returnitemsInfo, $hostitemInfo;
914 return @returnitemsInfo;
917 =head2 get_hostitemnumbers_of
919 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
921 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
923 Return a reference on a hash where key is a biblionumber and values are
924 references on array of itemnumbers.
929 sub get_hostitemnumbers_of {
930 my ($biblionumber) = @_;
932 if( !C4::Context->preference('EasyAnalyticalRecords') ) {
936 my $marcrecord = C4::Biblio::GetMarcBiblio({ biblionumber => $biblionumber });
937 return unless $marcrecord;
939 my ( @returnhostitemnumbers, $tag, $biblio_s, $item_s );
941 my $marcflavor = C4::Context->preference('marcflavour');
942 if ( $marcflavor eq 'MARC21' ) {
947 elsif ( $marcflavor eq 'UNIMARC' ) {
953 foreach my $hostfield ( $marcrecord->field($tag) ) {
954 my $hostbiblionumber = $hostfield->subfield($biblio_s);
955 next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield
956 my $linkeditemnumber = $hostfield->subfield($item_s);
957 if ( ! $linkeditemnumber ) {
958 warn "ERROR biblionumber $biblionumber has 773^0, but doesn't have 9";
961 my $is_from_biblio = Koha::Items->search({ itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber });
962 push @returnhostitemnumbers, $linkeditemnumber
966 return @returnhostitemnumbers;
969 =head2 GetHiddenItemnumbers
971 my @itemnumbers_to_hide = GetHiddenItemnumbers({ items => \@items, borcat => $category });
973 Given a list of items it checks which should be hidden from the OPAC given
974 the current configuration. Returns a list of itemnumbers corresponding to
975 those that should be hidden. Optionally takes a borcat parameter for certain borrower types
980 sub GetHiddenItemnumbers {
982 my $items = $params->{items};
983 if (my $exceptions = C4::Context->preference('OpacHiddenItemsExceptions') and $params->{'borcat'}){
984 foreach my $except (split(/\|/, $exceptions)){
985 if ($params->{'borcat'} eq $except){
986 return; # we don't hide anything for this borrower category
992 my $hidingrules = C4::Context->yaml_preference('OpacHiddenItems');
997 my $dbh = C4::Context->dbh;
1000 foreach my $item (@$items) {
1002 # We check each rule
1003 foreach my $field (keys %$hidingrules) {
1005 if (exists $item->{$field}) {
1006 $val = $item->{$field};
1009 my $query = "SELECT $field from items where itemnumber = ?";
1010 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1012 $val = '' unless defined $val;
1014 # If the results matches the values in the yaml file
1015 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1017 # We add the itemnumber to the list
1018 push @resultitems, $item->{'itemnumber'};
1020 # If at least one rule matched for an item, no need to test the others
1025 return @resultitems;
1028 =head1 LIMITED USE FUNCTIONS
1030 The following functions, while part of the public API,
1031 are not exported. This is generally because they are
1032 meant to be used by only one script for a specific
1033 purpose, and should not be used in any other context
1034 without careful thought.
1040 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1042 Returns MARC::Record of the item passed in parameter.
1043 This function is meant for use only in C<cataloguing/additem.pl>,
1044 where it is needed to support that script's MARC-like
1050 my ( $biblionumber, $itemnumber ) = @_;
1052 # GetMarcItem has been revised so that it does the following:
1053 # 1. Gets the item information from the items table.
1054 # 2. Converts it to a MARC field for storage in the bib record.
1056 # The previous behavior was:
1057 # 1. Get the bib record.
1058 # 2. Return the MARC tag corresponding to the item record.
1060 # The difference is that one treats the items row as authoritative,
1061 # while the other treats the MARC representation as authoritative
1062 # under certain circumstances.
1064 my $item = Koha::Items->find($itemnumber) or return;
1066 # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work.
1067 # Also, don't emit a subfield if the underlying field is blank.
1069 return Item2Marc($item->unblessed, $biblionumber);
1073 my ($itemrecord,$biblionumber)=@_;
1076 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1077 } keys %{ $itemrecord }
1079 my $framework = C4::Biblio::GetFrameworkCode( $biblionumber );
1080 my $itemmarc = C4::Biblio::TransformKohaToMarc( $mungeditem, { framework => $framework } );
1081 my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField(
1082 "items.itemnumber", $framework,
1085 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1086 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1087 foreach my $field ($itemmarc->field($itemtag)){
1088 $field->add_subfields(@$unlinked_item_subfields);
1094 =head1 PRIVATE FUNCTIONS AND VARIABLES
1096 The following functions are not meant to be called
1097 directly, but are documented in order to explain
1098 the inner workings of C<C4::Items>.
1102 =head2 _marc_from_item_hash
1104 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1106 Given an item hash representing a complete item record,
1107 create a C<MARC::Record> object containing an embedded
1108 tag representing that item.
1110 The third, optional parameter C<$unlinked_item_subfields> is
1111 an arrayref of subfields (not mapped to C<items> fields per the
1112 framework) to be added to the MARC representation
1117 sub _marc_from_item_hash {
1119 my $frameworkcode = shift;
1120 my $unlinked_item_subfields;
1122 $unlinked_item_subfields = shift;
1125 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1126 # Also, don't emit a subfield if the underlying field is blank.
1127 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1128 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1129 : () } keys %{ $item } };
1131 my $item_marc = MARC::Record->new();
1132 foreach my $item_field ( keys %{$mungeditem} ) {
1133 my ( $tag, $subfield ) = C4::Biblio::GetMarcFromKohaField( $item_field );
1134 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1135 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
1136 foreach my $value (@values){
1137 if ( my $field = $item_marc->field($tag) ) {
1138 $field->add_subfields( $subfield => $value );
1140 my $add_subfields = [];
1141 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1142 $add_subfields = $unlinked_item_subfields;
1144 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
1152 =head2 _repack_item_errors
1154 Add an error message hash generated by C<CheckItemPreSave>
1155 to a list of errors.
1159 sub _repack_item_errors {
1160 my $item_sequence_num = shift;
1161 my $item_ref = shift;
1162 my $error_ref = shift;
1164 my @repacked_errors = ();
1166 foreach my $error_code (sort keys %{ $error_ref }) {
1167 my $repacked_error = {};
1168 $repacked_error->{'item_sequence'} = $item_sequence_num;
1169 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
1170 $repacked_error->{'error_code'} = $error_code;
1171 $repacked_error->{'error_information'} = $error_ref->{$error_code};
1172 push @repacked_errors, $repacked_error;
1175 return @repacked_errors;
1178 =head2 _get_unlinked_item_subfields
1180 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
1184 sub _get_unlinked_item_subfields {
1185 my $original_item_marc = shift;
1186 my $frameworkcode = shift;
1188 my $marcstructure = C4::Biblio::GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
1190 # assume that this record has only one field, and that that
1191 # field contains only the item information
1193 my @fields = $original_item_marc->fields();
1194 if ($#fields > -1) {
1195 my $field = $fields[0];
1196 my $tag = $field->tag();
1197 foreach my $subfield ($field->subfields()) {
1198 if (defined $subfield->[1] and
1199 $subfield->[1] ne '' and
1200 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
1201 push @$subfields, $subfield->[0] => $subfield->[1];
1208 =head2 _get_unlinked_subfields_xml
1210 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
1214 sub _get_unlinked_subfields_xml {
1215 my $unlinked_item_subfields = shift;
1218 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1219 my $marc = MARC::Record->new();
1220 # use of tag 999 is arbitrary, and doesn't need to match the item tag
1221 # used in the framework
1222 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
1223 $marc->encoding("UTF-8");
1224 $xml = $marc->as_xml("USMARC");
1230 =head2 _parse_unlinked_item_subfields_from_xml
1232 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
1236 sub _parse_unlinked_item_subfields_from_xml {
1238 require C4::Charset;
1239 return unless defined $xml and $xml ne "";
1240 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
1241 my $unlinked_subfields = [];
1242 my @fields = $marc->fields();
1243 if ($#fields > -1) {
1244 foreach my $subfield ($fields[0]->subfields()) {
1245 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
1248 return $unlinked_subfields;
1251 =head2 GetAnalyticsCount
1253 $count= &GetAnalyticsCount($itemnumber)
1255 counts Usage of itemnumber in Analytical bibliorecords.
1259 sub GetAnalyticsCount {
1260 my ($itemnumber) = @_;
1262 ### ZOOM search here
1264 $query= "hi=".$itemnumber;
1265 my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX});
1266 my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10);
1270 sub _SearchItems_build_where_fragment {
1273 my $dbh = C4::Context->dbh;
1276 if (exists($filter->{conjunction})) {
1277 my (@where_strs, @where_args);
1278 foreach my $f (@{ $filter->{filters} }) {
1279 my $fragment = _SearchItems_build_where_fragment($f);
1281 push @where_strs, $fragment->{str};
1282 push @where_args, @{ $fragment->{args} };
1287 $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')';
1290 args => \@where_args,
1294 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
1295 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
1296 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
1297 my @operators = qw(= != > < >= <= like);
1298 push @operators, 'not like';
1299 my $field = $filter->{field} // q{};
1300 if ( (0 < grep { $_ eq $field } @columns) or (substr($field, 0, 5) eq 'marc:') ) {
1301 my $op = $filter->{operator};
1302 my $query = $filter->{query};
1303 my $ifnull = $filter->{ifnull};
1305 if (!$op or (0 == grep { $_ eq $op } @operators)) {
1306 $op = '='; # default operator
1310 if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) {
1312 my $marcsubfield = $2;
1313 my ($kohafield) = $dbh->selectrow_array(q|
1314 SELECT kohafield FROM marc_subfield_structure
1315 WHERE tagfield=? AND tagsubfield=? AND frameworkcode=''
1316 |, undef, $marcfield, $marcsubfield);
1319 $column = $kohafield;
1321 # MARC field is not linked to a DB field so we need to use
1322 # ExtractValue on marcxml from biblio_metadata or
1323 # items.more_subfields_xml, depending on the MARC field.
1326 my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber');
1327 if ($marcfield eq $itemfield) {
1328 $sqlfield = 'more_subfields_xml';
1329 $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]';
1331 $sqlfield = 'metadata'; # From biblio_metadata
1332 if ($marcfield < 10) {
1333 $xpath = "//record/controlfield[\@tag=\"$marcfield\"]";
1335 $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]";
1338 $column = "ExtractValue($sqlfield, '$xpath')";
1344 if ( defined $ifnull ) {
1345 $column = "COALESCE($column, ?)";
1348 if (ref $query eq 'ARRAY') {
1351 } elsif ($op eq '!=') {
1355 str => "$column $op (" . join (',', ('?') x @$query) . ")",
1360 str => "$column $op ?",
1365 if ( defined $ifnull ) {
1366 unshift @{ $where_fragment->{args} }, $ifnull;
1371 return $where_fragment;
1376 my ($items, $total) = SearchItems($filter, $params);
1378 Perform a search among items
1380 $filter is a reference to a hash which can be a filter, or a combination of filters.
1382 A filter has the following keys:
1386 =item * field: the name of a SQL column in table items
1388 =item * query: the value to search in this column
1390 =item * operator: comparison operator. Can be one of = != > < >= <= like 'not like'
1394 A combination of filters hash the following keys:
1398 =item * conjunction: 'AND' or 'OR'
1400 =item * filters: array ref of filters
1404 $params is a reference to a hash that can contain the following parameters:
1408 =item * rows: Number of items to return. 0 returns everything (default: 0)
1410 =item * page: Page to return (return items from (page-1)*rows to (page*rows)-1)
1413 =item * sortby: A SQL column name in items table to sort on
1415 =item * sortorder: 'ASC' or 'DESC'
1422 my ($filter, $params) = @_;
1426 return unless ref $filter eq 'HASH';
1427 return unless ref $params eq 'HASH';
1429 # Default parameters
1430 $params->{rows} ||= 0;
1431 $params->{page} ||= 1;
1432 $params->{sortby} ||= 'itemnumber';
1433 $params->{sortorder} ||= 'ASC';
1435 my ($where_str, @where_args);
1436 my $where_fragment = _SearchItems_build_where_fragment($filter);
1437 if ($where_fragment) {
1438 $where_str = $where_fragment->{str};
1439 @where_args = @{ $where_fragment->{args} };
1442 my $dbh = C4::Context->dbh;
1444 SELECT SQL_CALC_FOUND_ROWS items.*
1446 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1447 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1448 LEFT JOIN biblio_metadata ON biblio_metadata.biblionumber = biblio.biblionumber
1451 if (defined $where_str and $where_str ne '') {
1452 $query .= qq{ AND $where_str };
1455 $query .= q{ AND biblio_metadata.format = 'marcxml' AND biblio_metadata.schema = ? };
1456 push @where_args, C4::Context->preference('marcflavour');
1458 my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns;
1459 push @columns, Koha::Database->new()->schema()->resultset('Biblio')->result_source->columns;
1460 push @columns, Koha::Database->new()->schema()->resultset('Biblioitem')->result_source->columns;
1461 my $sortby = (0 < grep {$params->{sortby} eq $_} @columns)
1462 ? $params->{sortby} : 'itemnumber';
1463 my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC';
1464 $query .= qq{ ORDER BY $sortby $sortorder };
1466 my $rows = $params->{rows};
1469 my $offset = $rows * ($params->{page}-1);
1470 $query .= qq { LIMIT ?, ? };
1471 push @limit_args, $offset, $rows;
1474 my $sth = $dbh->prepare($query);
1475 my $rv = $sth->execute(@where_args, @limit_args);
1477 return unless ($rv);
1478 my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() });
1480 return ($sth->fetchall_arrayref({}), $total_rows);
1484 =head1 OTHER FUNCTIONS
1488 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
1490 Find the given $subfield in the given $tag in the given
1491 MARC::Record $record. If the subfield is found, returns
1492 the (indicators, value) pair; otherwise, (undef, undef) is
1496 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
1497 I suggest we export it from this module.
1502 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
1505 if ( $tagfield < 10 ) {
1506 if ( $record->field($tagfield) ) {
1507 push @result, $record->field($tagfield)->data();
1512 foreach my $field ( $record->field($tagfield) ) {
1513 my @subfields = $field->subfields();
1514 foreach my $subfield (@subfields) {
1515 if ( @$subfield[0] eq $insubfield ) {
1516 push @result, @$subfield[1];
1517 $indicator = $field->indicator(1) . $field->indicator(2);
1522 return ( $indicator, @result );
1526 =head2 PrepareItemrecordDisplay
1528 PrepareItemrecordDisplay($bibnum,$itemumber,$defaultvalues,$frameworkcode);
1530 Returns a hash with all the fields for Display a given item data in a template
1532 $defaultvalues should either contain a hashref of values for the new item, or be undefined.
1534 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
1538 sub PrepareItemrecordDisplay {
1540 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
1542 my $dbh = C4::Context->dbh;
1543 $frameworkcode = C4::Biblio::GetFrameworkCode($bibnum) if $bibnum;
1544 my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" );
1546 # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is
1547 # a shared data structure. No plugin (including custom ones) should change
1548 # its contents. See also GetMarcStructure.
1549 my $tagslib = GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } );
1551 # Pick the default location from NewItemsDefaultLocation
1552 if ( C4::Context->preference('NewItemsDefaultLocation') ) {
1553 $defaultvalues //= {};
1554 $defaultvalues->{location} //= C4::Context->preference('NewItemsDefaultLocation');
1557 # return nothing if we don't have found an existing framework.
1558 return q{} unless $tagslib;
1561 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
1565 my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1567 SELECT authorised_value,lib FROM authorised_values
1570 LEFT JOIN authorised_values_branches ON ( id = av_id )
1575 $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit;
1576 $query .= qq{ ORDER BY lib};
1577 my $authorised_values_sth = $dbh->prepare( $query );
1578 foreach my $tag ( sort keys %{$tagslib} ) {
1581 # loop through each subfield
1583 foreach my $subfield (
1584 sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} }
1585 grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty
1586 values %{ $tagslib->{$tag} } )
1588 next unless ( $subfield->{'tab'} );
1589 next if ( $subfield->{'tab'} ne "10" );
1591 $subfield_data{tag} = $tag;
1592 $subfield_data{subfield} = $subfield->{subfield};
1593 $subfield_data{countsubfield} = $cntsubf++;
1594 $subfield_data{kohafield} = $subfield->{kohafield};
1595 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield->{subfield}."_".int(rand(1000000));
1597 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
1598 $subfield_data{marc_lib} = $subfield->{lib};
1599 $subfield_data{mandatory} = $subfield->{mandatory};
1600 $subfield_data{repeatable} = $subfield->{repeatable};
1601 $subfield_data{hidden} = "display:none"
1602 if ( ( $subfield->{hidden} > 4 )
1603 || ( $subfield->{hidden} < -4 ) );
1604 my ( $x, $defaultvalue );
1606 ( $x, $defaultvalue ) = _find_value( $tag, $subfield->{subfield}, $itemrecord );
1608 $defaultvalue = $subfield->{defaultvalue} unless $defaultvalue;
1609 if ( !defined $defaultvalue ) {
1610 $defaultvalue = q||;
1612 $defaultvalue =~ s/"/"/g;
1613 # get today date & replace <<YYYY>>, <<MM>>, <<DD>> if provided in the default value
1614 my $today_dt = dt_from_string;
1615 my $year = $today_dt->strftime('%Y');
1616 my $shortyear = $today_dt->strftime('%y');
1617 my $month = $today_dt->strftime('%m');
1618 my $day = $today_dt->strftime('%d');
1619 $defaultvalue =~ s/<<YYYY>>/$year/g;
1620 $defaultvalue =~ s/<<YY>>/$shortyear/g;
1621 $defaultvalue =~ s/<<MM>>/$month/g;
1622 $defaultvalue =~ s/<<DD>>/$day/g;
1624 # And <<USER>> with surname (?)
1626 ( C4::Context->userenv
1627 ? C4::Context->userenv->{'surname'}
1628 : "superlibrarian" );
1629 $defaultvalue =~ s/<<USER>>/$username/g;
1632 my $maxlength = $subfield->{maxlength};
1634 # search for itemcallnumber if applicable
1635 if ( $subfield->{kohafield} eq 'items.itemcallnumber'
1636 && C4::Context->preference('itemcallnumber') && $itemrecord) {
1637 foreach my $itemcn_pref (split(/,/,C4::Context->preference('itemcallnumber'))){
1638 my $CNtag = substr( $itemcn_pref, 0, 3 );
1639 next unless my $field = $itemrecord->field($CNtag);
1640 my $CNsubfields = substr( $itemcn_pref, 3 );
1641 $CNsubfields = undef if $CNsubfields eq '';
1642 $defaultvalue = $field->as_string( $CNsubfields, ' ');
1643 last if $defaultvalue;
1646 if ( $subfield->{kohafield} eq 'items.itemcallnumber'
1648 && $defaultvalues->{'callnumber'} ) {
1649 if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield->{subfield}) ){
1650 # if the item record exists, only use default value if the item has no callnumber
1651 $defaultvalue = $defaultvalues->{callnumber};
1652 } elsif ( !$itemrecord and $defaultvalues ) {
1653 # if the item record *doesn't* exists, always use the default value
1654 $defaultvalue = $defaultvalues->{callnumber};
1657 if ( ( $subfield->{kohafield} eq 'items.holdingbranch' || $subfield->{kohafield} eq 'items.homebranch' )
1659 && $defaultvalues->{'branchcode'} ) {
1660 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) {
1661 $defaultvalue = $defaultvalues->{branchcode};
1664 if ( ( $subfield->{kohafield} eq 'items.location' )
1666 && $defaultvalues->{'location'} ) {
1668 if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield->{subfield}) ) {
1669 # if the item record exists, only use default value if the item has no locationr
1670 $defaultvalue = $defaultvalues->{location};
1671 } elsif ( !$itemrecord and $defaultvalues ) {
1672 # if the item record *doesn't* exists, always use the default value
1673 $defaultvalue = $defaultvalues->{location};
1676 if ( $subfield->{authorised_value} ) {
1677 my @authorised_values;
1680 # builds list, depending on authorised value...
1682 if ( $subfield->{'authorised_value'} eq "branches" ) {
1683 if ( ( C4::Context->preference("IndependentBranches") )
1684 && !C4::Context->IsSuperLibrarian() ) {
1685 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
1686 $sth->execute( C4::Context->userenv->{branch} );
1687 push @authorised_values, ""
1688 unless ( $subfield->{mandatory} );
1689 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
1690 push @authorised_values, $branchcode;
1691 $authorised_lib{$branchcode} = $branchname;
1694 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
1696 push @authorised_values, ""
1697 unless ( $subfield->{mandatory} );
1698 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
1699 push @authorised_values, $branchcode;
1700 $authorised_lib{$branchcode} = $branchname;
1704 $defaultvalue = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
1705 if ( $defaultvalues and $defaultvalues->{branchcode} ) {
1706 $defaultvalue = $defaultvalues->{branchcode};
1710 } elsif ( $subfield->{authorised_value} eq "itemtypes" ) {
1711 my $itemtypes = Koha::ItemTypes->search_with_localization;
1712 push @authorised_values, "";
1713 while ( my $itemtype = $itemtypes->next ) {
1714 push @authorised_values, $itemtype->itemtype;
1715 $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description;
1717 if ($defaultvalues && $defaultvalues->{'itemtype'}) {
1718 $defaultvalue = $defaultvalues->{'itemtype'};
1722 } elsif ( $subfield->{authorised_value} eq "cn_source" ) {
1723 push @authorised_values, "";
1725 my $class_sources = GetClassSources();
1726 my $default_source = $defaultvalue || C4::Context->preference("DefaultClassificationSource");
1728 foreach my $class_source (sort keys %$class_sources) {
1729 next unless $class_sources->{$class_source}->{'used'} or
1730 ($class_source eq $default_source);
1731 push @authorised_values, $class_source;
1732 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
1735 $defaultvalue = $default_source;
1737 #---- "true" authorised value
1739 $authorised_values_sth->execute(
1740 $subfield->{authorised_value},
1741 $branch_limit ? $branch_limit : ()
1743 push @authorised_values, "";
1744 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
1745 push @authorised_values, $value;
1746 $authorised_lib{$value} = $lib;
1749 $subfield_data{marc_value} = {
1751 values => \@authorised_values,
1752 default => $defaultvalue // q{},
1753 labels => \%authorised_lib,
1755 } elsif ( $subfield->{value_builder} ) {
1757 require Koha::FrameworkPlugin;
1758 my $plugin = Koha::FrameworkPlugin->new({
1759 name => $subfield->{value_builder},
1762 my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id} };
1763 $plugin->build( $pars );
1764 if ( $itemrecord and my $field = $itemrecord->field($tag) ) {
1765 $defaultvalue = $field->subfield($subfield->{subfield}) || q{};
1767 if( !$plugin->errstr ) {
1768 #TODO Move html to template; see report 12176/13397
1769 my $tab= $plugin->noclick? '-1': '';
1770 my $class= $plugin->noclick? ' disabled': '';
1771 my $title= $plugin->noclick? 'No popup': 'Tag editor';
1772 $subfield_data{marc_value} = qq[<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" /><a href="#" id="buttonDot_$subfield_data{id}" class="buttonDot $class" title="$title">...</a>\n].$plugin->javascript;
1774 warn $plugin->errstr;
1775 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />); # supply default input form
1778 elsif ( $tag eq '' ) { # it's an hidden field
1779 $subfield_data{marc_value} = qq(<input type="hidden" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
1781 elsif ( $subfield->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
1782 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
1784 elsif ( length($defaultvalue) > 100
1785 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
1786 300 <= $tag && $tag < 400 && $subfield->{subfield} eq 'a' )
1787 or (C4::Context->preference("marcflavour") eq "MARC21" and
1788 500 <= $tag && $tag < 600 )
1790 # oversize field (textarea)
1791 $subfield_data{marc_value} = qq(<textarea id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength">$defaultvalue</textarea>\n");
1793 $subfield_data{marc_value} = qq(<input type="text" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="50" maxlength="$maxlength" value="$defaultvalue" />);
1795 push( @loop_data, \%subfield_data );
1800 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
1801 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
1804 'itemtagfield' => $itemtagfield,
1805 'itemtagsubfield' => $itemtagsubfield,
1806 'itemnumber' => $itemnumber,
1807 'iteminformation' => \@loop_data
1811 sub ToggleNewStatus {
1812 my ( $params ) = @_;
1813 my @rules = @{ $params->{rules} };
1814 my $report_only = $params->{report_only};
1816 my $dbh = C4::Context->dbh;
1818 my @item_columns = map { "items.$_" } Koha::Items->columns;
1819 my @biblioitem_columns = map { "biblioitems.$_" } Koha::Biblioitems->columns;
1821 for my $rule ( @rules ) {
1822 my $age = $rule->{age};
1823 my $conditions = $rule->{conditions};
1824 my $substitutions = $rule->{substitutions};
1825 foreach ( @$substitutions ) {
1826 ( $_->{item_field} ) = ( $_->{field} =~ /items\.(.*)/ );
1833 LEFT JOIN biblioitems ON biblioitems.biblionumber = items.biblionumber
1836 for my $condition ( @$conditions ) {
1838 grep { $_ eq $condition->{field} } @item_columns
1839 or grep { $_ eq $condition->{field} } @biblioitem_columns
1841 if ( $condition->{value} =~ /\|/ ) {
1842 my @values = split /\|/, $condition->{value};
1843 $query .= qq| AND $condition->{field} IN (|
1844 . join( ',', ('?') x scalar @values )
1846 push @params, @values;
1848 $query .= qq| AND $condition->{field} = ?|;
1849 push @params, $condition->{value};
1853 if ( defined $age ) {
1854 $query .= q| AND TO_DAYS(NOW()) - TO_DAYS(dateaccessioned) >= ? |;
1857 my $sth = $dbh->prepare($query);
1858 $sth->execute( @params );
1859 while ( my $values = $sth->fetchrow_hashref ) {
1860 my $biblionumber = $values->{biblionumber};
1861 my $itemnumber = $values->{itemnumber};
1862 my $item = Koha::Items->find($itemnumber);
1863 for my $substitution ( @$substitutions ) {
1864 my $field = $substitution->{item_field};
1865 my $value = $substitution->{value};
1866 next unless $substitution->{field};
1867 next if ( defined $values->{ $substitution->{item_field} } and $values->{ $substitution->{item_field} } eq $substitution->{value} );
1868 $item->$field($value);
1869 push @{ $report->{$itemnumber} }, $substitution;
1871 $item->store unless $report_only;