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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #use warnings; FIXME - Bug 2505
28 use C4::Dates qw/format_date format_date_in_iso/;
36 use List::MoreUtils qw/any/;
38 use vars qw($VERSION @ISA @EXPORT);
44 @ISA = qw( Exporter );
67 GetItemsByBiblioitemnumber
71 GetItemnumberFromBarcode
72 GetBarcodeFromItemnumber
84 C4::Items - item management functions
88 This module contains an API for manipulating item
89 records in Koha, and is used by cataloguing, circulation,
90 acquisitions, and serials management.
92 A Koha item record is stored in two places: the
93 items table and embedded in a MARC tag in the XML
94 version of the associated bib record in C<biblioitems.marcxml>.
95 This is done to allow the item information to be readily
96 indexed (e.g., by Zebra), but means that each item
97 modification transaction must keep the items table
98 and the MARC XML in sync at all times.
100 Consequently, all code that creates, modifies, or deletes
101 item records B<must> use an appropriate function from
102 C<C4::Items>. If no existing function is suitable, it is
103 better to add one to C<C4::Items> than to use add
104 one-off SQL statements to add or modify items.
106 The items table will be considered authoritative. In other
107 words, if there is ever a discrepancy between the items
108 table and the MARC XML, the items table should be considered
111 =head1 HISTORICAL NOTE
113 Most of the functions in C<C4::Items> were originally in
114 the C<C4::Biblio> module.
116 =head1 CORE EXPORTED FUNCTIONS
118 The following functions are meant for use by users
125 $item = GetItem($itemnumber,$barcode,$serial);
127 Return item information, for a given itemnumber or barcode.
128 The return value is a hashref mapping item column
129 names to values. If C<$serial> is true, include serial publication data.
134 my ($itemnumber,$barcode, $serial) = @_;
135 my $dbh = C4::Context->dbh;
138 my $sth = $dbh->prepare("
140 WHERE itemnumber = ?");
141 $sth->execute($itemnumber);
142 $data = $sth->fetchrow_hashref;
144 my $sth = $dbh->prepare("
148 $sth->execute($barcode);
149 $data = $sth->fetchrow_hashref;
152 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
153 $ssth->execute($data->{'itemnumber'}) ;
154 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
156 #if we don't have an items.itype, use biblioitems.itemtype.
157 if( ! $data->{'itype'} ) {
158 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
159 $sth->execute($data->{'biblionumber'});
160 ($data->{'itype'}) = $sth->fetchrow_array;
167 CartToShelf($itemnumber);
169 Set the current shelving location of the item record
170 to its stored permanent shelving location. This is
171 primarily used to indicate when an item whose current
172 location is a special processing ('PROC') or shelving cart
173 ('CART') location is back in the stacks.
178 my ( $itemnumber ) = @_;
180 unless ( $itemnumber ) {
181 croak "FAILED CartToShelf() - no itemnumber supplied";
184 my $item = GetItem($itemnumber);
185 $item->{location} = $item->{permanent_location};
186 ModItem($item, undef, $itemnumber);
189 =head2 AddItemFromMarc
191 my ($biblionumber, $biblioitemnumber, $itemnumber)
192 = AddItemFromMarc($source_item_marc, $biblionumber);
194 Given a MARC::Record object containing an embedded item
195 record and a biblionumber, create a new item record.
199 sub AddItemFromMarc {
200 my ( $source_item_marc, $biblionumber ) = @_;
201 my $dbh = C4::Context->dbh;
203 # parse item hash from MARC
204 my $frameworkcode = GetFrameworkCode( $biblionumber );
205 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
207 my $localitemmarc=MARC::Record->new;
208 $localitemmarc->append_fields($source_item_marc->field($itemtag));
209 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
210 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
211 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
216 my ($biblionumber, $biblioitemnumber, $itemnumber)
217 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
219 Given a hash containing item column names as keys,
220 create a new Koha item record.
222 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
223 do not need to be supplied for general use; they exist
224 simply to allow them to be picked up from AddItemFromMarc.
226 The final optional parameter, C<$unlinked_item_subfields>, contains
227 an arrayref containing subfields present in the original MARC
228 representation of the item (e.g., from the item editor) that are
229 not mapped to C<items> columns directly but should instead
230 be stored in C<items.more_subfields_xml> and included in
231 the biblio items tag for display and indexing.
237 my $biblionumber = shift;
239 my $dbh = @_ ? shift : C4::Context->dbh;
240 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
241 my $unlinked_item_subfields;
243 $unlinked_item_subfields = shift
246 # needs old biblionumber and biblioitemnumber
247 $item->{'biblionumber'} = $biblionumber;
248 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
249 $sth->execute( $item->{'biblionumber'} );
250 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
252 _set_defaults_for_add($item);
253 _set_derived_columns_for_add($item);
254 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
255 # FIXME - checks here
256 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
257 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
258 $itype_sth->execute( $item->{'biblionumber'} );
259 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
262 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
263 $item->{'itemnumber'} = $itemnumber;
265 ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
267 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
269 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
272 =head2 AddItemBatchFromMarc
274 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
275 $biblionumber, $biblioitemnumber, $frameworkcode);
277 Efficiently create item records from a MARC biblio record with
278 embedded item fields. This routine is suitable for batch jobs.
280 This API assumes that the bib record has already been
281 saved to the C<biblio> and C<biblioitems> tables. It does
282 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
283 are populated, but it will do so via a call to ModBibiloMarc.
285 The goal of this API is to have a similar effect to using AddBiblio
286 and AddItems in succession, but without inefficient repeated
287 parsing of the MARC XML bib record.
289 This function returns an arrayref of new itemsnumbers and an arrayref of item
290 errors encountered during the processing. Each entry in the errors
291 list is a hashref containing the following keys:
297 Sequence number of original item tag in the MARC record.
301 Item barcode, provide to assist in the construction of
302 useful error messages.
304 =item error_condition
306 Code representing the error condition. Can be 'duplicate_barcode',
307 'invalid_homebranch', or 'invalid_holdingbranch'.
309 =item error_information
311 Additional information appropriate to the error condition.
317 sub AddItemBatchFromMarc {
318 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
320 my @itemnumbers = ();
322 my $dbh = C4::Context->dbh;
324 # loop through the item tags and start creating items
325 my @bad_item_fields = ();
326 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
327 my $item_sequence_num = 0;
328 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
329 $item_sequence_num++;
330 # we take the item field and stick it into a new
331 # MARC record -- this is required so far because (FIXME)
332 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
333 # and there is no TransformMarcFieldToKoha
334 my $temp_item_marc = MARC::Record->new();
335 $temp_item_marc->append_fields($item_field);
337 # add biblionumber and biblioitemnumber
338 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
339 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
340 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
341 $item->{'biblionumber'} = $biblionumber;
342 $item->{'biblioitemnumber'} = $biblioitemnumber;
344 # check for duplicate barcode
345 my %item_errors = CheckItemPreSave($item);
347 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
348 push @bad_item_fields, $item_field;
352 _set_defaults_for_add($item);
353 _set_derived_columns_for_add($item);
354 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
355 warn $error if $error;
356 push @itemnumbers, $itemnumber; # FIXME not checking error
357 $item->{'itemnumber'} = $itemnumber;
359 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
361 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
362 $item_field->replace_with($new_item_marc->field($itemtag));
365 # remove any MARC item fields for rejected items
366 foreach my $item_field (@bad_item_fields) {
367 $record->delete_field($item_field);
370 # update the MARC biblio
371 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
373 return (\@itemnumbers, \@errors);
376 =head2 ModItemFromMarc
378 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
380 This function updates an item record based on a supplied
381 C<MARC::Record> object containing an embedded item field.
382 This API is meant for the use of C<additem.pl>; for
383 other purposes, C<ModItem> should be used.
385 This function uses the hash %default_values_for_mod_from_marc,
386 which contains default values for item fields to
387 apply when modifying an item. This is needed beccause
388 if an item field's value is cleared, TransformMarcToKoha
389 does not include the column in the
390 hash that's passed to ModItem, which without
391 use of this hash makes it impossible to clear
392 an item field's value. See bug 2466.
394 Note that only columns that can be directly
395 changed from the cataloging and serials
396 item editors are included in this hash.
400 my %default_values_for_mod_from_marc = (
402 booksellerid => undef,
404 'items.cn_source' => undef,
407 # dateaccessioned => undef,
409 holdingbranch => undef,
411 itemcallnumber => undef,
420 replacementprice => undef,
421 replacementpricedate => undef,
424 stocknumber => undef,
429 sub ModItemFromMarc {
430 my $item_marc = shift;
431 my $biblionumber = shift;
432 my $itemnumber = shift;
434 my $dbh = C4::Context->dbh;
435 my $frameworkcode = GetFrameworkCode($biblionumber);
436 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
438 my $localitemmarc = MARC::Record->new;
439 $localitemmarc->append_fields( $item_marc->field($itemtag) );
440 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
441 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
442 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
444 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
446 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
451 ModItem({ column => $newvalue }, $biblionumber,
452 $itemnumber[, $original_item_marc]);
454 Change one or more columns in an item record and update
455 the MARC representation of the item.
457 The first argument is a hashref mapping from item column
458 names to the new values. The second and third arguments
459 are the biblionumber and itemnumber, respectively.
461 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
462 an arrayref containing subfields present in the original MARC
463 representation of the item (e.g., from the item editor) that are
464 not mapped to C<items> columns directly but should instead
465 be stored in C<items.more_subfields_xml> and included in
466 the biblio items tag for display and indexing.
468 If one of the changed columns is used to calculate
469 the derived value of a column such as C<items.cn_sort>,
470 this routine will perform the necessary calculation
477 my $biblionumber = shift;
478 my $itemnumber = shift;
480 # if $biblionumber is undefined, get it from the current item
481 unless (defined $biblionumber) {
482 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
485 my $dbh = @_ ? shift : C4::Context->dbh;
486 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
488 my $unlinked_item_subfields;
490 $unlinked_item_subfields = shift;
491 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
494 $item->{'itemnumber'} = $itemnumber or return undef;
495 _set_derived_columns_for_mod($item);
496 _do_column_fixes_for_mod($item);
499 # attempt to change itemnumber
500 # attempt to change biblionumber (if we want
501 # an API to relink an item to a different bib,
502 # it should be a separate function)
505 _koha_modify_item($item);
507 # request that bib be reindexed so that searching on current
508 # item status is possible
509 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
511 logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
514 =head2 ModItemTransfer
516 ModItemTransfer($itenumber, $frombranch, $tobranch);
518 Marks an item as being transferred from one branch
523 sub ModItemTransfer {
524 my ( $itemnumber, $frombranch, $tobranch ) = @_;
526 my $dbh = C4::Context->dbh;
528 #new entry in branchtransfers....
529 my $sth = $dbh->prepare(
530 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
531 VALUES (?, ?, NOW(), ?)");
532 $sth->execute($itemnumber, $frombranch, $tobranch);
534 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
535 ModDateLastSeen($itemnumber);
539 =head2 ModDateLastSeen
541 ModDateLastSeen($itemnum);
543 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
544 C<$itemnum> is the item number
548 sub ModDateLastSeen {
549 my ($itemnumber) = @_;
551 my $today = C4::Dates->new();
552 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
557 DelItem($dbh, $biblionumber, $itemnumber);
559 Exported function (core API) for deleting an item record in Koha.
564 my ( $dbh, $biblionumber, $itemnumber ) = @_;
566 # FIXME check the item has no current issues
568 _koha_delete_item( $dbh, $itemnumber );
570 # get the MARC record
571 my $record = GetMarcBiblio($biblionumber);
572 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
575 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
576 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
578 #search item field code
579 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
582 =head2 CheckItemPreSave
584 my $item_ref = TransformMarcToKoha($marc, 'items');
586 my %errors = CheckItemPreSave($item_ref);
587 if (exists $errors{'duplicate_barcode'}) {
588 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
589 } elsif (exists $errors{'invalid_homebranch'}) {
590 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
591 } elsif (exists $errors{'invalid_holdingbranch'}) {
592 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
597 Given a hashref containing item fields, determine if it can be
598 inserted or updated in the database. Specifically, checks for
599 database integrity issues, and returns a hash containing any
600 of the following keys, if applicable.
604 =item duplicate_barcode
606 Barcode, if it duplicates one already found in the database.
608 =item invalid_homebranch
610 Home branch, if not defined in branches table.
612 =item invalid_holdingbranch
614 Holding branch, if not defined in branches table.
618 This function does NOT implement any policy-related checks,
619 e.g., whether current operator is allowed to save an
620 item that has a given branch code.
624 sub CheckItemPreSave {
625 my $item_ref = shift;
629 # check for duplicate barcode
630 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
631 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
632 if ($existing_itemnumber) {
633 if (!exists $item_ref->{'itemnumber'} # new item
634 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
635 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
640 # check for valid home branch
641 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
642 my $branch_name = GetBranchName($item_ref->{'homebranch'});
643 unless (defined $branch_name) {
644 # relies on fact that branches.branchname is a non-NULL column,
645 # so GetBranchName returns undef only if branch does not exist
646 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
650 # check for valid holding branch
651 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
652 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
653 unless (defined $branch_name) {
654 # relies on fact that branches.branchname is a non-NULL column,
655 # so GetBranchName returns undef only if branch does not exist
656 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
664 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
666 The following functions provide various ways of
667 getting an item record, a set of item records, or
668 lists of authorized values for certain item fields.
670 Some of the functions in this group are candidates
671 for refactoring -- for example, some of the code
672 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
673 has copy-and-paste work.
679 $itemstatushash = GetItemStatus($fwkcode);
681 Returns a list of valid values for the
682 C<items.notforloan> field.
684 NOTE: does B<not> return an individual item's
687 Can be MARC dependant.
689 But basically could be can be loan or not
690 Create a status selector with the following code
692 =head3 in PERL SCRIPT
694 my $itemstatushash = getitemstatus;
696 foreach my $thisstatus (keys %$itemstatushash) {
697 my %row =(value => $thisstatus,
698 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
700 push @itemstatusloop, \%row;
702 $template->param(statusloop=>\@itemstatusloop);
706 <select name="statusloop">
707 <option value="">Default</option>
708 <!-- TMPL_LOOP name="statusloop" -->
709 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
717 # returns a reference to a hash of references to status...
720 my $dbh = C4::Context->dbh;
722 $fwk = '' unless ($fwk);
723 my ( $tag, $subfield ) =
724 GetMarcFromKohaField( "items.notforloan", $fwk );
725 if ( $tag and $subfield ) {
728 "SELECT authorised_value
729 FROM marc_subfield_structure
735 $sth->execute( $tag, $subfield, $fwk );
736 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
739 "SELECT authorised_value,lib
740 FROM authorised_values
745 $authvalsth->execute($authorisedvaluecat);
746 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
747 $itemstatus{$authorisedvalue} = $lib;
761 $itemstatus{"1"} = "Not For Loan";
765 =head2 GetItemLocation
767 $itemlochash = GetItemLocation($fwk);
769 Returns a list of valid values for the
770 C<items.location> field.
772 NOTE: does B<not> return an individual item's
775 where fwk stands for an optional framework code.
776 Create a location selector with the following code
778 =head3 in PERL SCRIPT
780 my $itemlochash = getitemlocation;
782 foreach my $thisloc (keys %$itemlochash) {
783 my $selected = 1 if $thisbranch eq $branch;
784 my %row =(locval => $thisloc,
785 selected => $selected,
786 locname => $itemlochash->{$thisloc},
788 push @itemlocloop, \%row;
790 $template->param(itemlocationloop => \@itemlocloop);
794 <select name="location">
795 <option value="">Default</option>
796 <!-- TMPL_LOOP name="itemlocationloop" -->
797 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
803 sub GetItemLocation {
805 # returns a reference to a hash of references to location...
808 my $dbh = C4::Context->dbh;
810 $fwk = '' unless ($fwk);
811 my ( $tag, $subfield ) =
812 GetMarcFromKohaField( "items.location", $fwk );
813 if ( $tag and $subfield ) {
816 "SELECT authorised_value
817 FROM marc_subfield_structure
822 $sth->execute( $tag, $subfield, $fwk );
823 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
826 "SELECT authorised_value,lib
827 FROM authorised_values
831 $authvalsth->execute($authorisedvaluecat);
832 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
833 $itemlocation{$authorisedvalue} = $lib;
835 return \%itemlocation;
847 $itemlocation{"1"} = "Not For Loan";
848 return \%itemlocation;
853 $items = GetLostItems( $where, $orderby );
855 This function gets a list of lost items.
861 C<$where> is a hashref. it containts a field of the items table as key
862 and the value to match as value. For example:
864 { barcode => 'abc123',
865 homebranch => 'CPL', }
867 C<$orderby> is a field of the items table by which the resultset
872 C<$items> is a reference to an array full of hashrefs with columns
873 from the "items" table as keys.
875 =item usage in the perl script:
877 my $where = { barcode => '0001548' };
878 my $items = GetLostItems( $where, "homebranch" );
879 $template->param( itemsloop => $items );
886 # Getting input args.
889 my $dbh = C4::Context->dbh;
894 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
895 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
896 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
898 authorised_values.category = 'LOST'
899 AND itemlost IS NOT NULL
902 my @query_parameters;
903 foreach my $key (keys %$where) {
904 $query .= " AND $key LIKE ?";
905 push @query_parameters, "%$where->{$key}%";
907 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
909 if ( defined $orderby && grep($orderby, @ordervalues)) {
910 $query .= ' ORDER BY '.$orderby;
913 my $sth = $dbh->prepare($query);
914 $sth->execute( @query_parameters );
916 while ( my $row = $sth->fetchrow_hashref ){
922 =head2 GetItemsForInventory
924 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
925 $location, $itemtype $datelastseen, $branch,
926 $offset, $size, $statushash);
928 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
930 The sub returns a reference to a list of hashes, each containing
931 itemnumber, author, title, barcode, item callnumber, and date last
932 seen. It is ordered by callnumber then title.
934 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
935 the datelastseen can be used to specify that you want to see items not seen since a past date only.
936 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
937 $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.
941 sub GetItemsForInventory {
942 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
943 my $dbh = C4::Context->dbh;
944 my ( @bind_params, @where_strings );
946 my $query = <<'END_SQL';
947 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
949 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
950 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
953 for my $authvfield (keys %$statushash){
954 if ( scalar @{$statushash->{$authvfield}} > 0 ){
955 my $joinedvals = join ',', @{$statushash->{$authvfield}};
956 push @where_strings, "$authvfield in (" . $joinedvals . ")";
962 push @where_strings, 'itemcallnumber >= ?';
963 push @bind_params, $minlocation;
967 push @where_strings, 'itemcallnumber <= ?';
968 push @bind_params, $maxlocation;
972 $datelastseen = format_date_in_iso($datelastseen);
973 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
974 push @bind_params, $datelastseen;
978 push @where_strings, 'items.location = ?';
979 push @bind_params, $location;
983 if($branch eq "homebranch"){
984 push @where_strings, 'items.homebranch = ?';
986 push @where_strings, 'items.holdingbranch = ?';
988 push @bind_params, $branchcode;
992 push @where_strings, 'biblioitems.itemtype = ?';
993 push @bind_params, $itemtype;
996 if ( $ignoreissued) {
997 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
998 push @where_strings, 'issues.date_due IS NULL';
1001 if ( @where_strings ) {
1003 $query .= join ' AND ', @where_strings;
1005 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1006 my $sth = $dbh->prepare($query);
1007 $sth->execute( @bind_params );
1011 while ( my $row = $sth->fetchrow_hashref ) {
1012 $offset-- if ($offset);
1013 $row->{datelastseen}=format_date($row->{datelastseen});
1014 if ( ( !$offset ) && $size ) {
1015 push @results, $row;
1022 =head2 GetItemsCount
1024 $count = &GetItemsCount( $biblionumber);
1026 This function return count of item with $biblionumber
1031 my ( $biblionumber ) = @_;
1032 my $dbh = C4::Context->dbh;
1033 my $query = "SELECT count(*)
1035 WHERE biblionumber=?";
1036 my $sth = $dbh->prepare($query);
1037 $sth->execute($biblionumber);
1038 my $count = $sth->fetchrow;
1042 =head2 GetItemInfosOf
1044 GetItemInfosOf(@itemnumbers);
1048 sub GetItemInfosOf {
1049 my @itemnumbers = @_;
1054 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1056 return get_infos_of( $query, 'itemnumber' );
1059 =head2 GetItemsByBiblioitemnumber
1061 GetItemsByBiblioitemnumber($biblioitemnumber);
1063 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1064 Called by C<C4::XISBN>
1068 sub GetItemsByBiblioitemnumber {
1069 my ( $bibitem ) = @_;
1070 my $dbh = C4::Context->dbh;
1071 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1072 # Get all items attached to a biblioitem
1075 $sth->execute($bibitem) || die $sth->errstr;
1076 while ( my $data = $sth->fetchrow_hashref ) {
1077 # Foreach item, get circulation information
1078 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1079 WHERE itemnumber = ?
1080 AND issues.borrowernumber = borrowers.borrowernumber"
1082 $sth2->execute( $data->{'itemnumber'} );
1083 if ( my $data2 = $sth2->fetchrow_hashref ) {
1084 # if item is out, set the due date and who it is out too
1085 $data->{'date_due'} = $data2->{'date_due'};
1086 $data->{'cardnumber'} = $data2->{'cardnumber'};
1087 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1090 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1091 $data->{'date_due'} = '';
1093 # Find the last 3 people who borrowed this item.
1094 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1095 AND old_issues.borrowernumber = borrowers.borrowernumber
1096 ORDER BY returndate desc,timestamp desc LIMIT 3";
1097 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1098 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1100 while ( my $data2 = $sth2->fetchrow_hashref ) {
1101 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1102 $data->{"card$i2"} = $data2->{'cardnumber'};
1103 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1106 push(@results,$data);
1113 @results = GetItemsInfo($biblionumber, $type);
1115 Returns information about books with the given biblionumber.
1117 C<$type> may be either C<intra> or anything else. If it is not set to
1118 C<intra>, then the search will exclude lost, very overdue, and
1121 C<GetItemsInfo> returns a list of references-to-hash. Each element
1122 contains a number of keys. Most of them are table items from the
1123 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1124 Koha database. Other keys include:
1128 =item C<$data-E<gt>{branchname}>
1130 The name (not the code) of the branch to which the book belongs.
1132 =item C<$data-E<gt>{datelastseen}>
1134 This is simply C<items.datelastseen>, except that while the date is
1135 stored in YYYY-MM-DD format in the database, here it is converted to
1136 DD/MM/YYYY format. A NULL date is returned as C<//>.
1138 =item C<$data-E<gt>{datedue}>
1140 =item C<$data-E<gt>{class}>
1142 This is the concatenation of C<biblioitems.classification>, the book's
1143 Dewey code, and C<biblioitems.subclass>.
1145 =item C<$data-E<gt>{ocount}>
1147 I think this is the number of copies of the book available.
1149 =item C<$data-E<gt>{order}>
1151 If this is set, it is set to C<One Order>.
1158 my ( $biblionumber, $type ) = @_;
1159 my $dbh = C4::Context->dbh;
1160 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1166 biblioitems.itemtype,
1169 biblioitems.publicationyear,
1170 biblioitems.publishercode,
1171 biblioitems.volumedate,
1172 biblioitems.volumedesc,
1175 items.notforloan as itemnotforloan,
1176 itemtypes.description,
1177 itemtypes.notforloan as notforloan_per_itemtype,
1180 LEFT JOIN branches ON items.homebranch = branches.branchcode
1181 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1182 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1183 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1184 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1185 $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1186 my $sth = $dbh->prepare($query);
1187 $sth->execute($biblionumber);
1192 my $isth = $dbh->prepare(
1193 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1194 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1195 WHERE itemnumber = ?"
1197 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1198 while ( my $data = $sth->fetchrow_hashref ) {
1201 $isth->execute( $data->{'itemnumber'} );
1202 if ( my $idata = $isth->fetchrow_hashref ) {
1203 $data->{borrowernumber} = $idata->{borrowernumber};
1204 $data->{cardnumber} = $idata->{cardnumber};
1205 $data->{surname} = $idata->{surname};
1206 $data->{firstname} = $idata->{firstname};
1207 $datedue = $idata->{'date_due'};
1208 if (C4::Context->preference("IndependantBranches")){
1209 my $userenv = C4::Context->userenv;
1210 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1211 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1215 if ( $data->{'serial'}) {
1216 $ssth->execute($data->{'itemnumber'}) ;
1217 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1220 if ( $datedue eq '' ) {
1221 my ( $restype, $reserves ) =
1222 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1223 # Previous conditional check with if ($restype) is not needed because a true
1224 # result for one item will result in subsequent items defaulting to this true
1226 $count_reserves = $restype;
1228 #get branch information.....
1229 my $bsth = $dbh->prepare(
1230 "SELECT * FROM branches WHERE branchcode = ?
1233 $bsth->execute( $data->{'holdingbranch'} );
1234 if ( my $bdata = $bsth->fetchrow_hashref ) {
1235 $data->{'branchname'} = $bdata->{'branchname'};
1237 $data->{'datedue'} = $datedue;
1238 $data->{'count_reserves'} = $count_reserves;
1240 # get notforloan complete status if applicable
1241 my $sthnflstatus = $dbh->prepare(
1242 'SELECT authorised_value
1243 FROM marc_subfield_structure
1244 WHERE kohafield="items.notforloan"
1248 $sthnflstatus->execute;
1249 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1250 if ($authorised_valuecode) {
1251 $sthnflstatus = $dbh->prepare(
1252 "SELECT lib FROM authorised_values
1254 AND authorised_value=?"
1256 $sthnflstatus->execute( $authorised_valuecode,
1257 $data->{itemnotforloan} );
1258 my ($lib) = $sthnflstatus->fetchrow;
1259 $data->{notforloanvalue} = $lib;
1262 # get restricted status and description if applicable
1263 my $restrictedstatus = $dbh->prepare(
1264 'SELECT authorised_value
1265 FROM marc_subfield_structure
1266 WHERE kohafield="items.restricted"
1270 $restrictedstatus->execute;
1271 ($authorised_valuecode) = $restrictedstatus->fetchrow;
1272 if ($authorised_valuecode) {
1273 $restrictedstatus = $dbh->prepare(
1274 "SELECT lib,lib_opac FROM authorised_values
1276 AND authorised_value=?"
1278 $restrictedstatus->execute( $authorised_valuecode,
1279 $data->{restricted} );
1281 if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1282 $data->{restricted} = $rstdata->{'lib'};
1283 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1287 # my stack procedures
1288 my $stackstatus = $dbh->prepare(
1289 'SELECT authorised_value
1290 FROM marc_subfield_structure
1291 WHERE kohafield="items.stack"
1294 $stackstatus->execute;
1296 ($authorised_valuecode) = $stackstatus->fetchrow;
1297 if ($authorised_valuecode) {
1298 $stackstatus = $dbh->prepare(
1300 FROM authorised_values
1302 AND authorised_value=?
1305 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1306 my ($lib) = $stackstatus->fetchrow;
1307 $data->{stack} = $lib;
1309 # Find the last 3 people who borrowed this item.
1310 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1311 WHERE itemnumber = ?
1312 AND old_issues.borrowernumber = borrowers.borrowernumber
1313 ORDER BY returndate DESC
1315 $sth2->execute($data->{'itemnumber'});
1317 while (my $data2 = $sth2->fetchrow_hashref()) {
1318 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1319 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1320 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1324 $results[$i] = $data;
1328 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1334 =head2 GetItemsLocationInfo
1336 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1338 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1340 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1344 =item C<$data-E<gt>{homebranch}>
1346 Branch Name of the item's homebranch
1348 =item C<$data-E<gt>{holdingbranch}>
1350 Branch Name of the item's holdingbranch
1352 =item C<$data-E<gt>{location}>
1354 Item's shelving location code
1356 =item C<$data-E<gt>{location_intranet}>
1358 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1360 =item C<$data-E<gt>{location_opac}>
1362 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1365 =item C<$data-E<gt>{itemcallnumber}>
1367 Item's itemcallnumber
1369 =item C<$data-E<gt>{cn_sort}>
1371 Item's call number normalized for sorting
1377 sub GetItemsLocationInfo {
1378 my $biblionumber = shift;
1381 my $dbh = C4::Context->dbh;
1382 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1383 location, itemcallnumber, cn_sort
1384 FROM items, branches as a, branches as b
1385 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1386 AND biblionumber = ?
1387 ORDER BY cn_sort ASC";
1388 my $sth = $dbh->prepare($query);
1389 $sth->execute($biblionumber);
1391 while ( my $data = $sth->fetchrow_hashref ) {
1392 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1393 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1394 push @results, $data;
1400 =head2 GetLastAcquisitions
1402 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1403 'itemtypes' => ('BK','BD')}, 10);
1407 sub GetLastAcquisitions {
1408 my ($data,$max) = @_;
1410 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1412 my $number_of_branches = @{$data->{branches}};
1413 my $number_of_itemtypes = @{$data->{itemtypes}};
1416 my @where = ('WHERE 1 ');
1417 $number_of_branches and push @where
1418 , 'AND holdingbranch IN ('
1419 , join(',', ('?') x $number_of_branches )
1423 $number_of_itemtypes and push @where
1424 , "AND $itemtype IN ("
1425 , join(',', ('?') x $number_of_itemtypes )
1429 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1430 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1431 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1433 GROUP BY biblio.biblionumber
1434 ORDER BY dateaccessioned DESC LIMIT $max";
1436 my $dbh = C4::Context->dbh;
1437 my $sth = $dbh->prepare($query);
1439 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1442 while( my $row = $sth->fetchrow_hashref){
1443 push @results, {date => $row->{dateaccessioned}
1444 , biblionumber => $row->{biblionumber}
1445 , title => $row->{title}};
1451 =head2 get_itemnumbers_of
1453 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1455 Given a list of biblionumbers, return the list of corresponding itemnumbers
1456 for each biblionumber.
1458 Return a reference on a hash where keys are biblionumbers and values are
1459 references on array of itemnumbers.
1463 sub get_itemnumbers_of {
1464 my @biblionumbers = @_;
1466 my $dbh = C4::Context->dbh;
1472 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1474 my $sth = $dbh->prepare($query);
1475 $sth->execute(@biblionumbers);
1479 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1480 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1483 return \%itemnumbers_of;
1486 =head2 GetItemnumberFromBarcode
1488 $result = GetItemnumberFromBarcode($barcode);
1492 sub GetItemnumberFromBarcode {
1494 my $dbh = C4::Context->dbh;
1497 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1498 $rq->execute($barcode);
1499 my ($result) = $rq->fetchrow;
1503 =head2 GetBarcodeFromItemnumber
1505 $result = GetBarcodeFromItemnumber($itemnumber);
1509 sub GetBarcodeFromItemnumber {
1510 my ($itemnumber) = @_;
1511 my $dbh = C4::Context->dbh;
1514 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1515 $rq->execute($itemnumber);
1516 my ($result) = $rq->fetchrow;
1520 =head2 GetHiddenItemnumbers
1524 $result = GetHiddenItemnumbers(@items);
1530 sub GetHiddenItemnumbers {
1534 my $yaml = C4::Context->preference('OpacHiddenItems');
1537 $hidingrules = YAML::Load($yaml);
1540 warn "Unable to parse OpacHiddenItems syspref : $@";
1543 my $dbh = C4::Context->dbh;
1546 foreach my $item (@items) {
1548 # We check each rule
1549 foreach my $field (keys %$hidingrules) {
1550 my $query = "SELECT $field from items where itemnumber = ?";
1551 my $sth = $dbh->prepare($query);
1552 $sth->execute($item->{'itemnumber'});
1553 my ($result) = $sth->fetchrow;
1555 # If the results matches the values in the yaml file
1556 if (any { $result eq $_ } @{$hidingrules->{$field}}) {
1558 # We add the itemnumber to the list
1559 push @resultitems, $item->{'itemnumber'};
1561 # If at least one rule matched for an item, no need to test the others
1566 return @resultitems;
1571 =head3 get_item_authorised_values
1573 find the types and values for all authorised values assigned to this item.
1575 parameters: itemnumber
1577 returns: a hashref malling the authorised value to the value set for this itemnumber
1579 $authorised_values = {
1585 'RESTRICTED' => undef,
1588 'branches' => 'CPL',
1589 'cn_source' => undef,
1590 'itemtypes' => 'SER',
1593 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1597 sub get_item_authorised_values {
1598 my $itemnumber = shift;
1600 # assume that these entries in the authorised_value table are item level.
1601 my $query = q(SELECT distinct authorised_value, kohafield
1602 FROM marc_subfield_structure
1603 WHERE kohafield like 'item%'
1604 AND authorised_value != '' );
1606 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1607 my $iteminfo = GetItem( $itemnumber );
1608 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1610 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1611 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1612 $field =~ s/^items\.//;
1613 if ( exists $iteminfo->{ $field } ) {
1614 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1617 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1621 =head3 get_authorised_value_images
1623 find a list of icons that are appropriate for display based on the
1624 authorised values for a biblio.
1626 parameters: listref of authorised values, such as comes from
1627 get_item_authorised_values or
1628 from C4::Biblio::get_biblio_authorised_values
1630 returns: listref of hashrefs for each image. Each hashref looks like this:
1632 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1637 Notes: Currently, I put on the full path to the images on the staff
1638 side. This should either be configurable or not done at all. Since I
1639 have to deal with 'intranet' or 'opac' in
1640 get_biblio_authorised_values, perhaps I should be passing it in.
1644 sub get_authorised_value_images {
1645 my $authorised_values = shift;
1649 my $authorised_value_list = GetAuthorisedValues();
1650 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1651 foreach my $this_authorised_value ( @$authorised_value_list ) {
1652 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1653 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1654 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1655 if ( defined $this_authorised_value->{'imageurl'} ) {
1656 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1657 label => $this_authorised_value->{'lib'},
1658 category => $this_authorised_value->{'category'},
1659 value => $this_authorised_value->{'authorised_value'}, };
1664 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1669 =head1 LIMITED USE FUNCTIONS
1671 The following functions, while part of the public API,
1672 are not exported. This is generally because they are
1673 meant to be used by only one script for a specific
1674 purpose, and should not be used in any other context
1675 without careful thought.
1681 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1683 Returns MARC::Record of the item passed in parameter.
1684 This function is meant for use only in C<cataloguing/additem.pl>,
1685 where it is needed to support that script's MARC-like
1691 my ( $biblionumber, $itemnumber ) = @_;
1693 # GetMarcItem has been revised so that it does the following:
1694 # 1. Gets the item information from the items table.
1695 # 2. Converts it to a MARC field for storage in the bib record.
1697 # The previous behavior was:
1698 # 1. Get the bib record.
1699 # 2. Return the MARC tag corresponding to the item record.
1701 # The difference is that one treats the items row as authoritative,
1702 # while the other treats the MARC representation as authoritative
1703 # under certain circumstances.
1705 my $itemrecord = GetItem($itemnumber);
1707 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1708 # Also, don't emit a subfield if the underlying field is blank.
1711 return Item2Marc($itemrecord,$biblionumber);
1715 my ($itemrecord,$biblionumber)=@_;
1718 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1719 } keys %{ $itemrecord }
1721 my $itemmarc = TransformKohaToMarc($mungeditem);
1722 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1724 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1725 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1726 foreach my $field ($itemmarc->field($itemtag)){
1727 $field->add_subfields(@$unlinked_item_subfields);
1733 =head1 PRIVATE FUNCTIONS AND VARIABLES
1735 The following functions are not meant to be called
1736 directly, but are documented in order to explain
1737 the inner workings of C<C4::Items>.
1741 =head2 %derived_columns
1743 This hash keeps track of item columns that
1744 are strictly derived from other columns in
1745 the item record and are not meant to be set
1748 Each key in the hash should be the name of a
1749 column (as named by TransformMarcToKoha). Each
1750 value should be hashref whose keys are the
1751 columns on which the derived column depends. The
1752 hashref should also contain a 'BUILDER' key
1753 that is a reference to a sub that calculates
1758 my %derived_columns = (
1759 'items.cn_sort' => {
1760 'itemcallnumber' => 1,
1761 'items.cn_source' => 1,
1762 'BUILDER' => \&_calc_items_cn_sort,
1766 =head2 _set_derived_columns_for_add
1768 _set_derived_column_for_add($item);
1770 Given an item hash representing a new item to be added,
1771 calculate any derived columns. Currently the only
1772 such column is C<items.cn_sort>.
1776 sub _set_derived_columns_for_add {
1779 foreach my $column (keys %derived_columns) {
1780 my $builder = $derived_columns{$column}->{'BUILDER'};
1781 my $source_values = {};
1782 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1783 next if $source_column eq 'BUILDER';
1784 $source_values->{$source_column} = $item->{$source_column};
1786 $builder->($item, $source_values);
1790 =head2 _set_derived_columns_for_mod
1792 _set_derived_column_for_mod($item);
1794 Given an item hash representing a new item to be modified.
1795 calculate any derived columns. Currently the only
1796 such column is C<items.cn_sort>.
1798 This routine differs from C<_set_derived_columns_for_add>
1799 in that it needs to handle partial item records. In other
1800 words, the caller of C<ModItem> may have supplied only one
1801 or two columns to be changed, so this function needs to
1802 determine whether any of the columns to be changed affect
1803 any of the derived columns. Also, if a derived column
1804 depends on more than one column, but the caller is not
1805 changing all of then, this routine retrieves the unchanged
1806 values from the database in order to ensure a correct
1811 sub _set_derived_columns_for_mod {
1814 foreach my $column (keys %derived_columns) {
1815 my $builder = $derived_columns{$column}->{'BUILDER'};
1816 my $source_values = {};
1817 my %missing_sources = ();
1818 my $must_recalc = 0;
1819 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1820 next if $source_column eq 'BUILDER';
1821 if (exists $item->{$source_column}) {
1823 $source_values->{$source_column} = $item->{$source_column};
1825 $missing_sources{$source_column} = 1;
1829 foreach my $source_column (keys %missing_sources) {
1830 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1832 $builder->($item, $source_values);
1837 =head2 _do_column_fixes_for_mod
1839 _do_column_fixes_for_mod($item);
1841 Given an item hashref containing one or more
1842 columns to modify, fix up certain values.
1843 Specifically, set to 0 any passed value
1844 of C<notforloan>, C<damaged>, C<itemlost>, or
1845 C<wthdrawn> that is either undefined or
1846 contains the empty string.
1850 sub _do_column_fixes_for_mod {
1853 if (exists $item->{'notforloan'} and
1854 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1855 $item->{'notforloan'} = 0;
1857 if (exists $item->{'damaged'} and
1858 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1859 $item->{'damaged'} = 0;
1861 if (exists $item->{'itemlost'} and
1862 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1863 $item->{'itemlost'} = 0;
1865 if (exists $item->{'wthdrawn'} and
1866 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1867 $item->{'wthdrawn'} = 0;
1869 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1870 $item->{'permanent_location'} = $item->{'location'};
1872 if (exists $item->{'timestamp'}) {
1873 delete $item->{'timestamp'};
1877 =head2 _get_single_item_column
1879 _get_single_item_column($column, $itemnumber);
1881 Retrieves the value of a single column from an C<items>
1882 row specified by C<$itemnumber>.
1886 sub _get_single_item_column {
1888 my $itemnumber = shift;
1890 my $dbh = C4::Context->dbh;
1891 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1892 $sth->execute($itemnumber);
1893 my ($value) = $sth->fetchrow();
1897 =head2 _calc_items_cn_sort
1899 _calc_items_cn_sort($item, $source_values);
1901 Helper routine to calculate C<items.cn_sort>.
1905 sub _calc_items_cn_sort {
1907 my $source_values = shift;
1909 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1912 =head2 _set_defaults_for_add
1914 _set_defaults_for_add($item_hash);
1916 Given an item hash representing an item to be added, set
1917 correct default values for columns whose default value
1918 is not handled by the DBMS. This includes the following
1925 C<items.dateaccessioned>
1947 sub _set_defaults_for_add {
1949 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1950 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1953 =head2 _koha_new_item
1955 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1957 Perform the actual insert into the C<items> table.
1961 sub _koha_new_item {
1962 my ( $item, $barcode ) = @_;
1963 my $dbh=C4::Context->dbh;
1966 "INSERT INTO items SET
1968 biblioitemnumber = ?,
1970 dateaccessioned = ?,
1974 replacementprice = ?,
1975 replacementpricedate = NOW(),
1976 datelastborrowed = ?,
1977 datelastseen = NOW(),
2000 more_subfields_xml = ?,
2004 my $sth = $dbh->prepare($query);
2006 $item->{'biblionumber'},
2007 $item->{'biblioitemnumber'},
2009 $item->{'dateaccessioned'},
2010 $item->{'booksellerid'},
2011 $item->{'homebranch'},
2013 $item->{'replacementprice'},
2014 $item->{datelastborrowed},
2016 $item->{'notforloan'},
2018 $item->{'itemlost'},
2019 $item->{'wthdrawn'},
2020 $item->{'itemcallnumber'},
2021 $item->{'restricted'},
2022 $item->{'itemnotes'},
2023 $item->{'holdingbranch'},
2025 $item->{'location'},
2028 $item->{'renewals'},
2029 $item->{'reserves'},
2030 $item->{'items.cn_source'},
2031 $item->{'items.cn_sort'},
2034 $item->{'materials'},
2036 $item->{'enumchron'},
2037 $item->{'more_subfields_xml'},
2038 $item->{'copynumber'},
2039 $item->{'stocknumber'},
2041 my $itemnumber = $dbh->{'mysql_insertid'};
2042 if ( defined $sth->errstr ) {
2043 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2045 return ( $itemnumber, $error );
2048 =head2 MoveItemFromBiblio
2050 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2052 Moves an item from a biblio to another
2054 Returns undef if the move failed or the biblionumber of the destination record otherwise
2058 sub MoveItemFromBiblio {
2059 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2060 my $dbh = C4::Context->dbh;
2061 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2062 $sth->execute( $tobiblio );
2063 my ( $tobiblioitem ) = $sth->fetchrow();
2064 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2065 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2067 ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2068 ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2069 # Checking if the item we want to move is in an order
2070 my $order = GetOrderFromItemnumber($itemnumber);
2072 # Replacing the biblionumber within the order if necessary
2073 $order->{'biblionumber'} = $tobiblio;
2083 DelItemCheck($dbh, $biblionumber, $itemnumber);
2085 Exported function (core API) for deleting an item record in Koha if there no current issue.
2090 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2093 # check that there is no issue on this item before deletion.
2094 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2095 $sth->execute($itemnumber);
2097 my $item = GetItem($itemnumber);
2098 my $onloan = $sth->fetchrow;
2100 $error = "book_on_loan";
2102 elsif (C4::Context->preference("IndependantBranches") and (C4::Context->userenv->{branch} ne $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'})){
2103 $error = "not_same_branch";
2107 $error = "book_on_loan"
2110 # check it doesnt have a waiting reserve
2111 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2112 $sth->execute($itemnumber);
2113 my $reserve=$sth->fetchrow;
2115 $error = "book_reserved";
2118 DelItem($dbh, $biblionumber, $itemnumber);
2126 =head2 _koha_modify_item
2128 my ($itemnumber,$error) =_koha_modify_item( $item );
2130 Perform the actual update of the C<items> row. Note that this
2131 routine accepts a hashref specifying the columns to update.
2135 sub _koha_modify_item {
2137 my $dbh=C4::Context->dbh;
2140 my $query = "UPDATE items SET ";
2142 for my $key ( keys %$item ) {
2144 push @bind, $item->{$key};
2147 $query .= " WHERE itemnumber=?";
2148 push @bind, $item->{'itemnumber'};
2149 my $sth = C4::Context->dbh->prepare($query);
2150 $sth->execute(@bind);
2151 if ( C4::Context->dbh->errstr ) {
2152 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2155 return ($item->{'itemnumber'},$error);
2158 =head2 _koha_delete_item
2160 _koha_delete_item( $dbh, $itemnum );
2162 Internal function to delete an item record from the koha tables
2166 sub _koha_delete_item {
2167 my ( $dbh, $itemnum ) = @_;
2169 # save the deleted item to deleteditems table
2170 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2171 $sth->execute($itemnum);
2172 my $data = $sth->fetchrow_hashref();
2173 my $query = "INSERT INTO deleteditems SET ";
2175 foreach my $key ( keys %$data ) {
2176 $query .= "$key = ?,";
2177 push( @bind, $data->{$key} );
2180 $sth = $dbh->prepare($query);
2181 $sth->execute(@bind);
2183 # delete from items table
2184 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2185 $sth->execute($itemnum);
2189 =head2 _marc_from_item_hash
2191 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2193 Given an item hash representing a complete item record,
2194 create a C<MARC::Record> object containing an embedded
2195 tag representing that item.
2197 The third, optional parameter C<$unlinked_item_subfields> is
2198 an arrayref of subfields (not mapped to C<items> fields per the
2199 framework) to be added to the MARC representation
2204 sub _marc_from_item_hash {
2206 my $frameworkcode = shift;
2207 my $unlinked_item_subfields;
2209 $unlinked_item_subfields = shift;
2212 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2213 # Also, don't emit a subfield if the underlying field is blank.
2214 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2215 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2216 : () } keys %{ $item } };
2218 my $item_marc = MARC::Record->new();
2219 foreach my $item_field ( keys %{$mungeditem} ) {
2220 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2221 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2222 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2223 foreach my $value (@values){
2224 if ( my $field = $item_marc->field($tag) ) {
2225 $field->add_subfields( $subfield => $value );
2227 my $add_subfields = [];
2228 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2229 $add_subfields = $unlinked_item_subfields;
2231 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2239 =head2 _repack_item_errors
2241 Add an error message hash generated by C<CheckItemPreSave>
2242 to a list of errors.
2246 sub _repack_item_errors {
2247 my $item_sequence_num = shift;
2248 my $item_ref = shift;
2249 my $error_ref = shift;
2251 my @repacked_errors = ();
2253 foreach my $error_code (sort keys %{ $error_ref }) {
2254 my $repacked_error = {};
2255 $repacked_error->{'item_sequence'} = $item_sequence_num;
2256 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2257 $repacked_error->{'error_code'} = $error_code;
2258 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2259 push @repacked_errors, $repacked_error;
2262 return @repacked_errors;
2265 =head2 _get_unlinked_item_subfields
2267 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2271 sub _get_unlinked_item_subfields {
2272 my $original_item_marc = shift;
2273 my $frameworkcode = shift;
2275 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2277 # assume that this record has only one field, and that that
2278 # field contains only the item information
2280 my @fields = $original_item_marc->fields();
2281 if ($#fields > -1) {
2282 my $field = $fields[0];
2283 my $tag = $field->tag();
2284 foreach my $subfield ($field->subfields()) {
2285 if (defined $subfield->[1] and
2286 $subfield->[1] ne '' and
2287 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2288 push @$subfields, $subfield->[0] => $subfield->[1];
2295 =head2 _get_unlinked_subfields_xml
2297 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2301 sub _get_unlinked_subfields_xml {
2302 my $unlinked_item_subfields = shift;
2305 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2306 my $marc = MARC::Record->new();
2307 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2308 # used in the framework
2309 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2310 $marc->encoding("UTF-8");
2311 $xml = $marc->as_xml("USMARC");
2317 =head2 _parse_unlinked_item_subfields_from_xml
2319 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2323 sub _parse_unlinked_item_subfields_from_xml {
2326 return unless defined $xml and $xml ne "";
2327 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2328 my $unlinked_subfields = [];
2329 my @fields = $marc->fields();
2330 if ($#fields > -1) {
2331 foreach my $subfield ($fields[0]->subfields()) {
2332 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2335 return $unlinked_subfields;