3 # Copyright 2007 LibLime, Inc.
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
26 use C4::Dates qw/format_date format_date_in_iso/;
35 use vars qw($VERSION @ISA @EXPORT);
41 @ISA = qw( Exporter );
64 GetItemsByBiblioitemnumber
67 GetItemnumberFromBarcode
78 C4::Items - item management functions
82 This module contains an API for manipulating item
83 records in Koha, and is used by cataloguing, circulation,
84 acquisitions, and serials management.
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 Consequently, all code that creates, modifies, or deletes
95 item records B<must> use an appropriate function from
96 C<C4::Items>. If no existing function is suitable, it is
97 better to add one to C<C4::Items> than to use add
98 one-off SQL statements to add or modify items.
100 The items table will be considered authoritative. In other
101 words, if there is ever a discrepancy between the items
102 table and the MARC XML, the items table should be considered
105 =head1 HISTORICAL NOTE
107 Most of the functions in C<C4::Items> were originally in
108 the C<C4::Biblio> module.
110 =head1 CORE EXPORTED FUNCTIONS
112 The following functions are meant for use by users
121 $item = GetItem($itemnumber,$barcode,$serial);
125 Return item information, for a given itemnumber or barcode.
126 The return value is a hashref mapping item column
127 names to values. If C<$serial> is true, include serial publication data.
132 my ($itemnumber,$barcode, $serial) = @_;
133 my $dbh = C4::Context->dbh;
136 my $sth = $dbh->prepare("
138 WHERE itemnumber = ?");
139 $sth->execute($itemnumber);
140 $data = $sth->fetchrow_hashref;
142 my $sth = $dbh->prepare("
146 $sth->execute($barcode);
147 $data = $sth->fetchrow_hashref;
150 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
151 $ssth->execute($data->{'itemnumber'}) ;
152 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
153 warn $data->{'serialseq'} , $data->{'publisheddate'};
155 #if we don't have an items.itype, use biblioitems.itemtype.
156 if( ! $data->{'itype'} ) {
157 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
158 $sth->execute($data->{'biblionumber'});
159 ($data->{'itype'}) = $sth->fetchrow_array;
168 CartToShelf($itemnumber);
172 Set the current shelving location of the item record
173 to its stored permanent shelving location. This is
174 primarily used to indicate when an item whose current
175 location is a special processing ('PROC') or shelving cart
176 ('CART') location is back in the stacks.
181 my ( $itemnumber ) = @_;
183 unless ( $itemnumber ) {
184 croak "FAILED CartToShelf() - no itemnumber supplied";
187 my $item = GetItem($itemnumber);
188 $item->{location} = $item->{permanent_location};
189 ModItem($item, undef, $itemnumber);
192 =head2 AddItemFromMarc
196 my ($biblionumber, $biblioitemnumber, $itemnumber)
197 = AddItemFromMarc($source_item_marc, $biblionumber);
201 Given a MARC::Record object containing an embedded item
202 record and a biblionumber, create a new item record.
206 sub AddItemFromMarc {
207 my ( $source_item_marc, $biblionumber ) = @_;
208 my $dbh = C4::Context->dbh;
210 # parse item hash from MARC
211 my $frameworkcode = GetFrameworkCode( $biblionumber );
212 my $item = &TransformMarcToKoha( $dbh, $source_item_marc, $frameworkcode );
213 my $unlinked_item_subfields = _get_unlinked_item_subfields($source_item_marc, $frameworkcode);
214 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
221 my ($biblionumber, $biblioitemnumber, $itemnumber)
222 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
226 Given a hash containing item column names as keys,
227 create a new Koha item record.
229 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
230 do not need to be supplied for general use; they exist
231 simply to allow them to be picked up from AddItemFromMarc.
233 The final optional parameter, C<$unlinked_item_subfields>, contains
234 an arrayref containing subfields present in the original MARC
235 representation of the item (e.g., from the item editor) that are
236 not mapped to C<items> columns directly but should instead
237 be stored in C<items.more_subfields_xml> and included in
238 the biblio items tag for display and indexing.
244 my $biblionumber = shift;
246 my $dbh = @_ ? shift : C4::Context->dbh;
247 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
248 my $unlinked_item_subfields;
250 $unlinked_item_subfields = shift
253 # needs old biblionumber and biblioitemnumber
254 $item->{'biblionumber'} = $biblionumber;
255 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
256 $sth->execute( $item->{'biblionumber'} );
257 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
259 _set_defaults_for_add($item);
260 _set_derived_columns_for_add($item);
261 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
262 # FIXME - checks here
263 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
264 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
265 $itype_sth->execute( $item->{'biblionumber'} );
266 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
269 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
270 $item->{'itemnumber'} = $itemnumber;
272 # create MARC tag representing item and add to bib
273 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
274 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
276 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
278 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
281 =head2 AddItemBatchFromMarc
285 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
289 Efficiently create item records from a MARC biblio record with
290 embedded item fields. This routine is suitable for batch jobs.
292 This API assumes that the bib record has already been
293 saved to the C<biblio> and C<biblioitems> tables. It does
294 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
295 are populated, but it will do so via a call to ModBibiloMarc.
297 The goal of this API is to have a similar effect to using AddBiblio
298 and AddItems in succession, but without inefficient repeated
299 parsing of the MARC XML bib record.
301 This function returns an arrayref of new itemsnumbers and an arrayref of item
302 errors encountered during the processing. Each entry in the errors
303 list is a hashref containing the following keys:
309 Sequence number of original item tag in the MARC record.
313 Item barcode, provide to assist in the construction of
314 useful error messages.
316 =item error_condition
318 Code representing the error condition. Can be 'duplicate_barcode',
319 'invalid_homebranch', or 'invalid_holdingbranch'.
321 =item error_information
323 Additional information appropriate to the error condition.
329 sub AddItemBatchFromMarc {
330 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
332 my @itemnumbers = ();
334 my $dbh = C4::Context->dbh;
336 # loop through the item tags and start creating items
337 my @bad_item_fields = ();
338 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
339 my $item_sequence_num = 0;
340 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
341 $item_sequence_num++;
342 # we take the item field and stick it into a new
343 # MARC record -- this is required so far because (FIXME)
344 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
345 # and there is no TransformMarcFieldToKoha
346 my $temp_item_marc = MARC::Record->new();
347 $temp_item_marc->append_fields($item_field);
349 # add biblionumber and biblioitemnumber
350 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
351 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
352 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
353 $item->{'biblionumber'} = $biblionumber;
354 $item->{'biblioitemnumber'} = $biblioitemnumber;
356 # check for duplicate barcode
357 my %item_errors = CheckItemPreSave($item);
359 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
360 push @bad_item_fields, $item_field;
364 _set_defaults_for_add($item);
365 _set_derived_columns_for_add($item);
366 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
367 warn $error if $error;
368 push @itemnumbers, $itemnumber; # FIXME not checking error
369 $item->{'itemnumber'} = $itemnumber;
371 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
373 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
374 $item_field->replace_with($new_item_marc->field($itemtag));
377 # remove any MARC item fields for rejected items
378 foreach my $item_field (@bad_item_fields) {
379 $record->delete_field($item_field);
382 # update the MARC biblio
383 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
385 return (\@itemnumbers, \@errors);
388 =head2 ModItemFromMarc
392 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
396 This function updates an item record based on a supplied
397 C<MARC::Record> object containing an embedded item field.
398 This API is meant for the use of C<additem.pl>; for
399 other purposes, C<ModItem> should be used.
401 This function uses the hash %default_values_for_mod_from_marc,
402 which contains default values for item fields to
403 apply when modifying an item. This is needed beccause
404 if an item field's value is cleared, TransformMarcToKoha
405 does not include the column in the
406 hash that's passed to ModItem, which without
407 use of this hash makes it impossible to clear
408 an item field's value. See bug 2466.
410 Note that only columns that can be directly
411 changed from the cataloging and serials
412 item editors are included in this hash.
416 my %default_values_for_mod_from_marc = (
418 booksellerid => undef,
420 'items.cn_source' => undef,
423 dateaccessioned => undef,
425 holdingbranch => undef,
427 itemcallnumber => undef,
436 replacementprice => undef,
437 replacementpricedate => undef,
444 sub ModItemFromMarc {
445 my $item_marc = shift;
446 my $biblionumber = shift;
447 my $itemnumber = shift;
449 my $dbh = C4::Context->dbh;
450 my $frameworkcode = GetFrameworkCode( $biblionumber );
451 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
453 my $localitemmarc=MARC::Record->new;
454 $localitemmarc->append_fields($item_marc->field($itemtag));
455 my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode ,'items');
456 foreach my $item_field (keys %default_values_for_mod_from_marc) {
457 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
459 my $unlinked_item_subfields = _get_unlinked_item_subfields($item_marc, $frameworkcode);
461 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
468 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
472 Change one or more columns in an item record and update
473 the MARC representation of the item.
475 The first argument is a hashref mapping from item column
476 names to the new values. The second and third arguments
477 are the biblionumber and itemnumber, respectively.
479 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
480 an arrayref containing subfields present in the original MARC
481 representation of the item (e.g., from the item editor) that are
482 not mapped to C<items> columns directly but should instead
483 be stored in C<items.more_subfields_xml> and included in
484 the biblio items tag for display and indexing.
486 If one of the changed columns is used to calculate
487 the derived value of a column such as C<items.cn_sort>,
488 this routine will perform the necessary calculation
495 my $biblionumber = shift;
496 my $itemnumber = shift;
498 # if $biblionumber is undefined, get it from the current item
499 unless (defined $biblionumber) {
500 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
503 my $dbh = @_ ? shift : C4::Context->dbh;
504 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
506 my $unlinked_item_subfields;
508 $unlinked_item_subfields = shift;
509 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
512 $item->{'itemnumber'} = $itemnumber or return undef;
513 _set_derived_columns_for_mod($item);
514 _do_column_fixes_for_mod($item);
517 # attempt to change itemnumber
518 # attempt to change biblionumber (if we want
519 # an API to relink an item to a different bib,
520 # it should be a separate function)
523 _koha_modify_item($item);
525 # update biblio MARC XML
526 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
528 unless (defined $unlinked_item_subfields) {
529 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
531 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
532 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
534 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
535 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
536 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
539 =head2 ModItemTransfer
543 ModItemTransfer($itenumber, $frombranch, $tobranch);
547 Marks an item as being transferred from one branch
552 sub ModItemTransfer {
553 my ( $itemnumber, $frombranch, $tobranch ) = @_;
555 my $dbh = C4::Context->dbh;
557 #new entry in branchtransfers....
558 my $sth = $dbh->prepare(
559 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
560 VALUES (?, ?, NOW(), ?)");
561 $sth->execute($itemnumber, $frombranch, $tobranch);
563 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
564 ModDateLastSeen($itemnumber);
568 =head2 ModDateLastSeen
572 ModDateLastSeen($itemnum);
576 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
577 C<$itemnum> is the item number
581 sub ModDateLastSeen {
582 my ($itemnumber) = @_;
584 my $today = C4::Dates->new();
585 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
592 DelItem($biblionumber, $itemnumber);
596 Exported function (core API) for deleting an item record in Koha.
601 my ( $dbh, $biblionumber, $itemnumber ) = @_;
603 # FIXME check the item has no current issues
605 _koha_delete_item( $dbh, $itemnumber );
607 # get the MARC record
608 my $record = GetMarcBiblio($biblionumber);
609 my $frameworkcode = GetFrameworkCode($biblionumber);
612 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
613 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
615 #search item field code
616 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
617 my @fields = $record->field($itemtag);
619 # delete the item specified
620 foreach my $field (@fields) {
621 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
622 $record->delete_field($field);
625 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
626 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
629 =head2 CheckItemPreSave
633 my $item_ref = TransformMarcToKoha($marc, 'items');
635 my %errors = CheckItemPreSave($item_ref);
636 if (exists $errors{'duplicate_barcode'}) {
637 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
638 } elsif (exists $errors{'invalid_homebranch'}) {
639 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
640 } elsif (exists $errors{'invalid_holdingbranch'}) {
641 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
648 Given a hashref containing item fields, determine if it can be
649 inserted or updated in the database. Specifically, checks for
650 database integrity issues, and returns a hash containing any
651 of the following keys, if applicable.
655 =item duplicate_barcode
657 Barcode, if it duplicates one already found in the database.
659 =item invalid_homebranch
661 Home branch, if not defined in branches table.
663 =item invalid_holdingbranch
665 Holding branch, if not defined in branches table.
669 This function does NOT implement any policy-related checks,
670 e.g., whether current operator is allowed to save an
671 item that has a given branch code.
675 sub CheckItemPreSave {
676 my $item_ref = shift;
680 # check for duplicate barcode
681 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
682 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
683 if ($existing_itemnumber) {
684 if (!exists $item_ref->{'itemnumber'} # new item
685 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
686 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
691 # check for valid home branch
692 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
693 my $branch_name = GetBranchName($item_ref->{'homebranch'});
694 unless (defined $branch_name) {
695 # relies on fact that branches.branchname is a non-NULL column,
696 # so GetBranchName returns undef only if branch does not exist
697 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
701 # check for valid holding branch
702 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
703 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
704 unless (defined $branch_name) {
705 # relies on fact that branches.branchname is a non-NULL column,
706 # so GetBranchName returns undef only if branch does not exist
707 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
715 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
717 The following functions provide various ways of
718 getting an item record, a set of item records, or
719 lists of authorized values for certain item fields.
721 Some of the functions in this group are candidates
722 for refactoring -- for example, some of the code
723 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
724 has copy-and-paste work.
732 $itemstatushash = GetItemStatus($fwkcode);
736 Returns a list of valid values for the
737 C<items.notforloan> field.
739 NOTE: does B<not> return an individual item's
742 Can be MARC dependant.
744 But basically could be can be loan or not
745 Create a status selector with the following code
747 =head3 in PERL SCRIPT
751 my $itemstatushash = getitemstatus;
753 foreach my $thisstatus (keys %$itemstatushash) {
754 my %row =(value => $thisstatus,
755 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
757 push @itemstatusloop, \%row;
759 $template->param(statusloop=>\@itemstatusloop);
767 <select name="statusloop">
768 <option value="">Default</option>
769 <!-- TMPL_LOOP name="statusloop" -->
770 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
780 # returns a reference to a hash of references to status...
783 my $dbh = C4::Context->dbh;
785 $fwk = '' unless ($fwk);
786 my ( $tag, $subfield ) =
787 GetMarcFromKohaField( "items.notforloan", $fwk );
788 if ( $tag and $subfield ) {
791 "SELECT authorised_value
792 FROM marc_subfield_structure
798 $sth->execute( $tag, $subfield, $fwk );
799 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
802 "SELECT authorised_value,lib
803 FROM authorised_values
808 $authvalsth->execute($authorisedvaluecat);
809 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
810 $itemstatus{$authorisedvalue} = $lib;
824 $itemstatus{"1"} = "Not For Loan";
828 =head2 GetItemLocation
832 $itemlochash = GetItemLocation($fwk);
836 Returns a list of valid values for the
837 C<items.location> field.
839 NOTE: does B<not> return an individual item's
842 where fwk stands for an optional framework code.
843 Create a location selector with the following code
845 =head3 in PERL SCRIPT
849 my $itemlochash = getitemlocation;
851 foreach my $thisloc (keys %$itemlochash) {
852 my $selected = 1 if $thisbranch eq $branch;
853 my %row =(locval => $thisloc,
854 selected => $selected,
855 locname => $itemlochash->{$thisloc},
857 push @itemlocloop, \%row;
859 $template->param(itemlocationloop => \@itemlocloop);
867 <select name="location">
868 <option value="">Default</option>
869 <!-- TMPL_LOOP name="itemlocationloop" -->
870 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
878 sub GetItemLocation {
880 # returns a reference to a hash of references to location...
883 my $dbh = C4::Context->dbh;
885 $fwk = '' unless ($fwk);
886 my ( $tag, $subfield ) =
887 GetMarcFromKohaField( "items.location", $fwk );
888 if ( $tag and $subfield ) {
891 "SELECT authorised_value
892 FROM marc_subfield_structure
897 $sth->execute( $tag, $subfield, $fwk );
898 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
901 "SELECT authorised_value,lib
902 FROM authorised_values
906 $authvalsth->execute($authorisedvaluecat);
907 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
908 $itemlocation{$authorisedvalue} = $lib;
910 return \%itemlocation;
922 $itemlocation{"1"} = "Not For Loan";
923 return \%itemlocation;
930 $items = GetLostItems( $where, $orderby );
934 This function gets a list of lost items.
940 C<$where> is a hashref. it containts a field of the items table as key
941 and the value to match as value. For example:
943 { barcode => 'abc123',
944 homebranch => 'CPL', }
946 C<$orderby> is a field of the items table by which the resultset
951 C<$items> is a reference to an array full of hashrefs with columns
952 from the "items" table as keys.
954 =item usage in the perl script:
956 my $where = { barcode => '0001548' };
957 my $items = GetLostItems( $where, "homebranch" );
958 $template->param( itemsloop => $items );
965 # Getting input args.
968 my $dbh = C4::Context->dbh;
973 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
974 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
975 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
977 authorised_values.category = 'LOST'
978 AND itemlost IS NOT NULL
981 my @query_parameters;
982 foreach my $key (keys %$where) {
983 $query .= " AND $key LIKE ?";
984 push @query_parameters, "%$where->{$key}%";
986 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
988 if ( defined $orderby && grep($orderby, @ordervalues)) {
989 $query .= ' ORDER BY '.$orderby;
992 my $sth = $dbh->prepare($query);
993 $sth->execute( @query_parameters );
995 while ( my $row = $sth->fetchrow_hashref ){
1001 =head2 GetItemsForInventory
1005 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size, $statushash);
1009 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1011 The sub returns a reference to a list of hashes, each containing
1012 itemnumber, author, title, barcode, item callnumber, and date last
1013 seen. It is ordered by callnumber then title.
1015 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1016 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1017 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1018 $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.
1022 sub GetItemsForInventory {
1023 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branch, $offset, $size, $statushash ) = @_;
1024 my $dbh = C4::Context->dbh;
1025 my ( @bind_params, @where_strings );
1027 my $query = <<'END_SQL';
1028 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
1030 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1031 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1034 for my $authvfield (keys %$statushash){
1035 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1036 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1037 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1043 push @where_strings, 'itemcallnumber >= ?';
1044 push @bind_params, $minlocation;
1048 push @where_strings, 'itemcallnumber <= ?';
1049 push @bind_params, $maxlocation;
1052 if ($datelastseen) {
1053 $datelastseen = format_date_in_iso($datelastseen);
1054 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1055 push @bind_params, $datelastseen;
1059 push @where_strings, 'items.location = ?';
1060 push @bind_params, $location;
1064 push @where_strings, 'items.homebranch = ?';
1065 push @bind_params, $branch;
1069 push @where_strings, 'biblioitems.itemtype = ?';
1070 push @bind_params, $itemtype;
1073 if ( $ignoreissued) {
1074 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1075 push @where_strings, 'issues.date_due IS NULL';
1078 if ( @where_strings ) {
1080 $query .= join ' AND ', @where_strings;
1082 $query .= ' ORDER BY itemcallnumber, title';
1083 my $sth = $dbh->prepare($query);
1084 $sth->execute( @bind_params );
1088 while ( my $row = $sth->fetchrow_hashref ) {
1089 $offset-- if ($offset);
1090 $row->{datelastseen}=format_date($row->{datelastseen});
1091 if ( ( !$offset ) && $size ) {
1092 push @results, $row;
1099 =head2 GetItemsCount
1102 $count = &GetItemsCount( $biblionumber);
1106 This function return count of item with $biblionumber
1111 my ( $biblionumber ) = @_;
1112 my $dbh = C4::Context->dbh;
1113 my $query = "SELECT count(*)
1115 WHERE biblionumber=?";
1116 my $sth = $dbh->prepare($query);
1117 $sth->execute($biblionumber);
1118 my $count = $sth->fetchrow;
1122 =head2 GetItemInfosOf
1126 GetItemInfosOf(@itemnumbers);
1132 sub GetItemInfosOf {
1133 my @itemnumbers = @_;
1138 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1140 return get_infos_of( $query, 'itemnumber' );
1143 =head2 GetItemsByBiblioitemnumber
1147 GetItemsByBiblioitemnumber($biblioitemnumber);
1151 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1152 Called by C<C4::XISBN>
1156 sub GetItemsByBiblioitemnumber {
1157 my ( $bibitem ) = @_;
1158 my $dbh = C4::Context->dbh;
1159 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1160 # Get all items attached to a biblioitem
1163 $sth->execute($bibitem) || die $sth->errstr;
1164 while ( my $data = $sth->fetchrow_hashref ) {
1165 # Foreach item, get circulation information
1166 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1167 WHERE itemnumber = ?
1168 AND issues.borrowernumber = borrowers.borrowernumber"
1170 $sth2->execute( $data->{'itemnumber'} );
1171 if ( my $data2 = $sth2->fetchrow_hashref ) {
1172 # if item is out, set the due date and who it is out too
1173 $data->{'date_due'} = $data2->{'date_due'};
1174 $data->{'cardnumber'} = $data2->{'cardnumber'};
1175 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1178 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1179 $data->{'date_due'} = '';
1181 # Find the last 3 people who borrowed this item.
1182 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1183 AND old_issues.borrowernumber = borrowers.borrowernumber
1184 ORDER BY returndate desc,timestamp desc LIMIT 3";
1185 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1186 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1188 while ( my $data2 = $sth2->fetchrow_hashref ) {
1189 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1190 $data->{"card$i2"} = $data2->{'cardnumber'};
1191 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1194 push(@results,$data);
1203 @results = GetItemsInfo($biblionumber, $type);
1207 Returns information about books with the given biblionumber.
1209 C<$type> may be either C<intra> or anything else. If it is not set to
1210 C<intra>, then the search will exclude lost, very overdue, and
1213 C<GetItemsInfo> returns a list of references-to-hash. Each element
1214 contains a number of keys. Most of them are table items from the
1215 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1216 Koha database. Other keys include:
1220 =item C<$data-E<gt>{branchname}>
1222 The name (not the code) of the branch to which the book belongs.
1224 =item C<$data-E<gt>{datelastseen}>
1226 This is simply C<items.datelastseen>, except that while the date is
1227 stored in YYYY-MM-DD format in the database, here it is converted to
1228 DD/MM/YYYY format. A NULL date is returned as C<//>.
1230 =item C<$data-E<gt>{datedue}>
1232 =item C<$data-E<gt>{class}>
1234 This is the concatenation of C<biblioitems.classification>, the book's
1235 Dewey code, and C<biblioitems.subclass>.
1237 =item C<$data-E<gt>{ocount}>
1239 I think this is the number of copies of the book available.
1241 =item C<$data-E<gt>{order}>
1243 If this is set, it is set to C<One Order>.
1250 my ( $biblionumber, $type ) = @_;
1251 my $dbh = C4::Context->dbh;
1252 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1258 biblioitems.itemtype,
1261 biblioitems.publicationyear,
1262 biblioitems.publishercode,
1263 biblioitems.volumedate,
1264 biblioitems.volumedesc,
1267 items.notforloan as itemnotforloan,
1268 itemtypes.description
1270 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1271 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1272 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1273 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1274 $query .= " WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1275 my $sth = $dbh->prepare($query);
1276 $sth->execute($biblionumber);
1281 my $isth = $dbh->prepare(
1282 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1283 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1284 WHERE itemnumber = ?"
1286 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1287 while ( my $data = $sth->fetchrow_hashref ) {
1290 $isth->execute( $data->{'itemnumber'} );
1291 if ( my $idata = $isth->fetchrow_hashref ) {
1292 $data->{borrowernumber} = $idata->{borrowernumber};
1293 $data->{cardnumber} = $idata->{cardnumber};
1294 $data->{surname} = $idata->{surname};
1295 $data->{firstname} = $idata->{firstname};
1296 $datedue = $idata->{'date_due'};
1297 if (C4::Context->preference("IndependantBranches")){
1298 my $userenv = C4::Context->userenv;
1299 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1300 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1304 if ( $data->{'serial'}) {
1305 $ssth->execute($data->{'itemnumber'}) ;
1306 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1309 if ( $datedue eq '' ) {
1310 my ( $restype, $reserves ) =
1311 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1312 # Previous conditional check with if ($restype) is not needed because a true
1313 # result for one item will result in subsequent items defaulting to this true
1315 $count_reserves = $restype;
1317 #get branch information.....
1318 my $bsth = $dbh->prepare(
1319 "SELECT * FROM branches WHERE branchcode = ?
1322 $bsth->execute( $data->{'holdingbranch'} );
1323 if ( my $bdata = $bsth->fetchrow_hashref ) {
1324 $data->{'branchname'} = $bdata->{'branchname'};
1326 $data->{'datedue'} = $datedue;
1327 $data->{'count_reserves'} = $count_reserves;
1329 # get notforloan complete status if applicable
1330 my $sthnflstatus = $dbh->prepare(
1331 'SELECT authorised_value
1332 FROM marc_subfield_structure
1333 WHERE kohafield="items.notforloan"
1337 $sthnflstatus->execute;
1338 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1339 if ($authorised_valuecode) {
1340 $sthnflstatus = $dbh->prepare(
1341 "SELECT lib FROM authorised_values
1343 AND authorised_value=?"
1345 $sthnflstatus->execute( $authorised_valuecode,
1346 $data->{itemnotforloan} );
1347 my ($lib) = $sthnflstatus->fetchrow;
1348 $data->{notforloanvalue} = $lib;
1350 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1352 # my stack procedures
1353 my $stackstatus = $dbh->prepare(
1354 'SELECT authorised_value
1355 FROM marc_subfield_structure
1356 WHERE kohafield="items.stack"
1359 $stackstatus->execute;
1361 ($authorised_valuecode) = $stackstatus->fetchrow;
1362 if ($authorised_valuecode) {
1363 $stackstatus = $dbh->prepare(
1365 FROM authorised_values
1367 AND authorised_value=?
1370 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1371 my ($lib) = $stackstatus->fetchrow;
1372 $data->{stack} = $lib;
1374 # Find the last 3 people who borrowed this item.
1375 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1376 WHERE itemnumber = ?
1377 AND old_issues.borrowernumber = borrowers.borrowernumber
1378 ORDER BY returndate DESC
1380 $sth2->execute($data->{'itemnumber'});
1382 while (my $data2 = $sth2->fetchrow_hashref()) {
1383 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1384 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1385 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1389 $results[$i] = $data;
1393 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1399 =head2 GetLastAcquisitions
1403 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 'itemtypes' => ('BK','BD')}, 10);
1409 sub GetLastAcquisitions {
1410 my ($data,$max) = @_;
1412 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1414 my $number_of_branches = @{$data->{branches}};
1415 my $number_of_itemtypes = @{$data->{itemtypes}};
1418 my @where = ('WHERE 1 ');
1419 $number_of_branches and push @where
1420 , 'AND holdingbranch IN ('
1421 , join(',', ('?') x $number_of_branches )
1425 $number_of_itemtypes and push @where
1426 , "AND $itemtype IN ("
1427 , join(',', ('?') x $number_of_itemtypes )
1431 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1432 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1433 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1435 GROUP BY biblio.biblionumber
1436 ORDER BY dateaccessioned DESC LIMIT $max";
1438 my $dbh = C4::Context->dbh;
1439 my $sth = $dbh->prepare($query);
1441 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1444 while( my $row = $sth->fetchrow_hashref){
1445 push @results, {date => $row->{dateaccessioned}
1446 , biblionumber => $row->{biblionumber}
1447 , title => $row->{title}};
1453 =head2 get_itemnumbers_of
1457 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1461 Given a list of biblionumbers, return the list of corresponding itemnumbers
1462 for each biblionumber.
1464 Return a reference on a hash where keys are biblionumbers and values are
1465 references on array of itemnumbers.
1469 sub get_itemnumbers_of {
1470 my @biblionumbers = @_;
1472 my $dbh = C4::Context->dbh;
1478 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1480 my $sth = $dbh->prepare($query);
1481 $sth->execute(@biblionumbers);
1485 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1486 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1489 return \%itemnumbers_of;
1492 =head2 GetItemnumberFromBarcode
1496 $result = GetItemnumberFromBarcode($barcode);
1502 sub GetItemnumberFromBarcode {
1504 my $dbh = C4::Context->dbh;
1507 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1508 $rq->execute($barcode);
1509 my ($result) = $rq->fetchrow;
1513 =head3 get_item_authorised_values
1515 find the types and values for all authorised values assigned to this item.
1520 returns: a hashref malling the authorised value to the value set for this itemnumber
1522 $authorised_values = {
1528 'RESTRICTED' => undef,
1531 'branches' => 'CPL',
1532 'cn_source' => undef,
1533 'itemtypes' => 'SER',
1536 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1540 sub get_item_authorised_values {
1541 my $itemnumber = shift;
1543 # assume that these entries in the authorised_value table are item level.
1544 my $query = q(SELECT distinct authorised_value, kohafield
1545 FROM marc_subfield_structure
1546 WHERE kohafield like 'item%'
1547 AND authorised_value != '' );
1549 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1550 my $iteminfo = GetItem( $itemnumber );
1551 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1553 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1554 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1555 $field =~ s/^items\.//;
1556 if ( exists $iteminfo->{ $field } ) {
1557 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1560 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1564 =head3 get_authorised_value_images
1566 find a list of icons that are appropriate for display based on the
1567 authorised values for a biblio.
1569 parameters: listref of authorised values, such as comes from
1570 get_item_authorised_values or
1571 from C4::Biblio::get_biblio_authorised_values
1573 returns: listref of hashrefs for each image. Each hashref looks like
1576 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1581 Notes: Currently, I put on the full path to the images on the staff
1582 side. This should either be configurable or not done at all. Since I
1583 have to deal with 'intranet' or 'opac' in
1584 get_biblio_authorised_values, perhaps I should be passing it in.
1588 sub get_authorised_value_images {
1589 my $authorised_values = shift;
1593 my $authorised_value_list = GetAuthorisedValues();
1594 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1595 foreach my $this_authorised_value ( @$authorised_value_list ) {
1596 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1597 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1598 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1599 if ( defined $this_authorised_value->{'imageurl'} ) {
1600 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1601 label => $this_authorised_value->{'lib'},
1602 category => $this_authorised_value->{'category'},
1603 value => $this_authorised_value->{'authorised_value'}, };
1608 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1613 =head1 LIMITED USE FUNCTIONS
1615 The following functions, while part of the public API,
1616 are not exported. This is generally because they are
1617 meant to be used by only one script for a specific
1618 purpose, and should not be used in any other context
1619 without careful thought.
1627 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1631 Returns MARC::Record of the item passed in parameter.
1632 This function is meant for use only in C<cataloguing/additem.pl>,
1633 where it is needed to support that script's MARC-like
1639 my ( $biblionumber, $itemnumber ) = @_;
1641 # GetMarcItem has been revised so that it does the following:
1642 # 1. Gets the item information from the items table.
1643 # 2. Converts it to a MARC field for storage in the bib record.
1645 # The previous behavior was:
1646 # 1. Get the bib record.
1647 # 2. Return the MARC tag corresponding to the item record.
1649 # The difference is that one treats the items row as authoritative,
1650 # while the other treats the MARC representation as authoritative
1651 # under certain circumstances.
1653 my $itemrecord = GetItem($itemnumber);
1655 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1656 # Also, don't emit a subfield if the underlying field is blank.
1659 return Item2Marc($itemrecord,$biblionumber);
1663 my ($itemrecord,$biblionumber)=@_;
1666 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1667 } keys %{ $itemrecord }
1669 my $itemmarc = TransformKohaToMarc($mungeditem);
1670 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1672 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1673 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1674 foreach my $field ($itemmarc->field($itemtag)){
1675 $field->add_subfields(@$unlinked_item_subfields);
1681 =head1 PRIVATE FUNCTIONS AND VARIABLES
1683 The following functions are not meant to be called
1684 directly, but are documented in order to explain
1685 the inner workings of C<C4::Items>.
1689 =head2 %derived_columns
1691 This hash keeps track of item columns that
1692 are strictly derived from other columns in
1693 the item record and are not meant to be set
1696 Each key in the hash should be the name of a
1697 column (as named by TransformMarcToKoha). Each
1698 value should be hashref whose keys are the
1699 columns on which the derived column depends. The
1700 hashref should also contain a 'BUILDER' key
1701 that is a reference to a sub that calculates
1706 my %derived_columns = (
1707 'items.cn_sort' => {
1708 'itemcallnumber' => 1,
1709 'items.cn_source' => 1,
1710 'BUILDER' => \&_calc_items_cn_sort,
1714 =head2 _set_derived_columns_for_add
1718 _set_derived_column_for_add($item);
1722 Given an item hash representing a new item to be added,
1723 calculate any derived columns. Currently the only
1724 such column is C<items.cn_sort>.
1728 sub _set_derived_columns_for_add {
1731 foreach my $column (keys %derived_columns) {
1732 my $builder = $derived_columns{$column}->{'BUILDER'};
1733 my $source_values = {};
1734 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1735 next if $source_column eq 'BUILDER';
1736 $source_values->{$source_column} = $item->{$source_column};
1738 $builder->($item, $source_values);
1742 =head2 _set_derived_columns_for_mod
1746 _set_derived_column_for_mod($item);
1750 Given an item hash representing a new item to be modified.
1751 calculate any derived columns. Currently the only
1752 such column is C<items.cn_sort>.
1754 This routine differs from C<_set_derived_columns_for_add>
1755 in that it needs to handle partial item records. In other
1756 words, the caller of C<ModItem> may have supplied only one
1757 or two columns to be changed, so this function needs to
1758 determine whether any of the columns to be changed affect
1759 any of the derived columns. Also, if a derived column
1760 depends on more than one column, but the caller is not
1761 changing all of then, this routine retrieves the unchanged
1762 values from the database in order to ensure a correct
1767 sub _set_derived_columns_for_mod {
1770 foreach my $column (keys %derived_columns) {
1771 my $builder = $derived_columns{$column}->{'BUILDER'};
1772 my $source_values = {};
1773 my %missing_sources = ();
1774 my $must_recalc = 0;
1775 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1776 next if $source_column eq 'BUILDER';
1777 if (exists $item->{$source_column}) {
1779 $source_values->{$source_column} = $item->{$source_column};
1781 $missing_sources{$source_column} = 1;
1785 foreach my $source_column (keys %missing_sources) {
1786 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1788 $builder->($item, $source_values);
1793 =head2 _do_column_fixes_for_mod
1797 _do_column_fixes_for_mod($item);
1801 Given an item hashref containing one or more
1802 columns to modify, fix up certain values.
1803 Specifically, set to 0 any passed value
1804 of C<notforloan>, C<damaged>, C<itemlost>, or
1805 C<wthdrawn> that is either undefined or
1806 contains the empty string.
1810 sub _do_column_fixes_for_mod {
1813 if (exists $item->{'notforloan'} and
1814 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1815 $item->{'notforloan'} = 0;
1817 if (exists $item->{'damaged'} and
1818 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1819 $item->{'damaged'} = 0;
1821 if (exists $item->{'itemlost'} and
1822 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1823 $item->{'itemlost'} = 0;
1825 if (exists $item->{'wthdrawn'} and
1826 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1827 $item->{'wthdrawn'} = 0;
1829 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1830 $item->{'permanent_location'} = $item->{'location'};
1834 =head2 _get_single_item_column
1838 _get_single_item_column($column, $itemnumber);
1842 Retrieves the value of a single column from an C<items>
1843 row specified by C<$itemnumber>.
1847 sub _get_single_item_column {
1849 my $itemnumber = shift;
1851 my $dbh = C4::Context->dbh;
1852 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1853 $sth->execute($itemnumber);
1854 my ($value) = $sth->fetchrow();
1858 =head2 _calc_items_cn_sort
1862 _calc_items_cn_sort($item, $source_values);
1866 Helper routine to calculate C<items.cn_sort>.
1870 sub _calc_items_cn_sort {
1872 my $source_values = shift;
1874 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1877 =head2 _set_defaults_for_add
1881 _set_defaults_for_add($item_hash);
1885 Given an item hash representing an item to be added, set
1886 correct default values for columns whose default value
1887 is not handled by the DBMS. This includes the following
1894 C<items.dateaccessioned>
1916 sub _set_defaults_for_add {
1918 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1919 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1922 =head2 _koha_new_item
1926 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1930 Perform the actual insert into the C<items> table.
1934 sub _koha_new_item {
1935 my ( $item, $barcode ) = @_;
1936 my $dbh=C4::Context->dbh;
1939 "INSERT INTO items SET
1941 biblioitemnumber = ?,
1943 dateaccessioned = ?,
1947 replacementprice = ?,
1948 replacementpricedate = NOW(),
1949 datelastborrowed = ?,
1950 datelastseen = NOW(),
1973 more_subfields_xml = ?,
1976 my $sth = $dbh->prepare($query);
1978 $item->{'biblionumber'},
1979 $item->{'biblioitemnumber'},
1981 $item->{'dateaccessioned'},
1982 $item->{'booksellerid'},
1983 $item->{'homebranch'},
1985 $item->{'replacementprice'},
1986 $item->{datelastborrowed},
1988 $item->{'notforloan'},
1990 $item->{'itemlost'},
1991 $item->{'wthdrawn'},
1992 $item->{'itemcallnumber'},
1993 $item->{'restricted'},
1994 $item->{'itemnotes'},
1995 $item->{'holdingbranch'},
1997 $item->{'location'},
2000 $item->{'renewals'},
2001 $item->{'reserves'},
2002 $item->{'items.cn_source'},
2003 $item->{'items.cn_sort'},
2006 $item->{'materials'},
2008 $item->{'enumchron'},
2009 $item->{'more_subfields_xml'},
2010 $item->{'copynumber'},
2012 my $itemnumber = $dbh->{'mysql_insertid'};
2013 if ( defined $sth->errstr ) {
2014 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2016 return ( $itemnumber, $error );
2019 =head2 MoveItemFromBiblio
2023 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2027 Moves an item from a biblio to another
2029 Returns undef if the move failed or the biblionumber of the destination record otherwise
2031 sub MoveItemFromBiblio {
2032 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2033 my $dbh = C4::Context->dbh;
2034 my $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2035 my $return = $sth->execute($tobiblio, $tobiblio, $itemnumber, $frombiblio);
2039 my $frameworkcode = GetFrameworkCode($frombiblio);
2041 # Getting marc field for itemnumber
2042 my ($itemtag, $itemsubfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
2044 # Getting the record we want to move the item from
2045 my $record = GetMarcBiblio($frombiblio);
2047 # The item we want to move
2051 foreach my $fielditem ($record->field($itemtag)){
2052 # If it is the item we want to move
2053 if ($fielditem->subfield($itemsubfield) == $itemnumber) {
2056 # Then delete it from the record
2057 $record->delete_field($fielditem)
2061 # If we found an item (should always true, except in case of database-marcxml inconsistency)
2064 # Checking if the item we want to move is in an order
2065 my $order = GetOrderFromItemnumber($itemnumber);
2067 # Replacing the biblionumber within the order if necessary
2068 $order->{'biblionumber'} = $tobiblio;
2072 # Saving the modification
2073 ModBiblioMarc($record, $frombiblio, $frameworkcode);
2075 # Getting the record we want to move the item to
2076 $record = GetMarcBiblio($tobiblio);
2078 # Inserting the previously saved item
2079 $record->insert_fields_ordered($item);
2081 # Saving the modification
2082 ModBiblioMarc($record, $tobiblio, $frameworkcode);
2096 DelItemCheck($dbh, $biblionumber, $itemnumber);
2100 Exported function (core API) for deleting an item record in Koha if there no current issue.
2105 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2108 # check that there is no issue on this item before deletion.
2109 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2110 $sth->execute($itemnumber);
2112 my $onloan=$sth->fetchrow;
2115 $error = "book_on_loan"
2117 # check it doesnt have a waiting reserve
2118 $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
2119 $sth->execute($itemnumber);
2120 my $reserve=$sth->fetchrow;
2122 $error = "book_reserved";
2124 DelItem($dbh, $biblionumber, $itemnumber);
2131 =head2 _koha_modify_item
2135 my ($itemnumber,$error) =_koha_modify_item( $item );
2139 Perform the actual update of the C<items> row. Note that this
2140 routine accepts a hashref specifying the columns to update.
2144 sub _koha_modify_item {
2146 my $dbh=C4::Context->dbh;
2149 my $query = "UPDATE items SET ";
2151 for my $key ( keys %$item ) {
2153 push @bind, $item->{$key};
2156 $query .= " WHERE itemnumber=?";
2157 push @bind, $item->{'itemnumber'};
2158 my $sth = C4::Context->dbh->prepare($query);
2159 $sth->execute(@bind);
2160 if ( C4::Context->dbh->errstr ) {
2161 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2164 return ($item->{'itemnumber'},$error);
2167 =head2 _koha_delete_item
2171 _koha_delete_item( $dbh, $itemnum );
2175 Internal function to delete an item record from the koha tables
2179 sub _koha_delete_item {
2180 my ( $dbh, $itemnum ) = @_;
2182 # save the deleted item to deleteditems table
2183 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2184 $sth->execute($itemnum);
2185 my $data = $sth->fetchrow_hashref();
2186 my $query = "INSERT INTO deleteditems SET ";
2188 foreach my $key ( keys %$data ) {
2189 $query .= "$key = ?,";
2190 push( @bind, $data->{$key} );
2193 $sth = $dbh->prepare($query);
2194 $sth->execute(@bind);
2196 # delete from items table
2197 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2198 $sth->execute($itemnum);
2202 =head2 _marc_from_item_hash
2206 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2210 Given an item hash representing a complete item record,
2211 create a C<MARC::Record> object containing an embedded
2212 tag representing that item.
2214 The third, optional parameter C<$unlinked_item_subfields> is
2215 an arrayref of subfields (not mapped to C<items> fields per the
2216 framework) to be added to the MARC representation
2221 sub _marc_from_item_hash {
2223 my $frameworkcode = shift;
2224 my $unlinked_item_subfields;
2226 $unlinked_item_subfields = shift;
2229 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2230 # Also, don't emit a subfield if the underlying field is blank.
2231 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2232 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2233 : () } keys %{ $item } };
2235 my $item_marc = MARC::Record->new();
2236 foreach my $item_field (keys %{ $mungeditem }) {
2237 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
2238 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2239 if (my $field = $item_marc->field($tag)) {
2240 $field->add_subfields($subfield => $mungeditem->{$item_field});
2242 my $add_subfields = [];
2243 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2244 $add_subfields = $unlinked_item_subfields;
2246 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
2253 =head2 _add_item_field_to_biblio
2257 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2261 Adds the fields from a MARC record containing the
2262 representation of a Koha item record to the MARC
2263 biblio record. The input C<$item_marc> record
2264 is expect to contain just one field, the embedded
2265 item information field.
2269 sub _add_item_field_to_biblio {
2270 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2272 my $biblio_marc = GetMarcBiblio($biblionumber);
2273 foreach my $field ($item_marc->fields()) {
2274 $biblio_marc->append_fields($field);
2277 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2280 =head2 _replace_item_field_in_biblio
2284 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2288 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2289 representation of the item, examine the biblio MARC
2290 for the corresponding tag for that item and
2291 replace it with the tag from C<$item_marc>.
2295 sub _replace_item_field_in_biblio {
2296 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2297 my $dbh = C4::Context->dbh;
2299 # get complete MARC record & replace the item field by the new one
2300 my $completeRecord = GetMarcBiblio($biblionumber);
2301 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2302 my $itemField = $ItemRecord->field($itemtag);
2303 my @items = $completeRecord->field($itemtag);
2306 if ($_->subfield($itemsubfield) eq $itemnumber) {
2307 $_->replace_with($itemField);
2313 # If we haven't found the matching field,
2314 # just add it. However, this means that
2315 # there is likely a bug.
2316 $completeRecord->append_fields($itemField);
2320 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2323 =head2 _repack_item_errors
2325 Add an error message hash generated by C<CheckItemPreSave>
2326 to a list of errors.
2330 sub _repack_item_errors {
2331 my $item_sequence_num = shift;
2332 my $item_ref = shift;
2333 my $error_ref = shift;
2335 my @repacked_errors = ();
2337 foreach my $error_code (sort keys %{ $error_ref }) {
2338 my $repacked_error = {};
2339 $repacked_error->{'item_sequence'} = $item_sequence_num;
2340 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2341 $repacked_error->{'error_code'} = $error_code;
2342 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2343 push @repacked_errors, $repacked_error;
2346 return @repacked_errors;
2349 =head2 _get_unlinked_item_subfields
2353 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2359 sub _get_unlinked_item_subfields {
2360 my $original_item_marc = shift;
2361 my $frameworkcode = shift;
2363 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2365 # assume that this record has only one field, and that that
2366 # field contains only the item information
2368 my @fields = $original_item_marc->fields();
2369 if ($#fields > -1) {
2370 my $field = $fields[0];
2371 my $tag = $field->tag();
2372 foreach my $subfield ($field->subfields()) {
2373 if (defined $subfield->[1] and
2374 $subfield->[1] ne '' and
2375 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2376 push @$subfields, $subfield->[0] => $subfield->[1];
2383 =head2 _get_unlinked_subfields_xml
2387 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2393 sub _get_unlinked_subfields_xml {
2394 my $unlinked_item_subfields = shift;
2397 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2398 my $marc = MARC::Record->new();
2399 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2400 # used in the framework
2401 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2402 $marc->encoding("UTF-8");
2403 $xml = $marc->as_xml("USMARC");
2409 =head2 _parse_unlinked_item_subfields_from_xml
2413 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2419 sub _parse_unlinked_item_subfields_from_xml {
2422 return unless defined $xml and $xml ne "";
2423 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2424 my $unlinked_subfields = [];
2425 my @fields = $marc->fields();
2426 if ($#fields > -1) {
2427 foreach my $subfield ($fields[0]->subfields()) {
2428 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2431 return $unlinked_subfields;