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 ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
214 my $localitemmarc=MARC::Record->new;
215 $localitemmarc->append_fields($source_item_marc->field($itemtag));
216 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
217 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
218 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
225 my ($biblionumber, $biblioitemnumber, $itemnumber)
226 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
230 Given a hash containing item column names as keys,
231 create a new Koha item record.
233 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
234 do not need to be supplied for general use; they exist
235 simply to allow them to be picked up from AddItemFromMarc.
237 The final optional parameter, C<$unlinked_item_subfields>, contains
238 an arrayref containing subfields present in the original MARC
239 representation of the item (e.g., from the item editor) that are
240 not mapped to C<items> columns directly but should instead
241 be stored in C<items.more_subfields_xml> and included in
242 the biblio items tag for display and indexing.
248 my $biblionumber = shift;
250 my $dbh = @_ ? shift : C4::Context->dbh;
251 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
252 my $unlinked_item_subfields;
254 $unlinked_item_subfields = shift
257 # needs old biblionumber and biblioitemnumber
258 $item->{'biblionumber'} = $biblionumber;
259 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
260 $sth->execute( $item->{'biblionumber'} );
261 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
263 _set_defaults_for_add($item);
264 _set_derived_columns_for_add($item);
265 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
266 # FIXME - checks here
267 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
268 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
269 $itype_sth->execute( $item->{'biblionumber'} );
270 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
273 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
274 $item->{'itemnumber'} = $itemnumber;
276 # create MARC tag representing item and add to bib
277 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
278 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
280 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
282 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
285 =head2 AddItemBatchFromMarc
289 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
293 Efficiently create item records from a MARC biblio record with
294 embedded item fields. This routine is suitable for batch jobs.
296 This API assumes that the bib record has already been
297 saved to the C<biblio> and C<biblioitems> tables. It does
298 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
299 are populated, but it will do so via a call to ModBibiloMarc.
301 The goal of this API is to have a similar effect to using AddBiblio
302 and AddItems in succession, but without inefficient repeated
303 parsing of the MARC XML bib record.
305 This function returns an arrayref of new itemsnumbers and an arrayref of item
306 errors encountered during the processing. Each entry in the errors
307 list is a hashref containing the following keys:
313 Sequence number of original item tag in the MARC record.
317 Item barcode, provide to assist in the construction of
318 useful error messages.
320 =item error_condition
322 Code representing the error condition. Can be 'duplicate_barcode',
323 'invalid_homebranch', or 'invalid_holdingbranch'.
325 =item error_information
327 Additional information appropriate to the error condition.
333 sub AddItemBatchFromMarc {
334 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
336 my @itemnumbers = ();
338 my $dbh = C4::Context->dbh;
340 # loop through the item tags and start creating items
341 my @bad_item_fields = ();
342 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
343 my $item_sequence_num = 0;
344 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
345 $item_sequence_num++;
346 # we take the item field and stick it into a new
347 # MARC record -- this is required so far because (FIXME)
348 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
349 # and there is no TransformMarcFieldToKoha
350 my $temp_item_marc = MARC::Record->new();
351 $temp_item_marc->append_fields($item_field);
353 # add biblionumber and biblioitemnumber
354 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
355 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
356 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
357 $item->{'biblionumber'} = $biblionumber;
358 $item->{'biblioitemnumber'} = $biblioitemnumber;
360 # check for duplicate barcode
361 my %item_errors = CheckItemPreSave($item);
363 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
364 push @bad_item_fields, $item_field;
368 _set_defaults_for_add($item);
369 _set_derived_columns_for_add($item);
370 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
371 warn $error if $error;
372 push @itemnumbers, $itemnumber; # FIXME not checking error
373 $item->{'itemnumber'} = $itemnumber;
375 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
377 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
378 $item_field->replace_with($new_item_marc->field($itemtag));
381 # remove any MARC item fields for rejected items
382 foreach my $item_field (@bad_item_fields) {
383 $record->delete_field($item_field);
386 # update the MARC biblio
387 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
389 return (\@itemnumbers, \@errors);
392 =head2 ModItemFromMarc
396 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
400 This function updates an item record based on a supplied
401 C<MARC::Record> object containing an embedded item field.
402 This API is meant for the use of C<additem.pl>; for
403 other purposes, C<ModItem> should be used.
405 This function uses the hash %default_values_for_mod_from_marc,
406 which contains default values for item fields to
407 apply when modifying an item. This is needed beccause
408 if an item field's value is cleared, TransformMarcToKoha
409 does not include the column in the
410 hash that's passed to ModItem, which without
411 use of this hash makes it impossible to clear
412 an item field's value. See bug 2466.
414 Note that only columns that can be directly
415 changed from the cataloging and serials
416 item editors are included in this hash.
420 my %default_values_for_mod_from_marc = (
422 booksellerid => undef,
424 'items.cn_source' => undef,
427 dateaccessioned => undef,
429 holdingbranch => undef,
431 itemcallnumber => undef,
440 replacementprice => undef,
441 replacementpricedate => undef,
448 sub ModItemFromMarc {
449 my $item_marc = shift;
450 my $biblionumber = shift;
451 my $itemnumber = shift;
453 my $dbh = C4::Context->dbh;
454 my $frameworkcode = GetFrameworkCode( $biblionumber );
455 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
457 my $localitemmarc=MARC::Record->new;
458 $localitemmarc->append_fields($item_marc->field($itemtag));
459 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items');
460 foreach my $item_field (keys %default_values_for_mod_from_marc) {
461 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
463 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
465 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
472 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
476 Change one or more columns in an item record and update
477 the MARC representation of the item.
479 The first argument is a hashref mapping from item column
480 names to the new values. The second and third arguments
481 are the biblionumber and itemnumber, respectively.
483 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
484 an arrayref containing subfields present in the original MARC
485 representation of the item (e.g., from the item editor) that are
486 not mapped to C<items> columns directly but should instead
487 be stored in C<items.more_subfields_xml> and included in
488 the biblio items tag for display and indexing.
490 If one of the changed columns is used to calculate
491 the derived value of a column such as C<items.cn_sort>,
492 this routine will perform the necessary calculation
499 my $biblionumber = shift;
500 my $itemnumber = shift;
502 # if $biblionumber is undefined, get it from the current item
503 unless (defined $biblionumber) {
504 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
507 my $dbh = @_ ? shift : C4::Context->dbh;
508 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
510 my $unlinked_item_subfields;
512 $unlinked_item_subfields = shift;
513 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
516 $item->{'itemnumber'} = $itemnumber or return undef;
517 _set_derived_columns_for_mod($item);
518 _do_column_fixes_for_mod($item);
521 # attempt to change itemnumber
522 # attempt to change biblionumber (if we want
523 # an API to relink an item to a different bib,
524 # it should be a separate function)
527 _koha_modify_item($item);
529 # update biblio MARC XML
530 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
532 unless (defined $unlinked_item_subfields) {
533 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
535 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
536 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
538 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
539 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
540 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
543 =head2 ModItemTransfer
547 ModItemTransfer($itenumber, $frombranch, $tobranch);
551 Marks an item as being transferred from one branch
556 sub ModItemTransfer {
557 my ( $itemnumber, $frombranch, $tobranch ) = @_;
559 my $dbh = C4::Context->dbh;
561 #new entry in branchtransfers....
562 my $sth = $dbh->prepare(
563 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
564 VALUES (?, ?, NOW(), ?)");
565 $sth->execute($itemnumber, $frombranch, $tobranch);
567 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
568 ModDateLastSeen($itemnumber);
572 =head2 ModDateLastSeen
576 ModDateLastSeen($itemnum);
580 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
581 C<$itemnum> is the item number
585 sub ModDateLastSeen {
586 my ($itemnumber) = @_;
588 my $today = C4::Dates->new();
589 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
596 DelItem($biblionumber, $itemnumber);
600 Exported function (core API) for deleting an item record in Koha.
605 my ( $dbh, $biblionumber, $itemnumber ) = @_;
607 # FIXME check the item has no current issues
609 _koha_delete_item( $dbh, $itemnumber );
611 # get the MARC record
612 my $record = GetMarcBiblio($biblionumber);
613 my $frameworkcode = GetFrameworkCode($biblionumber);
616 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
617 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
619 #search item field code
620 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
621 my @fields = $record->field($itemtag);
623 # delete the item specified
624 foreach my $field (@fields) {
625 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
626 $record->delete_field($field);
629 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
630 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
633 =head2 CheckItemPreSave
637 my $item_ref = TransformMarcToKoha($marc, 'items');
639 my %errors = CheckItemPreSave($item_ref);
640 if (exists $errors{'duplicate_barcode'}) {
641 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
642 } elsif (exists $errors{'invalid_homebranch'}) {
643 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
644 } elsif (exists $errors{'invalid_holdingbranch'}) {
645 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
652 Given a hashref containing item fields, determine if it can be
653 inserted or updated in the database. Specifically, checks for
654 database integrity issues, and returns a hash containing any
655 of the following keys, if applicable.
659 =item duplicate_barcode
661 Barcode, if it duplicates one already found in the database.
663 =item invalid_homebranch
665 Home branch, if not defined in branches table.
667 =item invalid_holdingbranch
669 Holding branch, if not defined in branches table.
673 This function does NOT implement any policy-related checks,
674 e.g., whether current operator is allowed to save an
675 item that has a given branch code.
679 sub CheckItemPreSave {
680 my $item_ref = shift;
684 # check for duplicate barcode
685 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
686 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
687 if ($existing_itemnumber) {
688 if (!exists $item_ref->{'itemnumber'} # new item
689 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
690 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
695 # check for valid home branch
696 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
697 my $branch_name = GetBranchName($item_ref->{'homebranch'});
698 unless (defined $branch_name) {
699 # relies on fact that branches.branchname is a non-NULL column,
700 # so GetBranchName returns undef only if branch does not exist
701 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
705 # check for valid holding branch
706 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
707 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
708 unless (defined $branch_name) {
709 # relies on fact that branches.branchname is a non-NULL column,
710 # so GetBranchName returns undef only if branch does not exist
711 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
719 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
721 The following functions provide various ways of
722 getting an item record, a set of item records, or
723 lists of authorized values for certain item fields.
725 Some of the functions in this group are candidates
726 for refactoring -- for example, some of the code
727 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
728 has copy-and-paste work.
736 $itemstatushash = GetItemStatus($fwkcode);
740 Returns a list of valid values for the
741 C<items.notforloan> field.
743 NOTE: does B<not> return an individual item's
746 Can be MARC dependant.
748 But basically could be can be loan or not
749 Create a status selector with the following code
751 =head3 in PERL SCRIPT
755 my $itemstatushash = getitemstatus;
757 foreach my $thisstatus (keys %$itemstatushash) {
758 my %row =(value => $thisstatus,
759 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
761 push @itemstatusloop, \%row;
763 $template->param(statusloop=>\@itemstatusloop);
771 <select name="statusloop">
772 <option value="">Default</option>
773 <!-- TMPL_LOOP name="statusloop" -->
774 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
784 # returns a reference to a hash of references to status...
787 my $dbh = C4::Context->dbh;
789 $fwk = '' unless ($fwk);
790 my ( $tag, $subfield ) =
791 GetMarcFromKohaField( "items.notforloan", $fwk );
792 if ( $tag and $subfield ) {
795 "SELECT authorised_value
796 FROM marc_subfield_structure
802 $sth->execute( $tag, $subfield, $fwk );
803 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
806 "SELECT authorised_value,lib
807 FROM authorised_values
812 $authvalsth->execute($authorisedvaluecat);
813 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
814 $itemstatus{$authorisedvalue} = $lib;
828 $itemstatus{"1"} = "Not For Loan";
832 =head2 GetItemLocation
836 $itemlochash = GetItemLocation($fwk);
840 Returns a list of valid values for the
841 C<items.location> field.
843 NOTE: does B<not> return an individual item's
846 where fwk stands for an optional framework code.
847 Create a location selector with the following code
849 =head3 in PERL SCRIPT
853 my $itemlochash = getitemlocation;
855 foreach my $thisloc (keys %$itemlochash) {
856 my $selected = 1 if $thisbranch eq $branch;
857 my %row =(locval => $thisloc,
858 selected => $selected,
859 locname => $itemlochash->{$thisloc},
861 push @itemlocloop, \%row;
863 $template->param(itemlocationloop => \@itemlocloop);
871 <select name="location">
872 <option value="">Default</option>
873 <!-- TMPL_LOOP name="itemlocationloop" -->
874 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
882 sub GetItemLocation {
884 # returns a reference to a hash of references to location...
887 my $dbh = C4::Context->dbh;
889 $fwk = '' unless ($fwk);
890 my ( $tag, $subfield ) =
891 GetMarcFromKohaField( "items.location", $fwk );
892 if ( $tag and $subfield ) {
895 "SELECT authorised_value
896 FROM marc_subfield_structure
901 $sth->execute( $tag, $subfield, $fwk );
902 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
905 "SELECT authorised_value,lib
906 FROM authorised_values
910 $authvalsth->execute($authorisedvaluecat);
911 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
912 $itemlocation{$authorisedvalue} = $lib;
914 return \%itemlocation;
926 $itemlocation{"1"} = "Not For Loan";
927 return \%itemlocation;
934 $items = GetLostItems( $where, $orderby );
938 This function gets a list of lost items.
944 C<$where> is a hashref. it containts a field of the items table as key
945 and the value to match as value. For example:
947 { barcode => 'abc123',
948 homebranch => 'CPL', }
950 C<$orderby> is a field of the items table by which the resultset
955 C<$items> is a reference to an array full of hashrefs with columns
956 from the "items" table as keys.
958 =item usage in the perl script:
960 my $where = { barcode => '0001548' };
961 my $items = GetLostItems( $where, "homebranch" );
962 $template->param( itemsloop => $items );
969 # Getting input args.
972 my $dbh = C4::Context->dbh;
977 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
978 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
979 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
981 authorised_values.category = 'LOST'
982 AND itemlost IS NOT NULL
985 my @query_parameters;
986 foreach my $key (keys %$where) {
987 $query .= " AND $key LIKE ?";
988 push @query_parameters, "%$where->{$key}%";
990 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
992 if ( defined $orderby && grep($orderby, @ordervalues)) {
993 $query .= ' ORDER BY '.$orderby;
996 my $sth = $dbh->prepare($query);
997 $sth->execute( @query_parameters );
999 while ( my $row = $sth->fetchrow_hashref ){
1005 =head2 GetItemsForInventory
1009 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size, $statushash);
1013 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1015 The sub returns a reference to a list of hashes, each containing
1016 itemnumber, author, title, barcode, item callnumber, and date last
1017 seen. It is ordered by callnumber then title.
1019 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1020 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1021 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1022 $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.
1026 sub GetItemsForInventory {
1027 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branch, $offset, $size, $statushash ) = @_;
1028 my $dbh = C4::Context->dbh;
1029 my ( @bind_params, @where_strings );
1031 my $query = <<'END_SQL';
1032 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
1034 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1035 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1038 for my $authvfield (keys %$statushash){
1039 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1040 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1041 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1047 push @where_strings, 'itemcallnumber >= ?';
1048 push @bind_params, $minlocation;
1052 push @where_strings, 'itemcallnumber <= ?';
1053 push @bind_params, $maxlocation;
1056 if ($datelastseen) {
1057 $datelastseen = format_date_in_iso($datelastseen);
1058 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1059 push @bind_params, $datelastseen;
1063 push @where_strings, 'items.location = ?';
1064 push @bind_params, $location;
1068 push @where_strings, 'items.homebranch = ?';
1069 push @bind_params, $branch;
1073 push @where_strings, 'biblioitems.itemtype = ?';
1074 push @bind_params, $itemtype;
1077 if ( $ignoreissued) {
1078 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1079 push @where_strings, 'issues.date_due IS NULL';
1082 if ( @where_strings ) {
1084 $query .= join ' AND ', @where_strings;
1086 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1087 my $sth = $dbh->prepare($query);
1088 $sth->execute( @bind_params );
1092 while ( my $row = $sth->fetchrow_hashref ) {
1093 $offset-- if ($offset);
1094 $row->{datelastseen}=format_date($row->{datelastseen});
1095 if ( ( !$offset ) && $size ) {
1096 push @results, $row;
1103 =head2 GetItemsCount
1106 $count = &GetItemsCount( $biblionumber);
1110 This function return count of item with $biblionumber
1115 my ( $biblionumber ) = @_;
1116 my $dbh = C4::Context->dbh;
1117 my $query = "SELECT count(*)
1119 WHERE biblionumber=?";
1120 my $sth = $dbh->prepare($query);
1121 $sth->execute($biblionumber);
1122 my $count = $sth->fetchrow;
1126 =head2 GetItemInfosOf
1130 GetItemInfosOf(@itemnumbers);
1136 sub GetItemInfosOf {
1137 my @itemnumbers = @_;
1142 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1144 return get_infos_of( $query, 'itemnumber' );
1147 =head2 GetItemsByBiblioitemnumber
1151 GetItemsByBiblioitemnumber($biblioitemnumber);
1155 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1156 Called by C<C4::XISBN>
1160 sub GetItemsByBiblioitemnumber {
1161 my ( $bibitem ) = @_;
1162 my $dbh = C4::Context->dbh;
1163 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1164 # Get all items attached to a biblioitem
1167 $sth->execute($bibitem) || die $sth->errstr;
1168 while ( my $data = $sth->fetchrow_hashref ) {
1169 # Foreach item, get circulation information
1170 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1171 WHERE itemnumber = ?
1172 AND issues.borrowernumber = borrowers.borrowernumber"
1174 $sth2->execute( $data->{'itemnumber'} );
1175 if ( my $data2 = $sth2->fetchrow_hashref ) {
1176 # if item is out, set the due date and who it is out too
1177 $data->{'date_due'} = $data2->{'date_due'};
1178 $data->{'cardnumber'} = $data2->{'cardnumber'};
1179 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1182 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1183 $data->{'date_due'} = '';
1185 # Find the last 3 people who borrowed this item.
1186 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1187 AND old_issues.borrowernumber = borrowers.borrowernumber
1188 ORDER BY returndate desc,timestamp desc LIMIT 3";
1189 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1190 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1192 while ( my $data2 = $sth2->fetchrow_hashref ) {
1193 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1194 $data->{"card$i2"} = $data2->{'cardnumber'};
1195 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1198 push(@results,$data);
1207 @results = GetItemsInfo($biblionumber, $type);
1211 Returns information about books with the given biblionumber.
1213 C<$type> may be either C<intra> or anything else. If it is not set to
1214 C<intra>, then the search will exclude lost, very overdue, and
1217 C<GetItemsInfo> returns a list of references-to-hash. Each element
1218 contains a number of keys. Most of them are table items from the
1219 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1220 Koha database. Other keys include:
1224 =item C<$data-E<gt>{branchname}>
1226 The name (not the code) of the branch to which the book belongs.
1228 =item C<$data-E<gt>{datelastseen}>
1230 This is simply C<items.datelastseen>, except that while the date is
1231 stored in YYYY-MM-DD format in the database, here it is converted to
1232 DD/MM/YYYY format. A NULL date is returned as C<//>.
1234 =item C<$data-E<gt>{datedue}>
1236 =item C<$data-E<gt>{class}>
1238 This is the concatenation of C<biblioitems.classification>, the book's
1239 Dewey code, and C<biblioitems.subclass>.
1241 =item C<$data-E<gt>{ocount}>
1243 I think this is the number of copies of the book available.
1245 =item C<$data-E<gt>{order}>
1247 If this is set, it is set to C<One Order>.
1254 my ( $biblionumber, $type ) = @_;
1255 my $dbh = C4::Context->dbh;
1256 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1262 biblioitems.itemtype,
1265 biblioitems.publicationyear,
1266 biblioitems.publishercode,
1267 biblioitems.volumedate,
1268 biblioitems.volumedesc,
1271 items.notforloan as itemnotforloan,
1272 itemtypes.description
1274 LEFT JOIN branches ON items.homebranch = branches.branchcode
1275 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1276 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1277 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1278 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1279 $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1280 my $sth = $dbh->prepare($query);
1281 $sth->execute($biblionumber);
1286 my $isth = $dbh->prepare(
1287 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1288 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1289 WHERE itemnumber = ?"
1291 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1292 while ( my $data = $sth->fetchrow_hashref ) {
1295 $isth->execute( $data->{'itemnumber'} );
1296 if ( my $idata = $isth->fetchrow_hashref ) {
1297 $data->{borrowernumber} = $idata->{borrowernumber};
1298 $data->{cardnumber} = $idata->{cardnumber};
1299 $data->{surname} = $idata->{surname};
1300 $data->{firstname} = $idata->{firstname};
1301 $datedue = $idata->{'date_due'};
1302 if (C4::Context->preference("IndependantBranches")){
1303 my $userenv = C4::Context->userenv;
1304 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1305 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1309 if ( $data->{'serial'}) {
1310 $ssth->execute($data->{'itemnumber'}) ;
1311 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1314 if ( $datedue eq '' ) {
1315 my ( $restype, $reserves ) =
1316 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1317 # Previous conditional check with if ($restype) is not needed because a true
1318 # result for one item will result in subsequent items defaulting to this true
1320 $count_reserves = $restype;
1322 #get branch information.....
1323 my $bsth = $dbh->prepare(
1324 "SELECT * FROM branches WHERE branchcode = ?
1327 $bsth->execute( $data->{'holdingbranch'} );
1328 if ( my $bdata = $bsth->fetchrow_hashref ) {
1329 $data->{'branchname'} = $bdata->{'branchname'};
1331 $data->{'datedue'} = $datedue;
1332 $data->{'count_reserves'} = $count_reserves;
1334 # get notforloan complete status if applicable
1335 my $sthnflstatus = $dbh->prepare(
1336 'SELECT authorised_value
1337 FROM marc_subfield_structure
1338 WHERE kohafield="items.notforloan"
1342 $sthnflstatus->execute;
1343 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1344 if ($authorised_valuecode) {
1345 $sthnflstatus = $dbh->prepare(
1346 "SELECT lib FROM authorised_values
1348 AND authorised_value=?"
1350 $sthnflstatus->execute( $authorised_valuecode,
1351 $data->{itemnotforloan} );
1352 my ($lib) = $sthnflstatus->fetchrow;
1353 $data->{notforloanvalue} = $lib;
1355 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1357 # my stack procedures
1358 my $stackstatus = $dbh->prepare(
1359 'SELECT authorised_value
1360 FROM marc_subfield_structure
1361 WHERE kohafield="items.stack"
1364 $stackstatus->execute;
1366 ($authorised_valuecode) = $stackstatus->fetchrow;
1367 if ($authorised_valuecode) {
1368 $stackstatus = $dbh->prepare(
1370 FROM authorised_values
1372 AND authorised_value=?
1375 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1376 my ($lib) = $stackstatus->fetchrow;
1377 $data->{stack} = $lib;
1379 # Find the last 3 people who borrowed this item.
1380 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1381 WHERE itemnumber = ?
1382 AND old_issues.borrowernumber = borrowers.borrowernumber
1383 ORDER BY returndate DESC
1385 $sth2->execute($data->{'itemnumber'});
1387 while (my $data2 = $sth2->fetchrow_hashref()) {
1388 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1389 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1390 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1394 $results[$i] = $data;
1398 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1404 =head2 GetLastAcquisitions
1408 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 'itemtypes' => ('BK','BD')}, 10);
1414 sub GetLastAcquisitions {
1415 my ($data,$max) = @_;
1417 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1419 my $number_of_branches = @{$data->{branches}};
1420 my $number_of_itemtypes = @{$data->{itemtypes}};
1423 my @where = ('WHERE 1 ');
1424 $number_of_branches and push @where
1425 , 'AND holdingbranch IN ('
1426 , join(',', ('?') x $number_of_branches )
1430 $number_of_itemtypes and push @where
1431 , "AND $itemtype IN ("
1432 , join(',', ('?') x $number_of_itemtypes )
1436 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1437 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1438 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1440 GROUP BY biblio.biblionumber
1441 ORDER BY dateaccessioned DESC LIMIT $max";
1443 my $dbh = C4::Context->dbh;
1444 my $sth = $dbh->prepare($query);
1446 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1449 while( my $row = $sth->fetchrow_hashref){
1450 push @results, {date => $row->{dateaccessioned}
1451 , biblionumber => $row->{biblionumber}
1452 , title => $row->{title}};
1458 =head2 get_itemnumbers_of
1462 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1466 Given a list of biblionumbers, return the list of corresponding itemnumbers
1467 for each biblionumber.
1469 Return a reference on a hash where keys are biblionumbers and values are
1470 references on array of itemnumbers.
1474 sub get_itemnumbers_of {
1475 my @biblionumbers = @_;
1477 my $dbh = C4::Context->dbh;
1483 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1485 my $sth = $dbh->prepare($query);
1486 $sth->execute(@biblionumbers);
1490 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1491 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1494 return \%itemnumbers_of;
1497 =head2 GetItemnumberFromBarcode
1501 $result = GetItemnumberFromBarcode($barcode);
1507 sub GetItemnumberFromBarcode {
1509 my $dbh = C4::Context->dbh;
1512 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1513 $rq->execute($barcode);
1514 my ($result) = $rq->fetchrow;
1518 =head3 get_item_authorised_values
1520 find the types and values for all authorised values assigned to this item.
1525 returns: a hashref malling the authorised value to the value set for this itemnumber
1527 $authorised_values = {
1533 'RESTRICTED' => undef,
1536 'branches' => 'CPL',
1537 'cn_source' => undef,
1538 'itemtypes' => 'SER',
1541 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1545 sub get_item_authorised_values {
1546 my $itemnumber = shift;
1548 # assume that these entries in the authorised_value table are item level.
1549 my $query = q(SELECT distinct authorised_value, kohafield
1550 FROM marc_subfield_structure
1551 WHERE kohafield like 'item%'
1552 AND authorised_value != '' );
1554 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1555 my $iteminfo = GetItem( $itemnumber );
1556 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1558 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1559 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1560 $field =~ s/^items\.//;
1561 if ( exists $iteminfo->{ $field } ) {
1562 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1565 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1569 =head3 get_authorised_value_images
1571 find a list of icons that are appropriate for display based on the
1572 authorised values for a biblio.
1574 parameters: listref of authorised values, such as comes from
1575 get_item_authorised_values or
1576 from C4::Biblio::get_biblio_authorised_values
1578 returns: listref of hashrefs for each image. Each hashref looks like
1581 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1586 Notes: Currently, I put on the full path to the images on the staff
1587 side. This should either be configurable or not done at all. Since I
1588 have to deal with 'intranet' or 'opac' in
1589 get_biblio_authorised_values, perhaps I should be passing it in.
1593 sub get_authorised_value_images {
1594 my $authorised_values = shift;
1598 my $authorised_value_list = GetAuthorisedValues();
1599 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1600 foreach my $this_authorised_value ( @$authorised_value_list ) {
1601 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1602 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1603 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1604 if ( defined $this_authorised_value->{'imageurl'} ) {
1605 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1606 label => $this_authorised_value->{'lib'},
1607 category => $this_authorised_value->{'category'},
1608 value => $this_authorised_value->{'authorised_value'}, };
1613 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1618 =head1 LIMITED USE FUNCTIONS
1620 The following functions, while part of the public API,
1621 are not exported. This is generally because they are
1622 meant to be used by only one script for a specific
1623 purpose, and should not be used in any other context
1624 without careful thought.
1632 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1636 Returns MARC::Record of the item passed in parameter.
1637 This function is meant for use only in C<cataloguing/additem.pl>,
1638 where it is needed to support that script's MARC-like
1644 my ( $biblionumber, $itemnumber ) = @_;
1646 # GetMarcItem has been revised so that it does the following:
1647 # 1. Gets the item information from the items table.
1648 # 2. Converts it to a MARC field for storage in the bib record.
1650 # The previous behavior was:
1651 # 1. Get the bib record.
1652 # 2. Return the MARC tag corresponding to the item record.
1654 # The difference is that one treats the items row as authoritative,
1655 # while the other treats the MARC representation as authoritative
1656 # under certain circumstances.
1658 my $itemrecord = GetItem($itemnumber);
1660 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1661 # Also, don't emit a subfield if the underlying field is blank.
1664 return Item2Marc($itemrecord,$biblionumber);
1668 my ($itemrecord,$biblionumber)=@_;
1671 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1672 } keys %{ $itemrecord }
1674 my $itemmarc = TransformKohaToMarc($mungeditem);
1675 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1677 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1678 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1679 foreach my $field ($itemmarc->field($itemtag)){
1680 $field->add_subfields(@$unlinked_item_subfields);
1686 =head1 PRIVATE FUNCTIONS AND VARIABLES
1688 The following functions are not meant to be called
1689 directly, but are documented in order to explain
1690 the inner workings of C<C4::Items>.
1694 =head2 %derived_columns
1696 This hash keeps track of item columns that
1697 are strictly derived from other columns in
1698 the item record and are not meant to be set
1701 Each key in the hash should be the name of a
1702 column (as named by TransformMarcToKoha). Each
1703 value should be hashref whose keys are the
1704 columns on which the derived column depends. The
1705 hashref should also contain a 'BUILDER' key
1706 that is a reference to a sub that calculates
1711 my %derived_columns = (
1712 'items.cn_sort' => {
1713 'itemcallnumber' => 1,
1714 'items.cn_source' => 1,
1715 'BUILDER' => \&_calc_items_cn_sort,
1719 =head2 _set_derived_columns_for_add
1723 _set_derived_column_for_add($item);
1727 Given an item hash representing a new item to be added,
1728 calculate any derived columns. Currently the only
1729 such column is C<items.cn_sort>.
1733 sub _set_derived_columns_for_add {
1736 foreach my $column (keys %derived_columns) {
1737 my $builder = $derived_columns{$column}->{'BUILDER'};
1738 my $source_values = {};
1739 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1740 next if $source_column eq 'BUILDER';
1741 $source_values->{$source_column} = $item->{$source_column};
1743 $builder->($item, $source_values);
1747 =head2 _set_derived_columns_for_mod
1751 _set_derived_column_for_mod($item);
1755 Given an item hash representing a new item to be modified.
1756 calculate any derived columns. Currently the only
1757 such column is C<items.cn_sort>.
1759 This routine differs from C<_set_derived_columns_for_add>
1760 in that it needs to handle partial item records. In other
1761 words, the caller of C<ModItem> may have supplied only one
1762 or two columns to be changed, so this function needs to
1763 determine whether any of the columns to be changed affect
1764 any of the derived columns. Also, if a derived column
1765 depends on more than one column, but the caller is not
1766 changing all of then, this routine retrieves the unchanged
1767 values from the database in order to ensure a correct
1772 sub _set_derived_columns_for_mod {
1775 foreach my $column (keys %derived_columns) {
1776 my $builder = $derived_columns{$column}->{'BUILDER'};
1777 my $source_values = {};
1778 my %missing_sources = ();
1779 my $must_recalc = 0;
1780 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1781 next if $source_column eq 'BUILDER';
1782 if (exists $item->{$source_column}) {
1784 $source_values->{$source_column} = $item->{$source_column};
1786 $missing_sources{$source_column} = 1;
1790 foreach my $source_column (keys %missing_sources) {
1791 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1793 $builder->($item, $source_values);
1798 =head2 _do_column_fixes_for_mod
1802 _do_column_fixes_for_mod($item);
1806 Given an item hashref containing one or more
1807 columns to modify, fix up certain values.
1808 Specifically, set to 0 any passed value
1809 of C<notforloan>, C<damaged>, C<itemlost>, or
1810 C<wthdrawn> that is either undefined or
1811 contains the empty string.
1815 sub _do_column_fixes_for_mod {
1818 if (exists $item->{'notforloan'} and
1819 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1820 $item->{'notforloan'} = 0;
1822 if (exists $item->{'damaged'} and
1823 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1824 $item->{'damaged'} = 0;
1826 if (exists $item->{'itemlost'} and
1827 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1828 $item->{'itemlost'} = 0;
1830 if (exists $item->{'wthdrawn'} and
1831 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1832 $item->{'wthdrawn'} = 0;
1834 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1835 $item->{'permanent_location'} = $item->{'location'};
1839 =head2 _get_single_item_column
1843 _get_single_item_column($column, $itemnumber);
1847 Retrieves the value of a single column from an C<items>
1848 row specified by C<$itemnumber>.
1852 sub _get_single_item_column {
1854 my $itemnumber = shift;
1856 my $dbh = C4::Context->dbh;
1857 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1858 $sth->execute($itemnumber);
1859 my ($value) = $sth->fetchrow();
1863 =head2 _calc_items_cn_sort
1867 _calc_items_cn_sort($item, $source_values);
1871 Helper routine to calculate C<items.cn_sort>.
1875 sub _calc_items_cn_sort {
1877 my $source_values = shift;
1879 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1882 =head2 _set_defaults_for_add
1886 _set_defaults_for_add($item_hash);
1890 Given an item hash representing an item to be added, set
1891 correct default values for columns whose default value
1892 is not handled by the DBMS. This includes the following
1899 C<items.dateaccessioned>
1921 sub _set_defaults_for_add {
1923 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1924 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1927 =head2 _koha_new_item
1931 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1935 Perform the actual insert into the C<items> table.
1939 sub _koha_new_item {
1940 my ( $item, $barcode ) = @_;
1941 my $dbh=C4::Context->dbh;
1944 "INSERT INTO items SET
1946 biblioitemnumber = ?,
1948 dateaccessioned = ?,
1952 replacementprice = ?,
1953 replacementpricedate = NOW(),
1954 datelastborrowed = ?,
1955 datelastseen = NOW(),
1978 more_subfields_xml = ?,
1981 my $sth = $dbh->prepare($query);
1983 $item->{'biblionumber'},
1984 $item->{'biblioitemnumber'},
1986 $item->{'dateaccessioned'},
1987 $item->{'booksellerid'},
1988 $item->{'homebranch'},
1990 $item->{'replacementprice'},
1991 $item->{datelastborrowed},
1993 $item->{'notforloan'},
1995 $item->{'itemlost'},
1996 $item->{'wthdrawn'},
1997 $item->{'itemcallnumber'},
1998 $item->{'restricted'},
1999 $item->{'itemnotes'},
2000 $item->{'holdingbranch'},
2002 $item->{'location'},
2005 $item->{'renewals'},
2006 $item->{'reserves'},
2007 $item->{'items.cn_source'},
2008 $item->{'items.cn_sort'},
2011 $item->{'materials'},
2013 $item->{'enumchron'},
2014 $item->{'more_subfields_xml'},
2015 $item->{'copynumber'},
2017 my $itemnumber = $dbh->{'mysql_insertid'};
2018 if ( defined $sth->errstr ) {
2019 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2021 return ( $itemnumber, $error );
2024 =head2 MoveItemFromBiblio
2028 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2032 Moves an item from a biblio to another
2034 Returns undef if the move failed or the biblionumber of the destination record otherwise
2036 sub MoveItemFromBiblio {
2037 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2038 my $dbh = C4::Context->dbh;
2039 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2040 $sth->execute( $tobiblio );
2041 my ( $tobiblioitem ) = $sth->fetchrow();
2042 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2043 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2047 my $frameworkcode = GetFrameworkCode($frombiblio);
2049 # Getting marc field for itemnumber
2050 my ($itemtag, $itemsubfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
2052 # Getting the record we want to move the item from
2053 my $record = GetMarcBiblio($frombiblio);
2055 # The item we want to move
2059 foreach my $fielditem ($record->field($itemtag)){
2060 # If it is the item we want to move
2061 if ($fielditem->subfield($itemsubfield) == $itemnumber) {
2064 # Then delete it from the record
2065 $record->delete_field($fielditem)
2069 # If we found an item (should always true, except in case of database-marcxml inconsistency)
2072 # Checking if the item we want to move is in an order
2073 my $order = GetOrderFromItemnumber($itemnumber);
2075 # Replacing the biblionumber within the order if necessary
2076 $order->{'biblionumber'} = $tobiblio;
2080 # Saving the modification
2081 ModBiblioMarc($record, $frombiblio, $frameworkcode);
2083 # Getting the record we want to move the item to
2084 $record = GetMarcBiblio($tobiblio);
2086 # Inserting the previously saved item
2087 $record->insert_fields_ordered($item);
2089 # Saving the modification
2090 ModBiblioMarc($record, $tobiblio, $frameworkcode);
2104 DelItemCheck($dbh, $biblionumber, $itemnumber);
2108 Exported function (core API) for deleting an item record in Koha if there no current issue.
2113 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2116 # check that there is no issue on this item before deletion.
2117 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2118 $sth->execute($itemnumber);
2120 my $onloan=$sth->fetchrow;
2123 $error = "book_on_loan"
2125 # check it doesnt have a waiting reserve
2126 $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
2127 $sth->execute($itemnumber);
2128 my $reserve=$sth->fetchrow;
2130 $error = "book_reserved";
2132 DelItem($dbh, $biblionumber, $itemnumber);
2139 =head2 _koha_modify_item
2143 my ($itemnumber,$error) =_koha_modify_item( $item );
2147 Perform the actual update of the C<items> row. Note that this
2148 routine accepts a hashref specifying the columns to update.
2152 sub _koha_modify_item {
2154 my $dbh=C4::Context->dbh;
2157 my $query = "UPDATE items SET ";
2159 for my $key ( keys %$item ) {
2161 push @bind, $item->{$key};
2164 $query .= " WHERE itemnumber=?";
2165 push @bind, $item->{'itemnumber'};
2166 my $sth = C4::Context->dbh->prepare($query);
2167 $sth->execute(@bind);
2168 if ( C4::Context->dbh->errstr ) {
2169 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2172 return ($item->{'itemnumber'},$error);
2175 =head2 _koha_delete_item
2179 _koha_delete_item( $dbh, $itemnum );
2183 Internal function to delete an item record from the koha tables
2187 sub _koha_delete_item {
2188 my ( $dbh, $itemnum ) = @_;
2190 # save the deleted item to deleteditems table
2191 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2192 $sth->execute($itemnum);
2193 my $data = $sth->fetchrow_hashref();
2194 my $query = "INSERT INTO deleteditems SET ";
2196 foreach my $key ( keys %$data ) {
2197 $query .= "$key = ?,";
2198 push( @bind, $data->{$key} );
2201 $sth = $dbh->prepare($query);
2202 $sth->execute(@bind);
2204 # delete from items table
2205 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2206 $sth->execute($itemnum);
2210 =head2 _marc_from_item_hash
2214 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2218 Given an item hash representing a complete item record,
2219 create a C<MARC::Record> object containing an embedded
2220 tag representing that item.
2222 The third, optional parameter C<$unlinked_item_subfields> is
2223 an arrayref of subfields (not mapped to C<items> fields per the
2224 framework) to be added to the MARC representation
2229 sub _marc_from_item_hash {
2231 my $frameworkcode = shift;
2232 my $unlinked_item_subfields;
2234 $unlinked_item_subfields = shift;
2237 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2238 # Also, don't emit a subfield if the underlying field is blank.
2239 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2240 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2241 : () } keys %{ $item } };
2243 my $item_marc = MARC::Record->new();
2244 foreach my $item_field (keys %{ $mungeditem }) {
2245 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
2246 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2247 if (my $field = $item_marc->field($tag)) {
2248 $field->add_subfields($subfield => $mungeditem->{$item_field});
2250 my $add_subfields = [];
2251 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2252 $add_subfields = $unlinked_item_subfields;
2254 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
2261 =head2 _add_item_field_to_biblio
2265 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2269 Adds the fields from a MARC record containing the
2270 representation of a Koha item record to the MARC
2271 biblio record. The input C<$item_marc> record
2272 is expect to contain just one field, the embedded
2273 item information field.
2277 sub _add_item_field_to_biblio {
2278 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2280 my $biblio_marc = GetMarcBiblio($biblionumber);
2281 foreach my $field ($item_marc->fields()) {
2282 $biblio_marc->append_fields($field);
2285 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2288 =head2 _replace_item_field_in_biblio
2292 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2296 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2297 representation of the item, examine the biblio MARC
2298 for the corresponding tag for that item and
2299 replace it with the tag from C<$item_marc>.
2303 sub _replace_item_field_in_biblio {
2304 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2305 my $dbh = C4::Context->dbh;
2307 # get complete MARC record & replace the item field by the new one
2308 my $completeRecord = GetMarcBiblio($biblionumber);
2309 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2310 my $itemField = $ItemRecord->field($itemtag);
2311 my @items = $completeRecord->field($itemtag);
2314 if ($_->subfield($itemsubfield) eq $itemnumber) {
2315 $_->replace_with($itemField);
2321 # If we haven't found the matching field,
2322 # just add it. However, this means that
2323 # there is likely a bug.
2324 $completeRecord->append_fields($itemField);
2328 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2331 =head2 _repack_item_errors
2333 Add an error message hash generated by C<CheckItemPreSave>
2334 to a list of errors.
2338 sub _repack_item_errors {
2339 my $item_sequence_num = shift;
2340 my $item_ref = shift;
2341 my $error_ref = shift;
2343 my @repacked_errors = ();
2345 foreach my $error_code (sort keys %{ $error_ref }) {
2346 my $repacked_error = {};
2347 $repacked_error->{'item_sequence'} = $item_sequence_num;
2348 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2349 $repacked_error->{'error_code'} = $error_code;
2350 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2351 push @repacked_errors, $repacked_error;
2354 return @repacked_errors;
2357 =head2 _get_unlinked_item_subfields
2361 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2367 sub _get_unlinked_item_subfields {
2368 my $original_item_marc = shift;
2369 my $frameworkcode = shift;
2371 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2373 # assume that this record has only one field, and that that
2374 # field contains only the item information
2376 my @fields = $original_item_marc->fields();
2377 if ($#fields > -1) {
2378 my $field = $fields[0];
2379 my $tag = $field->tag();
2380 foreach my $subfield ($field->subfields()) {
2381 if (defined $subfield->[1] and
2382 $subfield->[1] ne '' and
2383 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2384 push @$subfields, $subfield->[0] => $subfield->[1];
2391 =head2 _get_unlinked_subfields_xml
2395 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2401 sub _get_unlinked_subfields_xml {
2402 my $unlinked_item_subfields = shift;
2405 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2406 my $marc = MARC::Record->new();
2407 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2408 # used in the framework
2409 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2410 $marc->encoding("UTF-8");
2411 $xml = $marc->as_xml("USMARC");
2417 =head2 _parse_unlinked_item_subfields_from_xml
2421 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2427 sub _parse_unlinked_item_subfields_from_xml {
2430 return unless defined $xml and $xml ne "";
2431 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2432 my $unlinked_subfields = [];
2433 my @fields = $marc->fields();
2434 if ($#fields > -1) {
2435 foreach my $subfield ($fields[0]->subfields()) {
2436 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2439 return $unlinked_subfields;