3 # Copyright 2007 LibLime, Inc.
4 # Parts Copyright Biblibre 2010
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #use warnings; FIXME - Bug 2505
28 use C4::Dates qw/format_date format_date_in_iso/;
36 use List::MoreUtils qw/any/;
37 use Data::Dumper; # used as part of logging item record changes, not just for
38 # debugging; so please don't remove this
40 use vars qw($VERSION @ISA @EXPORT);
46 @ISA = qw( Exporter );
69 GetItemsByBiblioitemnumber
73 GetItemnumberFromBarcode
74 GetBarcodeFromItemnumber
86 C4::Items - item management functions
90 This module contains an API for manipulating item
91 records in Koha, and is used by cataloguing, circulation,
92 acquisitions, and serials management.
94 A Koha item record is stored in two places: the
95 items table and embedded in a MARC tag in the XML
96 version of the associated bib record in C<biblioitems.marcxml>.
97 This is done to allow the item information to be readily
98 indexed (e.g., by Zebra), but means that each item
99 modification transaction must keep the items table
100 and the MARC XML in sync at all times.
102 Consequently, all code that creates, modifies, or deletes
103 item records B<must> use an appropriate function from
104 C<C4::Items>. If no existing function is suitable, it is
105 better to add one to C<C4::Items> than to use add
106 one-off SQL statements to add or modify items.
108 The items table will be considered authoritative. In other
109 words, if there is ever a discrepancy between the items
110 table and the MARC XML, the items table should be considered
113 =head1 HISTORICAL NOTE
115 Most of the functions in C<C4::Items> were originally in
116 the C<C4::Biblio> module.
118 =head1 CORE EXPORTED FUNCTIONS
120 The following functions are meant for use by users
127 $item = GetItem($itemnumber,$barcode,$serial);
129 Return item information, for a given itemnumber or barcode.
130 The return value is a hashref mapping item column
131 names to values. If C<$serial> is true, include serial publication data.
136 my ($itemnumber,$barcode, $serial) = @_;
137 my $dbh = C4::Context->dbh;
140 my $sth = $dbh->prepare("
142 WHERE itemnumber = ?");
143 $sth->execute($itemnumber);
144 $data = $sth->fetchrow_hashref;
146 my $sth = $dbh->prepare("
150 $sth->execute($barcode);
151 $data = $sth->fetchrow_hashref;
154 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
155 $ssth->execute($data->{'itemnumber'}) ;
156 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
158 #if we don't have an items.itype, use biblioitems.itemtype.
159 if( ! $data->{'itype'} ) {
160 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
161 $sth->execute($data->{'biblionumber'});
162 ($data->{'itype'}) = $sth->fetchrow_array;
169 CartToShelf($itemnumber);
171 Set the current shelving location of the item record
172 to its stored permanent shelving location. This is
173 primarily used to indicate when an item whose current
174 location is a special processing ('PROC') or shelving cart
175 ('CART') location is back in the stacks.
180 my ( $itemnumber ) = @_;
182 unless ( $itemnumber ) {
183 croak "FAILED CartToShelf() - no itemnumber supplied";
186 my $item = GetItem($itemnumber);
187 $item->{location} = $item->{permanent_location};
188 ModItem($item, undef, $itemnumber);
191 =head2 AddItemFromMarc
193 my ($biblionumber, $biblioitemnumber, $itemnumber)
194 = AddItemFromMarc($source_item_marc, $biblionumber);
196 Given a MARC::Record object containing an embedded item
197 record and a biblionumber, create a new item record.
201 sub AddItemFromMarc {
202 my ( $source_item_marc, $biblionumber ) = @_;
203 my $dbh = C4::Context->dbh;
205 # parse item hash from MARC
206 my $frameworkcode = GetFrameworkCode( $biblionumber );
207 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
209 my $localitemmarc=MARC::Record->new;
210 $localitemmarc->append_fields($source_item_marc->field($itemtag));
211 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
212 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
213 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
218 my ($biblionumber, $biblioitemnumber, $itemnumber)
219 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
221 Given a hash containing item column names as keys,
222 create a new Koha item record.
224 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
225 do not need to be supplied for general use; they exist
226 simply to allow them to be picked up from AddItemFromMarc.
228 The final optional parameter, C<$unlinked_item_subfields>, contains
229 an arrayref containing subfields present in the original MARC
230 representation of the item (e.g., from the item editor) that are
231 not mapped to C<items> columns directly but should instead
232 be stored in C<items.more_subfields_xml> and included in
233 the biblio items tag for display and indexing.
239 my $biblionumber = shift;
241 my $dbh = @_ ? shift : C4::Context->dbh;
242 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
243 my $unlinked_item_subfields;
245 $unlinked_item_subfields = shift
248 # needs old biblionumber and biblioitemnumber
249 $item->{'biblionumber'} = $biblionumber;
250 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
251 $sth->execute( $item->{'biblionumber'} );
252 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
254 _set_defaults_for_add($item);
255 _set_derived_columns_for_add($item);
256 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
257 # FIXME - checks here
258 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
259 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
260 $itype_sth->execute( $item->{'biblionumber'} );
261 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
264 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
265 $item->{'itemnumber'} = $itemnumber;
267 ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
269 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
271 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
274 =head2 AddItemBatchFromMarc
276 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
277 $biblionumber, $biblioitemnumber, $frameworkcode);
279 Efficiently create item records from a MARC biblio record with
280 embedded item fields. This routine is suitable for batch jobs.
282 This API assumes that the bib record has already been
283 saved to the C<biblio> and C<biblioitems> tables. It does
284 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
285 are populated, but it will do so via a call to ModBibiloMarc.
287 The goal of this API is to have a similar effect to using AddBiblio
288 and AddItems in succession, but without inefficient repeated
289 parsing of the MARC XML bib record.
291 This function returns an arrayref of new itemsnumbers and an arrayref of item
292 errors encountered during the processing. Each entry in the errors
293 list is a hashref containing the following keys:
299 Sequence number of original item tag in the MARC record.
303 Item barcode, provide to assist in the construction of
304 useful error messages.
306 =item error_condition
308 Code representing the error condition. Can be 'duplicate_barcode',
309 'invalid_homebranch', or 'invalid_holdingbranch'.
311 =item error_information
313 Additional information appropriate to the error condition.
319 sub AddItemBatchFromMarc {
320 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
322 my @itemnumbers = ();
324 my $dbh = C4::Context->dbh;
326 # loop through the item tags and start creating items
327 my @bad_item_fields = ();
328 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
329 my $item_sequence_num = 0;
330 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
331 $item_sequence_num++;
332 # we take the item field and stick it into a new
333 # MARC record -- this is required so far because (FIXME)
334 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
335 # and there is no TransformMarcFieldToKoha
336 my $temp_item_marc = MARC::Record->new();
337 $temp_item_marc->append_fields($item_field);
339 # add biblionumber and biblioitemnumber
340 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
341 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
342 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
343 $item->{'biblionumber'} = $biblionumber;
344 $item->{'biblioitemnumber'} = $biblioitemnumber;
346 # check for duplicate barcode
347 my %item_errors = CheckItemPreSave($item);
349 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
350 push @bad_item_fields, $item_field;
354 _set_defaults_for_add($item);
355 _set_derived_columns_for_add($item);
356 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
357 warn $error if $error;
358 push @itemnumbers, $itemnumber; # FIXME not checking error
359 $item->{'itemnumber'} = $itemnumber;
361 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
363 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
364 $item_field->replace_with($new_item_marc->field($itemtag));
367 # remove any MARC item fields for rejected items
368 foreach my $item_field (@bad_item_fields) {
369 $record->delete_field($item_field);
372 # update the MARC biblio
373 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
375 return (\@itemnumbers, \@errors);
378 =head2 ModItemFromMarc
380 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
382 This function updates an item record based on a supplied
383 C<MARC::Record> object containing an embedded item field.
384 This API is meant for the use of C<additem.pl>; for
385 other purposes, C<ModItem> should be used.
387 This function uses the hash %default_values_for_mod_from_marc,
388 which contains default values for item fields to
389 apply when modifying an item. This is needed beccause
390 if an item field's value is cleared, TransformMarcToKoha
391 does not include the column in the
392 hash that's passed to ModItem, which without
393 use of this hash makes it impossible to clear
394 an item field's value. See bug 2466.
396 Note that only columns that can be directly
397 changed from the cataloging and serials
398 item editors are included in this hash.
402 my %default_values_for_mod_from_marc = (
404 booksellerid => undef,
406 'items.cn_source' => undef,
409 # dateaccessioned => undef,
411 holdingbranch => undef,
413 itemcallnumber => undef,
422 replacementprice => undef,
423 replacementpricedate => undef,
426 stocknumber => undef,
431 sub ModItemFromMarc {
432 my $item_marc = shift;
433 my $biblionumber = shift;
434 my $itemnumber = shift;
436 my $dbh = C4::Context->dbh;
437 my $frameworkcode = GetFrameworkCode($biblionumber);
438 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
440 my $localitemmarc = MARC::Record->new;
441 $localitemmarc->append_fields( $item_marc->field($itemtag) );
442 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
443 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
444 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
446 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
448 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
453 ModItem({ column => $newvalue }, $biblionumber,
454 $itemnumber[, $original_item_marc]);
456 Change one or more columns in an item record and update
457 the MARC representation of the item.
459 The first argument is a hashref mapping from item column
460 names to the new values. The second and third arguments
461 are the biblionumber and itemnumber, respectively.
463 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
464 an arrayref containing subfields present in the original MARC
465 representation of the item (e.g., from the item editor) that are
466 not mapped to C<items> columns directly but should instead
467 be stored in C<items.more_subfields_xml> and included in
468 the biblio items tag for display and indexing.
470 If one of the changed columns is used to calculate
471 the derived value of a column such as C<items.cn_sort>,
472 this routine will perform the necessary calculation
479 my $biblionumber = shift;
480 my $itemnumber = shift;
482 # if $biblionumber is undefined, get it from the current item
483 unless (defined $biblionumber) {
484 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
487 my $dbh = @_ ? shift : C4::Context->dbh;
488 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
490 my $unlinked_item_subfields;
492 $unlinked_item_subfields = shift;
493 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
496 $item->{'itemnumber'} = $itemnumber or return undef;
497 _set_derived_columns_for_mod($item);
498 _do_column_fixes_for_mod($item);
501 # attempt to change itemnumber
502 # attempt to change biblionumber (if we want
503 # an API to relink an item to a different bib,
504 # it should be a separate function)
507 _koha_modify_item($item);
509 # request that bib be reindexed so that searching on current
510 # item status is possible
511 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
513 logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
516 =head2 ModItemTransfer
518 ModItemTransfer($itenumber, $frombranch, $tobranch);
520 Marks an item as being transferred from one branch
525 sub ModItemTransfer {
526 my ( $itemnumber, $frombranch, $tobranch ) = @_;
528 my $dbh = C4::Context->dbh;
530 #new entry in branchtransfers....
531 my $sth = $dbh->prepare(
532 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
533 VALUES (?, ?, NOW(), ?)");
534 $sth->execute($itemnumber, $frombranch, $tobranch);
536 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
537 ModDateLastSeen($itemnumber);
541 =head2 ModDateLastSeen
543 ModDateLastSeen($itemnum);
545 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
546 C<$itemnum> is the item number
550 sub ModDateLastSeen {
551 my ($itemnumber) = @_;
553 my $today = C4::Dates->new();
554 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
559 DelItem($dbh, $biblionumber, $itemnumber);
561 Exported function (core API) for deleting an item record in Koha.
566 my ( $dbh, $biblionumber, $itemnumber ) = @_;
568 # FIXME check the item has no current issues
570 _koha_delete_item( $dbh, $itemnumber );
572 # get the MARC record
573 my $record = GetMarcBiblio($biblionumber);
574 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
577 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
578 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
580 #search item field code
581 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
584 =head2 CheckItemPreSave
586 my $item_ref = TransformMarcToKoha($marc, 'items');
588 my %errors = CheckItemPreSave($item_ref);
589 if (exists $errors{'duplicate_barcode'}) {
590 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
591 } elsif (exists $errors{'invalid_homebranch'}) {
592 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
593 } elsif (exists $errors{'invalid_holdingbranch'}) {
594 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
599 Given a hashref containing item fields, determine if it can be
600 inserted or updated in the database. Specifically, checks for
601 database integrity issues, and returns a hash containing any
602 of the following keys, if applicable.
606 =item duplicate_barcode
608 Barcode, if it duplicates one already found in the database.
610 =item invalid_homebranch
612 Home branch, if not defined in branches table.
614 =item invalid_holdingbranch
616 Holding branch, if not defined in branches table.
620 This function does NOT implement any policy-related checks,
621 e.g., whether current operator is allowed to save an
622 item that has a given branch code.
626 sub CheckItemPreSave {
627 my $item_ref = shift;
631 # check for duplicate barcode
632 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
633 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
634 if ($existing_itemnumber) {
635 if (!exists $item_ref->{'itemnumber'} # new item
636 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
637 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
642 # check for valid home branch
643 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
644 my $branch_name = GetBranchName($item_ref->{'homebranch'});
645 unless (defined $branch_name) {
646 # relies on fact that branches.branchname is a non-NULL column,
647 # so GetBranchName returns undef only if branch does not exist
648 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
652 # check for valid holding branch
653 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
654 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
655 unless (defined $branch_name) {
656 # relies on fact that branches.branchname is a non-NULL column,
657 # so GetBranchName returns undef only if branch does not exist
658 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
666 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
668 The following functions provide various ways of
669 getting an item record, a set of item records, or
670 lists of authorized values for certain item fields.
672 Some of the functions in this group are candidates
673 for refactoring -- for example, some of the code
674 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
675 has copy-and-paste work.
681 $itemstatushash = GetItemStatus($fwkcode);
683 Returns a list of valid values for the
684 C<items.notforloan> field.
686 NOTE: does B<not> return an individual item's
689 Can be MARC dependant.
691 But basically could be can be loan or not
692 Create a status selector with the following code
694 =head3 in PERL SCRIPT
696 my $itemstatushash = getitemstatus;
698 foreach my $thisstatus (keys %$itemstatushash) {
699 my %row =(value => $thisstatus,
700 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
702 push @itemstatusloop, \%row;
704 $template->param(statusloop=>\@itemstatusloop);
708 <select name="statusloop">
709 <option value="">Default</option>
710 <!-- TMPL_LOOP name="statusloop" -->
711 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
719 # returns a reference to a hash of references to status...
722 my $dbh = C4::Context->dbh;
724 $fwk = '' unless ($fwk);
725 my ( $tag, $subfield ) =
726 GetMarcFromKohaField( "items.notforloan", $fwk );
727 if ( $tag and $subfield ) {
730 "SELECT authorised_value
731 FROM marc_subfield_structure
737 $sth->execute( $tag, $subfield, $fwk );
738 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
741 "SELECT authorised_value,lib
742 FROM authorised_values
747 $authvalsth->execute($authorisedvaluecat);
748 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
749 $itemstatus{$authorisedvalue} = $lib;
763 $itemstatus{"1"} = "Not For Loan";
767 =head2 GetItemLocation
769 $itemlochash = GetItemLocation($fwk);
771 Returns a list of valid values for the
772 C<items.location> field.
774 NOTE: does B<not> return an individual item's
777 where fwk stands for an optional framework code.
778 Create a location selector with the following code
780 =head3 in PERL SCRIPT
782 my $itemlochash = getitemlocation;
784 foreach my $thisloc (keys %$itemlochash) {
785 my $selected = 1 if $thisbranch eq $branch;
786 my %row =(locval => $thisloc,
787 selected => $selected,
788 locname => $itemlochash->{$thisloc},
790 push @itemlocloop, \%row;
792 $template->param(itemlocationloop => \@itemlocloop);
796 <select name="location">
797 <option value="">Default</option>
798 <!-- TMPL_LOOP name="itemlocationloop" -->
799 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
805 sub GetItemLocation {
807 # returns a reference to a hash of references to location...
810 my $dbh = C4::Context->dbh;
812 $fwk = '' unless ($fwk);
813 my ( $tag, $subfield ) =
814 GetMarcFromKohaField( "items.location", $fwk );
815 if ( $tag and $subfield ) {
818 "SELECT authorised_value
819 FROM marc_subfield_structure
824 $sth->execute( $tag, $subfield, $fwk );
825 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
828 "SELECT authorised_value,lib
829 FROM authorised_values
833 $authvalsth->execute($authorisedvaluecat);
834 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
835 $itemlocation{$authorisedvalue} = $lib;
837 return \%itemlocation;
849 $itemlocation{"1"} = "Not For Loan";
850 return \%itemlocation;
855 $items = GetLostItems( $where, $orderby );
857 This function gets a list of lost items.
863 C<$where> is a hashref. it containts a field of the items table as key
864 and the value to match as value. For example:
866 { barcode => 'abc123',
867 homebranch => 'CPL', }
869 C<$orderby> is a field of the items table by which the resultset
874 C<$items> is a reference to an array full of hashrefs with columns
875 from the "items" table as keys.
877 =item usage in the perl script:
879 my $where = { barcode => '0001548' };
880 my $items = GetLostItems( $where, "homebranch" );
881 $template->param( itemsloop => $items );
888 # Getting input args.
891 my $dbh = C4::Context->dbh;
896 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
897 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
898 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
900 authorised_values.category = 'LOST'
901 AND itemlost IS NOT NULL
904 my @query_parameters;
905 foreach my $key (keys %$where) {
906 $query .= " AND $key LIKE ?";
907 push @query_parameters, "%$where->{$key}%";
909 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
911 if ( defined $orderby && grep($orderby, @ordervalues)) {
912 $query .= ' ORDER BY '.$orderby;
915 my $sth = $dbh->prepare($query);
916 $sth->execute( @query_parameters );
918 while ( my $row = $sth->fetchrow_hashref ){
924 =head2 GetItemsForInventory
926 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
927 $location, $itemtype $datelastseen, $branch,
928 $offset, $size, $statushash);
930 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
932 The sub returns a reference to a list of hashes, each containing
933 itemnumber, author, title, barcode, item callnumber, and date last
934 seen. It is ordered by callnumber then title.
936 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
937 the datelastseen can be used to specify that you want to see items not seen since a past date only.
938 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
939 $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.
943 sub GetItemsForInventory {
944 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
945 my $dbh = C4::Context->dbh;
946 my ( @bind_params, @where_strings );
948 my $query = <<'END_SQL';
949 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
951 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
952 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
955 for my $authvfield (keys %$statushash){
956 if ( scalar @{$statushash->{$authvfield}} > 0 ){
957 my $joinedvals = join ',', @{$statushash->{$authvfield}};
958 push @where_strings, "$authvfield in (" . $joinedvals . ")";
964 push @where_strings, 'itemcallnumber >= ?';
965 push @bind_params, $minlocation;
969 push @where_strings, 'itemcallnumber <= ?';
970 push @bind_params, $maxlocation;
974 $datelastseen = format_date_in_iso($datelastseen);
975 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
976 push @bind_params, $datelastseen;
980 push @where_strings, 'items.location = ?';
981 push @bind_params, $location;
985 if($branch eq "homebranch"){
986 push @where_strings, 'items.homebranch = ?';
988 push @where_strings, 'items.holdingbranch = ?';
990 push @bind_params, $branchcode;
994 push @where_strings, 'biblioitems.itemtype = ?';
995 push @bind_params, $itemtype;
998 if ( $ignoreissued) {
999 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1000 push @where_strings, 'issues.date_due IS NULL';
1003 if ( @where_strings ) {
1005 $query .= join ' AND ', @where_strings;
1007 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1008 my $sth = $dbh->prepare($query);
1009 $sth->execute( @bind_params );
1013 while ( my $row = $sth->fetchrow_hashref ) {
1014 $offset-- if ($offset);
1015 $row->{datelastseen}=format_date($row->{datelastseen});
1016 if ( ( !$offset ) && $size ) {
1017 push @results, $row;
1024 =head2 GetItemsCount
1026 $count = &GetItemsCount( $biblionumber);
1028 This function return count of item with $biblionumber
1033 my ( $biblionumber ) = @_;
1034 my $dbh = C4::Context->dbh;
1035 my $query = "SELECT count(*)
1037 WHERE biblionumber=?";
1038 my $sth = $dbh->prepare($query);
1039 $sth->execute($biblionumber);
1040 my $count = $sth->fetchrow;
1044 =head2 GetItemInfosOf
1046 GetItemInfosOf(@itemnumbers);
1050 sub GetItemInfosOf {
1051 my @itemnumbers = @_;
1056 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1058 return get_infos_of( $query, 'itemnumber' );
1061 =head2 GetItemsByBiblioitemnumber
1063 GetItemsByBiblioitemnumber($biblioitemnumber);
1065 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1066 Called by C<C4::XISBN>
1070 sub GetItemsByBiblioitemnumber {
1071 my ( $bibitem ) = @_;
1072 my $dbh = C4::Context->dbh;
1073 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1074 # Get all items attached to a biblioitem
1077 $sth->execute($bibitem) || die $sth->errstr;
1078 while ( my $data = $sth->fetchrow_hashref ) {
1079 # Foreach item, get circulation information
1080 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1081 WHERE itemnumber = ?
1082 AND issues.borrowernumber = borrowers.borrowernumber"
1084 $sth2->execute( $data->{'itemnumber'} );
1085 if ( my $data2 = $sth2->fetchrow_hashref ) {
1086 # if item is out, set the due date and who it is out too
1087 $data->{'date_due'} = $data2->{'date_due'};
1088 $data->{'cardnumber'} = $data2->{'cardnumber'};
1089 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1092 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1093 $data->{'date_due'} = '';
1095 # Find the last 3 people who borrowed this item.
1096 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1097 AND old_issues.borrowernumber = borrowers.borrowernumber
1098 ORDER BY returndate desc,timestamp desc LIMIT 3";
1099 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1100 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1102 while ( my $data2 = $sth2->fetchrow_hashref ) {
1103 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1104 $data->{"card$i2"} = $data2->{'cardnumber'};
1105 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1108 push(@results,$data);
1115 @results = GetItemsInfo($biblionumber);
1117 Returns information about items with the given biblionumber.
1119 C<GetItemsInfo> returns a list of references-to-hash. Each element
1120 contains a number of keys. Most of them are attributes from the
1121 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1122 Koha database. Other keys include:
1126 =item C<$data-E<gt>{branchname}>
1128 The name (not the code) of the branch to which the book belongs.
1130 =item C<$data-E<gt>{datelastseen}>
1132 This is simply C<items.datelastseen>, except that while the date is
1133 stored in YYYY-MM-DD format in the database, here it is converted to
1134 DD/MM/YYYY format. A NULL date is returned as C<//>.
1136 =item C<$data-E<gt>{datedue}>
1138 =item C<$data-E<gt>{class}>
1140 This is the concatenation of C<biblioitems.classification>, the book's
1141 Dewey code, and C<biblioitems.subclass>.
1143 =item C<$data-E<gt>{ocount}>
1145 I think this is the number of copies of the book available.
1147 =item C<$data-E<gt>{order}>
1149 If this is set, it is set to C<One Order>.
1156 my ( $biblionumber ) = @_;
1157 my $dbh = C4::Context->dbh;
1158 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1164 biblioitems.itemtype,
1167 biblioitems.publicationyear,
1168 biblioitems.publishercode,
1169 biblioitems.volumedate,
1170 biblioitems.volumedesc,
1173 items.notforloan as itemnotforloan,
1174 itemtypes.description,
1175 itemtypes.notforloan as notforloan_per_itemtype,
1178 LEFT JOIN branches ON items.homebranch = branches.branchcode
1179 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1180 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1181 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1182 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1183 $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1184 my $sth = $dbh->prepare($query);
1185 $sth->execute($biblionumber);
1190 my $isth = $dbh->prepare(
1191 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1192 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1193 WHERE itemnumber = ?"
1195 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1196 while ( my $data = $sth->fetchrow_hashref ) {
1199 $isth->execute( $data->{'itemnumber'} );
1200 if ( my $idata = $isth->fetchrow_hashref ) {
1201 $data->{borrowernumber} = $idata->{borrowernumber};
1202 $data->{cardnumber} = $idata->{cardnumber};
1203 $data->{surname} = $idata->{surname};
1204 $data->{firstname} = $idata->{firstname};
1205 $datedue = $idata->{'date_due'};
1206 if (C4::Context->preference("IndependantBranches")){
1207 my $userenv = C4::Context->userenv;
1208 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1209 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1213 if ( $data->{'serial'}) {
1214 $ssth->execute($data->{'itemnumber'}) ;
1215 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1218 if ( $datedue eq '' ) {
1219 my ( $restype, $reserves ) =
1220 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1221 # Previous conditional check with if ($restype) is not needed because a true
1222 # result for one item will result in subsequent items defaulting to this true
1224 $count_reserves = $restype;
1226 #get branch information.....
1227 my $bsth = $dbh->prepare(
1228 "SELECT * FROM branches WHERE branchcode = ?
1231 $bsth->execute( $data->{'holdingbranch'} );
1232 if ( my $bdata = $bsth->fetchrow_hashref ) {
1233 $data->{'branchname'} = $bdata->{'branchname'};
1235 $data->{'datedue'} = $datedue;
1236 $data->{'count_reserves'} = $count_reserves;
1238 # get notforloan complete status if applicable
1239 my $sthnflstatus = $dbh->prepare(
1240 'SELECT authorised_value
1241 FROM marc_subfield_structure
1242 WHERE kohafield="items.notforloan"
1246 $sthnflstatus->execute;
1247 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1248 if ($authorised_valuecode) {
1249 $sthnflstatus = $dbh->prepare(
1250 "SELECT lib FROM authorised_values
1252 AND authorised_value=?"
1254 $sthnflstatus->execute( $authorised_valuecode,
1255 $data->{itemnotforloan} );
1256 my ($lib) = $sthnflstatus->fetchrow;
1257 $data->{notforloanvalue} = $lib;
1260 # get restricted status and description if applicable
1261 my $restrictedstatus = $dbh->prepare(
1262 'SELECT authorised_value
1263 FROM marc_subfield_structure
1264 WHERE kohafield="items.restricted"
1268 $restrictedstatus->execute;
1269 ($authorised_valuecode) = $restrictedstatus->fetchrow;
1270 if ($authorised_valuecode) {
1271 $restrictedstatus = $dbh->prepare(
1272 "SELECT lib,lib_opac FROM authorised_values
1274 AND authorised_value=?"
1276 $restrictedstatus->execute( $authorised_valuecode,
1277 $data->{restricted} );
1279 if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1280 $data->{restricted} = $rstdata->{'lib'};
1281 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1285 # my stack procedures
1286 my $stackstatus = $dbh->prepare(
1287 'SELECT authorised_value
1288 FROM marc_subfield_structure
1289 WHERE kohafield="items.stack"
1292 $stackstatus->execute;
1294 ($authorised_valuecode) = $stackstatus->fetchrow;
1295 if ($authorised_valuecode) {
1296 $stackstatus = $dbh->prepare(
1298 FROM authorised_values
1300 AND authorised_value=?
1303 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1304 my ($lib) = $stackstatus->fetchrow;
1305 $data->{stack} = $lib;
1307 # Find the last 3 people who borrowed this item.
1308 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1309 WHERE itemnumber = ?
1310 AND old_issues.borrowernumber = borrowers.borrowernumber
1311 ORDER BY returndate DESC
1313 $sth2->execute($data->{'itemnumber'});
1315 while (my $data2 = $sth2->fetchrow_hashref()) {
1316 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1317 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1318 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1322 $results[$i] = $data;
1326 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1332 =head2 GetItemsLocationInfo
1334 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1336 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1338 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1342 =item C<$data-E<gt>{homebranch}>
1344 Branch Name of the item's homebranch
1346 =item C<$data-E<gt>{holdingbranch}>
1348 Branch Name of the item's holdingbranch
1350 =item C<$data-E<gt>{location}>
1352 Item's shelving location code
1354 =item C<$data-E<gt>{location_intranet}>
1356 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1358 =item C<$data-E<gt>{location_opac}>
1360 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1363 =item C<$data-E<gt>{itemcallnumber}>
1365 Item's itemcallnumber
1367 =item C<$data-E<gt>{cn_sort}>
1369 Item's call number normalized for sorting
1375 sub GetItemsLocationInfo {
1376 my $biblionumber = shift;
1379 my $dbh = C4::Context->dbh;
1380 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1381 location, itemcallnumber, cn_sort
1382 FROM items, branches as a, branches as b
1383 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1384 AND biblionumber = ?
1385 ORDER BY cn_sort ASC";
1386 my $sth = $dbh->prepare($query);
1387 $sth->execute($biblionumber);
1389 while ( my $data = $sth->fetchrow_hashref ) {
1390 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1391 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1392 push @results, $data;
1398 =head2 GetLastAcquisitions
1400 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1401 'itemtypes' => ('BK','BD')}, 10);
1405 sub GetLastAcquisitions {
1406 my ($data,$max) = @_;
1408 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1410 my $number_of_branches = @{$data->{branches}};
1411 my $number_of_itemtypes = @{$data->{itemtypes}};
1414 my @where = ('WHERE 1 ');
1415 $number_of_branches and push @where
1416 , 'AND holdingbranch IN ('
1417 , join(',', ('?') x $number_of_branches )
1421 $number_of_itemtypes and push @where
1422 , "AND $itemtype IN ("
1423 , join(',', ('?') x $number_of_itemtypes )
1427 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1428 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1429 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1431 GROUP BY biblio.biblionumber
1432 ORDER BY dateaccessioned DESC LIMIT $max";
1434 my $dbh = C4::Context->dbh;
1435 my $sth = $dbh->prepare($query);
1437 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1440 while( my $row = $sth->fetchrow_hashref){
1441 push @results, {date => $row->{dateaccessioned}
1442 , biblionumber => $row->{biblionumber}
1443 , title => $row->{title}};
1449 =head2 get_itemnumbers_of
1451 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1453 Given a list of biblionumbers, return the list of corresponding itemnumbers
1454 for each biblionumber.
1456 Return a reference on a hash where keys are biblionumbers and values are
1457 references on array of itemnumbers.
1461 sub get_itemnumbers_of {
1462 my @biblionumbers = @_;
1464 my $dbh = C4::Context->dbh;
1470 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1472 my $sth = $dbh->prepare($query);
1473 $sth->execute(@biblionumbers);
1477 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1478 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1481 return \%itemnumbers_of;
1484 =head2 GetItemnumberFromBarcode
1486 $result = GetItemnumberFromBarcode($barcode);
1490 sub GetItemnumberFromBarcode {
1492 my $dbh = C4::Context->dbh;
1495 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1496 $rq->execute($barcode);
1497 my ($result) = $rq->fetchrow;
1501 =head2 GetBarcodeFromItemnumber
1503 $result = GetBarcodeFromItemnumber($itemnumber);
1507 sub GetBarcodeFromItemnumber {
1508 my ($itemnumber) = @_;
1509 my $dbh = C4::Context->dbh;
1512 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1513 $rq->execute($itemnumber);
1514 my ($result) = $rq->fetchrow;
1518 =head2 GetHiddenItemnumbers
1522 $result = GetHiddenItemnumbers(@items);
1528 sub GetHiddenItemnumbers {
1532 my $yaml = C4::Context->preference('OpacHiddenItems');
1535 $hidingrules = YAML::Load($yaml);
1538 warn "Unable to parse OpacHiddenItems syspref : $@";
1541 my $dbh = C4::Context->dbh;
1544 foreach my $item (@items) {
1546 # We check each rule
1547 foreach my $field (keys %$hidingrules) {
1548 my $query = "SELECT $field from items where itemnumber = ?";
1549 my $sth = $dbh->prepare($query);
1550 $sth->execute($item->{'itemnumber'});
1551 my ($result) = $sth->fetchrow;
1553 # If the results matches the values in the yaml file
1554 if (any { $result eq $_ } @{$hidingrules->{$field}}) {
1556 # We add the itemnumber to the list
1557 push @resultitems, $item->{'itemnumber'};
1559 # If at least one rule matched for an item, no need to test the others
1564 return @resultitems;
1569 =head3 get_item_authorised_values
1571 find the types and values for all authorised values assigned to this item.
1573 parameters: itemnumber
1575 returns: a hashref malling the authorised value to the value set for this itemnumber
1577 $authorised_values = {
1583 'RESTRICTED' => undef,
1586 'branches' => 'CPL',
1587 'cn_source' => undef,
1588 'itemtypes' => 'SER',
1591 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1595 sub get_item_authorised_values {
1596 my $itemnumber = shift;
1598 # assume that these entries in the authorised_value table are item level.
1599 my $query = q(SELECT distinct authorised_value, kohafield
1600 FROM marc_subfield_structure
1601 WHERE kohafield like 'item%'
1602 AND authorised_value != '' );
1604 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1605 my $iteminfo = GetItem( $itemnumber );
1606 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1608 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1609 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1610 $field =~ s/^items\.//;
1611 if ( exists $iteminfo->{ $field } ) {
1612 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1615 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1619 =head3 get_authorised_value_images
1621 find a list of icons that are appropriate for display based on the
1622 authorised values for a biblio.
1624 parameters: listref of authorised values, such as comes from
1625 get_item_authorised_values or
1626 from C4::Biblio::get_biblio_authorised_values
1628 returns: listref of hashrefs for each image. Each hashref looks like this:
1630 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1635 Notes: Currently, I put on the full path to the images on the staff
1636 side. This should either be configurable or not done at all. Since I
1637 have to deal with 'intranet' or 'opac' in
1638 get_biblio_authorised_values, perhaps I should be passing it in.
1642 sub get_authorised_value_images {
1643 my $authorised_values = shift;
1647 my $authorised_value_list = GetAuthorisedValues();
1648 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1649 foreach my $this_authorised_value ( @$authorised_value_list ) {
1650 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1651 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1652 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1653 if ( defined $this_authorised_value->{'imageurl'} ) {
1654 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1655 label => $this_authorised_value->{'lib'},
1656 category => $this_authorised_value->{'category'},
1657 value => $this_authorised_value->{'authorised_value'}, };
1662 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1667 =head1 LIMITED USE FUNCTIONS
1669 The following functions, while part of the public API,
1670 are not exported. This is generally because they are
1671 meant to be used by only one script for a specific
1672 purpose, and should not be used in any other context
1673 without careful thought.
1679 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1681 Returns MARC::Record of the item passed in parameter.
1682 This function is meant for use only in C<cataloguing/additem.pl>,
1683 where it is needed to support that script's MARC-like
1689 my ( $biblionumber, $itemnumber ) = @_;
1691 # GetMarcItem has been revised so that it does the following:
1692 # 1. Gets the item information from the items table.
1693 # 2. Converts it to a MARC field for storage in the bib record.
1695 # The previous behavior was:
1696 # 1. Get the bib record.
1697 # 2. Return the MARC tag corresponding to the item record.
1699 # The difference is that one treats the items row as authoritative,
1700 # while the other treats the MARC representation as authoritative
1701 # under certain circumstances.
1703 my $itemrecord = GetItem($itemnumber);
1705 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1706 # Also, don't emit a subfield if the underlying field is blank.
1709 return Item2Marc($itemrecord,$biblionumber);
1713 my ($itemrecord,$biblionumber)=@_;
1716 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1717 } keys %{ $itemrecord }
1719 my $itemmarc = TransformKohaToMarc($mungeditem);
1720 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1722 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1723 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1724 foreach my $field ($itemmarc->field($itemtag)){
1725 $field->add_subfields(@$unlinked_item_subfields);
1731 =head1 PRIVATE FUNCTIONS AND VARIABLES
1733 The following functions are not meant to be called
1734 directly, but are documented in order to explain
1735 the inner workings of C<C4::Items>.
1739 =head2 %derived_columns
1741 This hash keeps track of item columns that
1742 are strictly derived from other columns in
1743 the item record and are not meant to be set
1746 Each key in the hash should be the name of a
1747 column (as named by TransformMarcToKoha). Each
1748 value should be hashref whose keys are the
1749 columns on which the derived column depends. The
1750 hashref should also contain a 'BUILDER' key
1751 that is a reference to a sub that calculates
1756 my %derived_columns = (
1757 'items.cn_sort' => {
1758 'itemcallnumber' => 1,
1759 'items.cn_source' => 1,
1760 'BUILDER' => \&_calc_items_cn_sort,
1764 =head2 _set_derived_columns_for_add
1766 _set_derived_column_for_add($item);
1768 Given an item hash representing a new item to be added,
1769 calculate any derived columns. Currently the only
1770 such column is C<items.cn_sort>.
1774 sub _set_derived_columns_for_add {
1777 foreach my $column (keys %derived_columns) {
1778 my $builder = $derived_columns{$column}->{'BUILDER'};
1779 my $source_values = {};
1780 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1781 next if $source_column eq 'BUILDER';
1782 $source_values->{$source_column} = $item->{$source_column};
1784 $builder->($item, $source_values);
1788 =head2 _set_derived_columns_for_mod
1790 _set_derived_column_for_mod($item);
1792 Given an item hash representing a new item to be modified.
1793 calculate any derived columns. Currently the only
1794 such column is C<items.cn_sort>.
1796 This routine differs from C<_set_derived_columns_for_add>
1797 in that it needs to handle partial item records. In other
1798 words, the caller of C<ModItem> may have supplied only one
1799 or two columns to be changed, so this function needs to
1800 determine whether any of the columns to be changed affect
1801 any of the derived columns. Also, if a derived column
1802 depends on more than one column, but the caller is not
1803 changing all of then, this routine retrieves the unchanged
1804 values from the database in order to ensure a correct
1809 sub _set_derived_columns_for_mod {
1812 foreach my $column (keys %derived_columns) {
1813 my $builder = $derived_columns{$column}->{'BUILDER'};
1814 my $source_values = {};
1815 my %missing_sources = ();
1816 my $must_recalc = 0;
1817 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1818 next if $source_column eq 'BUILDER';
1819 if (exists $item->{$source_column}) {
1821 $source_values->{$source_column} = $item->{$source_column};
1823 $missing_sources{$source_column} = 1;
1827 foreach my $source_column (keys %missing_sources) {
1828 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1830 $builder->($item, $source_values);
1835 =head2 _do_column_fixes_for_mod
1837 _do_column_fixes_for_mod($item);
1839 Given an item hashref containing one or more
1840 columns to modify, fix up certain values.
1841 Specifically, set to 0 any passed value
1842 of C<notforloan>, C<damaged>, C<itemlost>, or
1843 C<wthdrawn> that is either undefined or
1844 contains the empty string.
1848 sub _do_column_fixes_for_mod {
1851 if (exists $item->{'notforloan'} and
1852 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1853 $item->{'notforloan'} = 0;
1855 if (exists $item->{'damaged'} and
1856 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1857 $item->{'damaged'} = 0;
1859 if (exists $item->{'itemlost'} and
1860 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1861 $item->{'itemlost'} = 0;
1863 if (exists $item->{'wthdrawn'} and
1864 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1865 $item->{'wthdrawn'} = 0;
1867 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1868 $item->{'permanent_location'} = $item->{'location'};
1870 if (exists $item->{'timestamp'}) {
1871 delete $item->{'timestamp'};
1875 =head2 _get_single_item_column
1877 _get_single_item_column($column, $itemnumber);
1879 Retrieves the value of a single column from an C<items>
1880 row specified by C<$itemnumber>.
1884 sub _get_single_item_column {
1886 my $itemnumber = shift;
1888 my $dbh = C4::Context->dbh;
1889 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1890 $sth->execute($itemnumber);
1891 my ($value) = $sth->fetchrow();
1895 =head2 _calc_items_cn_sort
1897 _calc_items_cn_sort($item, $source_values);
1899 Helper routine to calculate C<items.cn_sort>.
1903 sub _calc_items_cn_sort {
1905 my $source_values = shift;
1907 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1910 =head2 _set_defaults_for_add
1912 _set_defaults_for_add($item_hash);
1914 Given an item hash representing an item to be added, set
1915 correct default values for columns whose default value
1916 is not handled by the DBMS. This includes the following
1923 C<items.dateaccessioned>
1945 sub _set_defaults_for_add {
1947 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1948 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1951 =head2 _koha_new_item
1953 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1955 Perform the actual insert into the C<items> table.
1959 sub _koha_new_item {
1960 my ( $item, $barcode ) = @_;
1961 my $dbh=C4::Context->dbh;
1964 "INSERT INTO items SET
1966 biblioitemnumber = ?,
1968 dateaccessioned = ?,
1972 replacementprice = ?,
1973 replacementpricedate = NOW(),
1974 datelastborrowed = ?,
1975 datelastseen = NOW(),
1998 more_subfields_xml = ?,
2002 my $sth = $dbh->prepare($query);
2004 $item->{'biblionumber'},
2005 $item->{'biblioitemnumber'},
2007 $item->{'dateaccessioned'},
2008 $item->{'booksellerid'},
2009 $item->{'homebranch'},
2011 $item->{'replacementprice'},
2012 $item->{datelastborrowed},
2014 $item->{'notforloan'},
2016 $item->{'itemlost'},
2017 $item->{'wthdrawn'},
2018 $item->{'itemcallnumber'},
2019 $item->{'restricted'},
2020 $item->{'itemnotes'},
2021 $item->{'holdingbranch'},
2023 $item->{'location'},
2026 $item->{'renewals'},
2027 $item->{'reserves'},
2028 $item->{'items.cn_source'},
2029 $item->{'items.cn_sort'},
2032 $item->{'materials'},
2034 $item->{'enumchron'},
2035 $item->{'more_subfields_xml'},
2036 $item->{'copynumber'},
2037 $item->{'stocknumber'},
2039 my $itemnumber = $dbh->{'mysql_insertid'};
2040 if ( defined $sth->errstr ) {
2041 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2043 return ( $itemnumber, $error );
2046 =head2 MoveItemFromBiblio
2048 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2050 Moves an item from a biblio to another
2052 Returns undef if the move failed or the biblionumber of the destination record otherwise
2056 sub MoveItemFromBiblio {
2057 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2058 my $dbh = C4::Context->dbh;
2059 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2060 $sth->execute( $tobiblio );
2061 my ( $tobiblioitem ) = $sth->fetchrow();
2062 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2063 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2065 ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2066 ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2067 # Checking if the item we want to move is in an order
2068 my $order = GetOrderFromItemnumber($itemnumber);
2070 # Replacing the biblionumber within the order if necessary
2071 $order->{'biblionumber'} = $tobiblio;
2081 DelItemCheck($dbh, $biblionumber, $itemnumber);
2083 Exported function (core API) for deleting an item record in Koha if there no current issue.
2088 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2091 # check that there is no issue on this item before deletion.
2092 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2093 $sth->execute($itemnumber);
2095 my $item = GetItem($itemnumber);
2096 my $onloan = $sth->fetchrow;
2098 $error = "book_on_loan";
2100 elsif (C4::Context->preference("IndependantBranches") and (C4::Context->userenv->{branch} ne $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'})){
2101 $error = "not_same_branch";
2105 $error = "book_on_loan"
2108 # check it doesnt have a waiting reserve
2109 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2110 $sth->execute($itemnumber);
2111 my $reserve=$sth->fetchrow;
2113 $error = "book_reserved";
2116 DelItem($dbh, $biblionumber, $itemnumber);
2124 =head2 _koha_modify_item
2126 my ($itemnumber,$error) =_koha_modify_item( $item );
2128 Perform the actual update of the C<items> row. Note that this
2129 routine accepts a hashref specifying the columns to update.
2133 sub _koha_modify_item {
2135 my $dbh=C4::Context->dbh;
2138 my $query = "UPDATE items SET ";
2140 for my $key ( keys %$item ) {
2142 push @bind, $item->{$key};
2145 $query .= " WHERE itemnumber=?";
2146 push @bind, $item->{'itemnumber'};
2147 my $sth = C4::Context->dbh->prepare($query);
2148 $sth->execute(@bind);
2149 if ( C4::Context->dbh->errstr ) {
2150 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2153 return ($item->{'itemnumber'},$error);
2156 =head2 _koha_delete_item
2158 _koha_delete_item( $dbh, $itemnum );
2160 Internal function to delete an item record from the koha tables
2164 sub _koha_delete_item {
2165 my ( $dbh, $itemnum ) = @_;
2167 # save the deleted item to deleteditems table
2168 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2169 $sth->execute($itemnum);
2170 my $data = $sth->fetchrow_hashref();
2171 my $query = "INSERT INTO deleteditems SET ";
2173 foreach my $key ( keys %$data ) {
2174 $query .= "$key = ?,";
2175 push( @bind, $data->{$key} );
2178 $sth = $dbh->prepare($query);
2179 $sth->execute(@bind);
2181 # delete from items table
2182 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2183 $sth->execute($itemnum);
2187 =head2 _marc_from_item_hash
2189 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2191 Given an item hash representing a complete item record,
2192 create a C<MARC::Record> object containing an embedded
2193 tag representing that item.
2195 The third, optional parameter C<$unlinked_item_subfields> is
2196 an arrayref of subfields (not mapped to C<items> fields per the
2197 framework) to be added to the MARC representation
2202 sub _marc_from_item_hash {
2204 my $frameworkcode = shift;
2205 my $unlinked_item_subfields;
2207 $unlinked_item_subfields = shift;
2210 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2211 # Also, don't emit a subfield if the underlying field is blank.
2212 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2213 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2214 : () } keys %{ $item } };
2216 my $item_marc = MARC::Record->new();
2217 foreach my $item_field ( keys %{$mungeditem} ) {
2218 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2219 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2220 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2221 foreach my $value (@values){
2222 if ( my $field = $item_marc->field($tag) ) {
2223 $field->add_subfields( $subfield => $value );
2225 my $add_subfields = [];
2226 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2227 $add_subfields = $unlinked_item_subfields;
2229 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2237 =head2 _repack_item_errors
2239 Add an error message hash generated by C<CheckItemPreSave>
2240 to a list of errors.
2244 sub _repack_item_errors {
2245 my $item_sequence_num = shift;
2246 my $item_ref = shift;
2247 my $error_ref = shift;
2249 my @repacked_errors = ();
2251 foreach my $error_code (sort keys %{ $error_ref }) {
2252 my $repacked_error = {};
2253 $repacked_error->{'item_sequence'} = $item_sequence_num;
2254 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2255 $repacked_error->{'error_code'} = $error_code;
2256 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2257 push @repacked_errors, $repacked_error;
2260 return @repacked_errors;
2263 =head2 _get_unlinked_item_subfields
2265 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2269 sub _get_unlinked_item_subfields {
2270 my $original_item_marc = shift;
2271 my $frameworkcode = shift;
2273 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2275 # assume that this record has only one field, and that that
2276 # field contains only the item information
2278 my @fields = $original_item_marc->fields();
2279 if ($#fields > -1) {
2280 my $field = $fields[0];
2281 my $tag = $field->tag();
2282 foreach my $subfield ($field->subfields()) {
2283 if (defined $subfield->[1] and
2284 $subfield->[1] ne '' and
2285 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2286 push @$subfields, $subfield->[0] => $subfield->[1];
2293 =head2 _get_unlinked_subfields_xml
2295 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2299 sub _get_unlinked_subfields_xml {
2300 my $unlinked_item_subfields = shift;
2303 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2304 my $marc = MARC::Record->new();
2305 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2306 # used in the framework
2307 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2308 $marc->encoding("UTF-8");
2309 $xml = $marc->as_xml("USMARC");
2315 =head2 _parse_unlinked_item_subfields_from_xml
2317 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2321 sub _parse_unlinked_item_subfields_from_xml {
2324 return unless defined $xml and $xml ne "";
2325 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2326 my $unlinked_subfields = [];
2327 my @fields = $marc->fields();
2328 if ($#fields > -1) {
2329 foreach my $subfield ($fields[0]->subfields()) {
2330 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2333 return $unlinked_subfields;