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
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #use warnings; FIXME - Bug 2505
27 use C4::Dates qw/format_date format_date_in_iso/;
36 use vars qw($VERSION @ISA @EXPORT);
42 @ISA = qw( Exporter );
65 GetItemsByBiblioitemnumber
68 GetItemnumberFromBarcode
69 GetBarcodeFromItemnumber
80 C4::Items - item management functions
84 This module contains an API for manipulating item
85 records in Koha, and is used by cataloguing, circulation,
86 acquisitions, and serials management.
88 A Koha item record is stored in two places: the
89 items table and embedded in a MARC tag in the XML
90 version of the associated bib record in C<biblioitems.marcxml>.
91 This is done to allow the item information to be readily
92 indexed (e.g., by Zebra), but means that each item
93 modification transaction must keep the items table
94 and the MARC XML in sync at all times.
96 Consequently, all code that creates, modifies, or deletes
97 item records B<must> use an appropriate function from
98 C<C4::Items>. If no existing function is suitable, it is
99 better to add one to C<C4::Items> than to use add
100 one-off SQL statements to add or modify items.
102 The items table will be considered authoritative. In other
103 words, if there is ever a discrepancy between the items
104 table and the MARC XML, the items table should be considered
107 =head1 HISTORICAL NOTE
109 Most of the functions in C<C4::Items> were originally in
110 the C<C4::Biblio> module.
112 =head1 CORE EXPORTED FUNCTIONS
114 The following functions are meant for use by users
123 $item = GetItem($itemnumber,$barcode,$serial);
127 Return item information, for a given itemnumber or barcode.
128 The return value is a hashref mapping item column
129 names to values. If C<$serial> is true, include serial publication data.
134 my ($itemnumber,$barcode, $serial) = @_;
135 my $dbh = C4::Context->dbh;
138 my $sth = $dbh->prepare("
140 WHERE itemnumber = ?");
141 $sth->execute($itemnumber);
142 $data = $sth->fetchrow_hashref;
144 my $sth = $dbh->prepare("
148 $sth->execute($barcode);
149 $data = $sth->fetchrow_hashref;
152 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
153 $ssth->execute($data->{'itemnumber'}) ;
154 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
155 warn $data->{'serialseq'} , $data->{'publisheddate'};
157 #if we don't have an items.itype, use biblioitems.itemtype.
158 if( ! $data->{'itype'} ) {
159 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
160 $sth->execute($data->{'biblionumber'});
161 ($data->{'itype'}) = $sth->fetchrow_array;
170 CartToShelf($itemnumber);
174 Set the current shelving location of the item record
175 to its stored permanent shelving location. This is
176 primarily used to indicate when an item whose current
177 location is a special processing ('PROC') or shelving cart
178 ('CART') location is back in the stacks.
183 my ( $itemnumber ) = @_;
185 unless ( $itemnumber ) {
186 croak "FAILED CartToShelf() - no itemnumber supplied";
189 my $item = GetItem($itemnumber);
190 $item->{location} = $item->{permanent_location};
191 ModItem($item, undef, $itemnumber);
194 =head2 AddItemFromMarc
198 my ($biblionumber, $biblioitemnumber, $itemnumber)
199 = AddItemFromMarc($source_item_marc, $biblionumber);
203 Given a MARC::Record object containing an embedded item
204 record and a biblionumber, create a new item record.
208 sub AddItemFromMarc {
209 my ( $source_item_marc, $biblionumber ) = @_;
210 my $dbh = C4::Context->dbh;
212 # parse item hash from MARC
213 my $frameworkcode = GetFrameworkCode( $biblionumber );
214 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
216 my $localitemmarc=MARC::Record->new;
217 $localitemmarc->append_fields($source_item_marc->field($itemtag));
218 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
219 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
220 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
227 my ($biblionumber, $biblioitemnumber, $itemnumber)
228 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
232 Given a hash containing item column names as keys,
233 create a new Koha item record.
235 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
236 do not need to be supplied for general use; they exist
237 simply to allow them to be picked up from AddItemFromMarc.
239 The final optional parameter, C<$unlinked_item_subfields>, contains
240 an arrayref containing subfields present in the original MARC
241 representation of the item (e.g., from the item editor) that are
242 not mapped to C<items> columns directly but should instead
243 be stored in C<items.more_subfields_xml> and included in
244 the biblio items tag for display and indexing.
250 my $biblionumber = shift;
252 my $dbh = @_ ? shift : C4::Context->dbh;
253 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
254 my $unlinked_item_subfields;
256 $unlinked_item_subfields = shift
259 # needs old biblionumber and biblioitemnumber
260 $item->{'biblionumber'} = $biblionumber;
261 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
262 $sth->execute( $item->{'biblionumber'} );
263 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
265 _set_defaults_for_add($item);
266 _set_derived_columns_for_add($item);
267 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
268 # FIXME - checks here
269 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
270 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
271 $itype_sth->execute( $item->{'biblionumber'} );
272 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
275 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
276 $item->{'itemnumber'} = $itemnumber;
278 # create MARC tag representing item and add to bib
279 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
280 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
282 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
284 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
287 =head2 AddItemBatchFromMarc
291 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
295 Efficiently create item records from a MARC biblio record with
296 embedded item fields. This routine is suitable for batch jobs.
298 This API assumes that the bib record has already been
299 saved to the C<biblio> and C<biblioitems> tables. It does
300 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
301 are populated, but it will do so via a call to ModBibiloMarc.
303 The goal of this API is to have a similar effect to using AddBiblio
304 and AddItems in succession, but without inefficient repeated
305 parsing of the MARC XML bib record.
307 This function returns an arrayref of new itemsnumbers and an arrayref of item
308 errors encountered during the processing. Each entry in the errors
309 list is a hashref containing the following keys:
315 Sequence number of original item tag in the MARC record.
319 Item barcode, provide to assist in the construction of
320 useful error messages.
322 =item error_condition
324 Code representing the error condition. Can be 'duplicate_barcode',
325 'invalid_homebranch', or 'invalid_holdingbranch'.
327 =item error_information
329 Additional information appropriate to the error condition.
335 sub AddItemBatchFromMarc {
336 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
338 my @itemnumbers = ();
340 my $dbh = C4::Context->dbh;
342 # loop through the item tags and start creating items
343 my @bad_item_fields = ();
344 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
345 my $item_sequence_num = 0;
346 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
347 $item_sequence_num++;
348 # we take the item field and stick it into a new
349 # MARC record -- this is required so far because (FIXME)
350 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
351 # and there is no TransformMarcFieldToKoha
352 my $temp_item_marc = MARC::Record->new();
353 $temp_item_marc->append_fields($item_field);
355 # add biblionumber and biblioitemnumber
356 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
357 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
358 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
359 $item->{'biblionumber'} = $biblionumber;
360 $item->{'biblioitemnumber'} = $biblioitemnumber;
362 # check for duplicate barcode
363 my %item_errors = CheckItemPreSave($item);
365 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
366 push @bad_item_fields, $item_field;
370 _set_defaults_for_add($item);
371 _set_derived_columns_for_add($item);
372 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
373 warn $error if $error;
374 push @itemnumbers, $itemnumber; # FIXME not checking error
375 $item->{'itemnumber'} = $itemnumber;
377 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
379 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
380 $item_field->replace_with($new_item_marc->field($itemtag));
383 # remove any MARC item fields for rejected items
384 foreach my $item_field (@bad_item_fields) {
385 $record->delete_field($item_field);
388 # update the MARC biblio
389 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
391 return (\@itemnumbers, \@errors);
394 =head2 ModItemFromMarc
398 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
402 This function updates an item record based on a supplied
403 C<MARC::Record> object containing an embedded item field.
404 This API is meant for the use of C<additem.pl>; for
405 other purposes, C<ModItem> should be used.
407 This function uses the hash %default_values_for_mod_from_marc,
408 which contains default values for item fields to
409 apply when modifying an item. This is needed beccause
410 if an item field's value is cleared, TransformMarcToKoha
411 does not include the column in the
412 hash that's passed to ModItem, which without
413 use of this hash makes it impossible to clear
414 an item field's value. See bug 2466.
416 Note that only columns that can be directly
417 changed from the cataloging and serials
418 item editors are included in this hash.
422 my %default_values_for_mod_from_marc = (
424 booksellerid => undef,
426 'items.cn_source' => undef,
429 dateaccessioned => undef,
431 holdingbranch => undef,
433 itemcallnumber => undef,
442 replacementprice => undef,
443 replacementpricedate => undef,
446 stocknumber => undef,
451 sub ModItemFromMarc {
452 my $item_marc = shift;
453 my $biblionumber = shift;
454 my $itemnumber = shift;
456 my $dbh = C4::Context->dbh;
457 my $frameworkcode = GetFrameworkCode( $biblionumber );
458 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
460 my $localitemmarc=MARC::Record->new;
461 $localitemmarc->append_fields($item_marc->field($itemtag));
462 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items');
463 foreach my $item_field (keys %default_values_for_mod_from_marc) {
464 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
466 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
468 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
475 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
479 Change one or more columns in an item record and update
480 the MARC representation of the item.
482 The first argument is a hashref mapping from item column
483 names to the new values. The second and third arguments
484 are the biblionumber and itemnumber, respectively.
486 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
487 an arrayref containing subfields present in the original MARC
488 representation of the item (e.g., from the item editor) that are
489 not mapped to C<items> columns directly but should instead
490 be stored in C<items.more_subfields_xml> and included in
491 the biblio items tag for display and indexing.
493 If one of the changed columns is used to calculate
494 the derived value of a column such as C<items.cn_sort>,
495 this routine will perform the necessary calculation
502 my $biblionumber = shift;
503 my $itemnumber = shift;
505 # if $biblionumber is undefined, get it from the current item
506 unless (defined $biblionumber) {
507 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
510 my $dbh = @_ ? shift : C4::Context->dbh;
511 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
513 my $unlinked_item_subfields;
515 $unlinked_item_subfields = shift;
516 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
519 $item->{'itemnumber'} = $itemnumber or return undef;
520 _set_derived_columns_for_mod($item);
521 _do_column_fixes_for_mod($item);
524 # attempt to change itemnumber
525 # attempt to change biblionumber (if we want
526 # an API to relink an item to a different bib,
527 # it should be a separate function)
530 _koha_modify_item($item);
532 # update biblio MARC XML
533 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
535 unless (defined $unlinked_item_subfields) {
536 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
538 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
539 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
541 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
542 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
543 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
546 =head2 ModItemTransfer
550 ModItemTransfer($itenumber, $frombranch, $tobranch);
554 Marks an item as being transferred from one branch
559 sub ModItemTransfer {
560 my ( $itemnumber, $frombranch, $tobranch ) = @_;
562 my $dbh = C4::Context->dbh;
564 #new entry in branchtransfers....
565 my $sth = $dbh->prepare(
566 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
567 VALUES (?, ?, NOW(), ?)");
568 $sth->execute($itemnumber, $frombranch, $tobranch);
570 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
571 ModDateLastSeen($itemnumber);
575 =head2 ModDateLastSeen
579 ModDateLastSeen($itemnum);
583 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
584 C<$itemnum> is the item number
588 sub ModDateLastSeen {
589 my ($itemnumber) = @_;
591 my $today = C4::Dates->new();
592 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
599 DelItem($dbh, $biblionumber, $itemnumber);
603 Exported function (core API) for deleting an item record in Koha.
608 my ( $dbh, $biblionumber, $itemnumber ) = @_;
610 # FIXME check the item has no current issues
612 _koha_delete_item( $dbh, $itemnumber );
614 # get the MARC record
615 my $record = GetMarcBiblio($biblionumber);
616 my $frameworkcode = GetFrameworkCode($biblionumber);
619 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
620 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
622 #search item field code
623 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
624 my @fields = $record->field($itemtag);
626 # delete the item specified
627 foreach my $field (@fields) {
628 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
629 $record->delete_field($field);
632 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
633 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
636 =head2 CheckItemPreSave
640 my $item_ref = TransformMarcToKoha($marc, 'items');
642 my %errors = CheckItemPreSave($item_ref);
643 if (exists $errors{'duplicate_barcode'}) {
644 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
645 } elsif (exists $errors{'invalid_homebranch'}) {
646 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
647 } elsif (exists $errors{'invalid_holdingbranch'}) {
648 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
655 Given a hashref containing item fields, determine if it can be
656 inserted or updated in the database. Specifically, checks for
657 database integrity issues, and returns a hash containing any
658 of the following keys, if applicable.
662 =item duplicate_barcode
664 Barcode, if it duplicates one already found in the database.
666 =item invalid_homebranch
668 Home branch, if not defined in branches table.
670 =item invalid_holdingbranch
672 Holding branch, if not defined in branches table.
676 This function does NOT implement any policy-related checks,
677 e.g., whether current operator is allowed to save an
678 item that has a given branch code.
682 sub CheckItemPreSave {
683 my $item_ref = shift;
687 # check for duplicate barcode
688 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
689 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
690 if ($existing_itemnumber) {
691 if (!exists $item_ref->{'itemnumber'} # new item
692 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
693 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
698 # check for valid home branch
699 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
700 my $branch_name = GetBranchName($item_ref->{'homebranch'});
701 unless (defined $branch_name) {
702 # relies on fact that branches.branchname is a non-NULL column,
703 # so GetBranchName returns undef only if branch does not exist
704 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
708 # check for valid holding branch
709 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
710 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
711 unless (defined $branch_name) {
712 # relies on fact that branches.branchname is a non-NULL column,
713 # so GetBranchName returns undef only if branch does not exist
714 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
722 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
724 The following functions provide various ways of
725 getting an item record, a set of item records, or
726 lists of authorized values for certain item fields.
728 Some of the functions in this group are candidates
729 for refactoring -- for example, some of the code
730 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
731 has copy-and-paste work.
739 $itemstatushash = GetItemStatus($fwkcode);
743 Returns a list of valid values for the
744 C<items.notforloan> field.
746 NOTE: does B<not> return an individual item's
749 Can be MARC dependant.
751 But basically could be can be loan or not
752 Create a status selector with the following code
754 =head3 in PERL SCRIPT
758 my $itemstatushash = getitemstatus;
760 foreach my $thisstatus (keys %$itemstatushash) {
761 my %row =(value => $thisstatus,
762 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
764 push @itemstatusloop, \%row;
766 $template->param(statusloop=>\@itemstatusloop);
774 <select name="statusloop">
775 <option value="">Default</option>
776 <!-- TMPL_LOOP name="statusloop" -->
777 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
787 # returns a reference to a hash of references to status...
790 my $dbh = C4::Context->dbh;
792 $fwk = '' unless ($fwk);
793 my ( $tag, $subfield ) =
794 GetMarcFromKohaField( "items.notforloan", $fwk );
795 if ( $tag and $subfield ) {
798 "SELECT authorised_value
799 FROM marc_subfield_structure
805 $sth->execute( $tag, $subfield, $fwk );
806 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
809 "SELECT authorised_value,lib
810 FROM authorised_values
815 $authvalsth->execute($authorisedvaluecat);
816 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
817 $itemstatus{$authorisedvalue} = $lib;
831 $itemstatus{"1"} = "Not For Loan";
835 =head2 GetItemLocation
839 $itemlochash = GetItemLocation($fwk);
843 Returns a list of valid values for the
844 C<items.location> field.
846 NOTE: does B<not> return an individual item's
849 where fwk stands for an optional framework code.
850 Create a location selector with the following code
852 =head3 in PERL SCRIPT
856 my $itemlochash = getitemlocation;
858 foreach my $thisloc (keys %$itemlochash) {
859 my $selected = 1 if $thisbranch eq $branch;
860 my %row =(locval => $thisloc,
861 selected => $selected,
862 locname => $itemlochash->{$thisloc},
864 push @itemlocloop, \%row;
866 $template->param(itemlocationloop => \@itemlocloop);
874 <select name="location">
875 <option value="">Default</option>
876 <!-- TMPL_LOOP name="itemlocationloop" -->
877 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
885 sub GetItemLocation {
887 # returns a reference to a hash of references to location...
890 my $dbh = C4::Context->dbh;
892 $fwk = '' unless ($fwk);
893 my ( $tag, $subfield ) =
894 GetMarcFromKohaField( "items.location", $fwk );
895 if ( $tag and $subfield ) {
898 "SELECT authorised_value
899 FROM marc_subfield_structure
904 $sth->execute( $tag, $subfield, $fwk );
905 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
908 "SELECT authorised_value,lib
909 FROM authorised_values
913 $authvalsth->execute($authorisedvaluecat);
914 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
915 $itemlocation{$authorisedvalue} = $lib;
917 return \%itemlocation;
929 $itemlocation{"1"} = "Not For Loan";
930 return \%itemlocation;
937 $items = GetLostItems( $where, $orderby );
941 This function gets a list of lost items.
947 C<$where> is a hashref. it containts a field of the items table as key
948 and the value to match as value. For example:
950 { barcode => 'abc123',
951 homebranch => 'CPL', }
953 C<$orderby> is a field of the items table by which the resultset
958 C<$items> is a reference to an array full of hashrefs with columns
959 from the "items" table as keys.
961 =item usage in the perl script:
963 my $where = { barcode => '0001548' };
964 my $items = GetLostItems( $where, "homebranch" );
965 $template->param( itemsloop => $items );
972 # Getting input args.
975 my $dbh = C4::Context->dbh;
980 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
981 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
982 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
984 authorised_values.category = 'LOST'
985 AND itemlost IS NOT NULL
988 my @query_parameters;
989 foreach my $key (keys %$where) {
990 $query .= " AND $key LIKE ?";
991 push @query_parameters, "%$where->{$key}%";
993 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
995 if ( defined $orderby && grep($orderby, @ordervalues)) {
996 $query .= ' ORDER BY '.$orderby;
999 my $sth = $dbh->prepare($query);
1000 $sth->execute( @query_parameters );
1002 while ( my $row = $sth->fetchrow_hashref ){
1008 =head2 GetItemsForInventory
1012 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size, $statushash);
1016 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1018 The sub returns a reference to a list of hashes, each containing
1019 itemnumber, author, title, barcode, item callnumber, and date last
1020 seen. It is ordered by callnumber then title.
1022 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1023 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1024 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1025 $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.
1029 sub GetItemsForInventory {
1030 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branch, $offset, $size, $statushash ) = @_;
1031 my $dbh = C4::Context->dbh;
1032 my ( @bind_params, @where_strings );
1034 my $query = <<'END_SQL';
1035 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
1037 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1038 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1041 for my $authvfield (keys %$statushash){
1042 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1043 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1044 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1050 push @where_strings, 'itemcallnumber >= ?';
1051 push @bind_params, $minlocation;
1055 push @where_strings, 'itemcallnumber <= ?';
1056 push @bind_params, $maxlocation;
1059 if ($datelastseen) {
1060 $datelastseen = format_date_in_iso($datelastseen);
1061 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1062 push @bind_params, $datelastseen;
1066 push @where_strings, 'items.location = ?';
1067 push @bind_params, $location;
1071 push @where_strings, 'items.homebranch = ?';
1072 push @bind_params, $branch;
1076 push @where_strings, 'biblioitems.itemtype = ?';
1077 push @bind_params, $itemtype;
1080 if ( $ignoreissued) {
1081 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1082 push @where_strings, 'issues.date_due IS NULL';
1085 if ( @where_strings ) {
1087 $query .= join ' AND ', @where_strings;
1089 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1090 my $sth = $dbh->prepare($query);
1091 $sth->execute( @bind_params );
1095 while ( my $row = $sth->fetchrow_hashref ) {
1096 $offset-- if ($offset);
1097 $row->{datelastseen}=format_date($row->{datelastseen});
1098 if ( ( !$offset ) && $size ) {
1099 push @results, $row;
1106 =head2 GetItemsCount
1109 $count = &GetItemsCount( $biblionumber);
1113 This function return count of item with $biblionumber
1118 my ( $biblionumber ) = @_;
1119 my $dbh = C4::Context->dbh;
1120 my $query = "SELECT count(*)
1122 WHERE biblionumber=?";
1123 my $sth = $dbh->prepare($query);
1124 $sth->execute($biblionumber);
1125 my $count = $sth->fetchrow;
1129 =head2 GetItemInfosOf
1133 GetItemInfosOf(@itemnumbers);
1139 sub GetItemInfosOf {
1140 my @itemnumbers = @_;
1145 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1147 return get_infos_of( $query, 'itemnumber' );
1150 =head2 GetItemsByBiblioitemnumber
1154 GetItemsByBiblioitemnumber($biblioitemnumber);
1158 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1159 Called by C<C4::XISBN>
1163 sub GetItemsByBiblioitemnumber {
1164 my ( $bibitem ) = @_;
1165 my $dbh = C4::Context->dbh;
1166 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1167 # Get all items attached to a biblioitem
1170 $sth->execute($bibitem) || die $sth->errstr;
1171 while ( my $data = $sth->fetchrow_hashref ) {
1172 # Foreach item, get circulation information
1173 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1174 WHERE itemnumber = ?
1175 AND issues.borrowernumber = borrowers.borrowernumber"
1177 $sth2->execute( $data->{'itemnumber'} );
1178 if ( my $data2 = $sth2->fetchrow_hashref ) {
1179 # if item is out, set the due date and who it is out too
1180 $data->{'date_due'} = $data2->{'date_due'};
1181 $data->{'cardnumber'} = $data2->{'cardnumber'};
1182 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1185 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1186 $data->{'date_due'} = '';
1188 # Find the last 3 people who borrowed this item.
1189 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1190 AND old_issues.borrowernumber = borrowers.borrowernumber
1191 ORDER BY returndate desc,timestamp desc LIMIT 3";
1192 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1193 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1195 while ( my $data2 = $sth2->fetchrow_hashref ) {
1196 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1197 $data->{"card$i2"} = $data2->{'cardnumber'};
1198 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1201 push(@results,$data);
1210 @results = GetItemsInfo($biblionumber, $type);
1214 Returns information about books with the given biblionumber.
1216 C<$type> may be either C<intra> or anything else. If it is not set to
1217 C<intra>, then the search will exclude lost, very overdue, and
1220 C<GetItemsInfo> returns a list of references-to-hash. Each element
1221 contains a number of keys. Most of them are table items from the
1222 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1223 Koha database. Other keys include:
1227 =item C<$data-E<gt>{branchname}>
1229 The name (not the code) of the branch to which the book belongs.
1231 =item C<$data-E<gt>{datelastseen}>
1233 This is simply C<items.datelastseen>, except that while the date is
1234 stored in YYYY-MM-DD format in the database, here it is converted to
1235 DD/MM/YYYY format. A NULL date is returned as C<//>.
1237 =item C<$data-E<gt>{datedue}>
1239 =item C<$data-E<gt>{class}>
1241 This is the concatenation of C<biblioitems.classification>, the book's
1242 Dewey code, and C<biblioitems.subclass>.
1244 =item C<$data-E<gt>{ocount}>
1246 I think this is the number of copies of the book available.
1248 =item C<$data-E<gt>{order}>
1250 If this is set, it is set to C<One Order>.
1257 my ( $biblionumber, $type ) = @_;
1258 my $dbh = C4::Context->dbh;
1259 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1265 biblioitems.itemtype,
1268 biblioitems.publicationyear,
1269 biblioitems.publishercode,
1270 biblioitems.volumedate,
1271 biblioitems.volumedesc,
1274 items.notforloan as itemnotforloan,
1275 itemtypes.description,
1276 itemtypes.notforloan as notforloan_per_itemtype,
1279 LEFT JOIN branches ON items.homebranch = branches.branchcode
1280 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1281 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1282 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1283 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1284 $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1285 my $sth = $dbh->prepare($query);
1286 $sth->execute($biblionumber);
1291 my $isth = $dbh->prepare(
1292 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1293 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1294 WHERE itemnumber = ?"
1296 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1297 while ( my $data = $sth->fetchrow_hashref ) {
1300 $isth->execute( $data->{'itemnumber'} );
1301 if ( my $idata = $isth->fetchrow_hashref ) {
1302 $data->{borrowernumber} = $idata->{borrowernumber};
1303 $data->{cardnumber} = $idata->{cardnumber};
1304 $data->{surname} = $idata->{surname};
1305 $data->{firstname} = $idata->{firstname};
1306 $datedue = $idata->{'date_due'};
1307 if (C4::Context->preference("IndependantBranches")){
1308 my $userenv = C4::Context->userenv;
1309 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1310 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1314 if ( $data->{'serial'}) {
1315 $ssth->execute($data->{'itemnumber'}) ;
1316 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1319 if ( $datedue eq '' ) {
1320 my ( $restype, $reserves ) =
1321 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1322 # Previous conditional check with if ($restype) is not needed because a true
1323 # result for one item will result in subsequent items defaulting to this true
1325 $count_reserves = $restype;
1327 #get branch information.....
1328 my $bsth = $dbh->prepare(
1329 "SELECT * FROM branches WHERE branchcode = ?
1332 $bsth->execute( $data->{'holdingbranch'} );
1333 if ( my $bdata = $bsth->fetchrow_hashref ) {
1334 $data->{'branchname'} = $bdata->{'branchname'};
1336 $data->{'datedue'} = $datedue;
1337 $data->{'count_reserves'} = $count_reserves;
1339 # get notforloan complete status if applicable
1340 my $sthnflstatus = $dbh->prepare(
1341 'SELECT authorised_value
1342 FROM marc_subfield_structure
1343 WHERE kohafield="items.notforloan"
1347 $sthnflstatus->execute;
1348 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1349 if ($authorised_valuecode) {
1350 $sthnflstatus = $dbh->prepare(
1351 "SELECT lib FROM authorised_values
1353 AND authorised_value=?"
1355 $sthnflstatus->execute( $authorised_valuecode,
1356 $data->{itemnotforloan} );
1357 my ($lib) = $sthnflstatus->fetchrow;
1358 $data->{notforloanvalue} = $lib;
1361 # my stack procedures
1362 my $stackstatus = $dbh->prepare(
1363 'SELECT authorised_value
1364 FROM marc_subfield_structure
1365 WHERE kohafield="items.stack"
1368 $stackstatus->execute;
1370 ($authorised_valuecode) = $stackstatus->fetchrow;
1371 if ($authorised_valuecode) {
1372 $stackstatus = $dbh->prepare(
1374 FROM authorised_values
1376 AND authorised_value=?
1379 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1380 my ($lib) = $stackstatus->fetchrow;
1381 $data->{stack} = $lib;
1383 # Find the last 3 people who borrowed this item.
1384 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1385 WHERE itemnumber = ?
1386 AND old_issues.borrowernumber = borrowers.borrowernumber
1387 ORDER BY returndate DESC
1389 $sth2->execute($data->{'itemnumber'});
1391 while (my $data2 = $sth2->fetchrow_hashref()) {
1392 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1393 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1394 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1398 $results[$i] = $data;
1402 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1408 =head2 GetLastAcquisitions
1412 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 'itemtypes' => ('BK','BD')}, 10);
1418 sub GetLastAcquisitions {
1419 my ($data,$max) = @_;
1421 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1423 my $number_of_branches = @{$data->{branches}};
1424 my $number_of_itemtypes = @{$data->{itemtypes}};
1427 my @where = ('WHERE 1 ');
1428 $number_of_branches and push @where
1429 , 'AND holdingbranch IN ('
1430 , join(',', ('?') x $number_of_branches )
1434 $number_of_itemtypes and push @where
1435 , "AND $itemtype IN ("
1436 , join(',', ('?') x $number_of_itemtypes )
1440 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1441 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1442 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1444 GROUP BY biblio.biblionumber
1445 ORDER BY dateaccessioned DESC LIMIT $max";
1447 my $dbh = C4::Context->dbh;
1448 my $sth = $dbh->prepare($query);
1450 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1453 while( my $row = $sth->fetchrow_hashref){
1454 push @results, {date => $row->{dateaccessioned}
1455 , biblionumber => $row->{biblionumber}
1456 , title => $row->{title}};
1462 =head2 get_itemnumbers_of
1466 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1470 Given a list of biblionumbers, return the list of corresponding itemnumbers
1471 for each biblionumber.
1473 Return a reference on a hash where keys are biblionumbers and values are
1474 references on array of itemnumbers.
1478 sub get_itemnumbers_of {
1479 my @biblionumbers = @_;
1481 my $dbh = C4::Context->dbh;
1487 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1489 my $sth = $dbh->prepare($query);
1490 $sth->execute(@biblionumbers);
1494 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1495 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1498 return \%itemnumbers_of;
1501 =head2 GetItemnumberFromBarcode
1505 $result = GetItemnumberFromBarcode($barcode);
1511 sub GetItemnumberFromBarcode {
1513 my $dbh = C4::Context->dbh;
1516 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1517 $rq->execute($barcode);
1518 my ($result) = $rq->fetchrow;
1522 =head2 GetBarcodeFromItemnumber
1526 $result = GetBarcodeFromItemnumber($itemnumber);
1532 sub GetBarcodeFromItemnumber {
1533 my ($itemnumber) = @_;
1534 my $dbh = C4::Context->dbh;
1537 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1538 $rq->execute($itemnumber);
1539 my ($result) = $rq->fetchrow;
1543 =head3 get_item_authorised_values
1545 find the types and values for all authorised values assigned to this item.
1550 returns: a hashref malling the authorised value to the value set for this itemnumber
1552 $authorised_values = {
1558 'RESTRICTED' => undef,
1561 'branches' => 'CPL',
1562 'cn_source' => undef,
1563 'itemtypes' => 'SER',
1566 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1570 sub get_item_authorised_values {
1571 my $itemnumber = shift;
1573 # assume that these entries in the authorised_value table are item level.
1574 my $query = q(SELECT distinct authorised_value, kohafield
1575 FROM marc_subfield_structure
1576 WHERE kohafield like 'item%'
1577 AND authorised_value != '' );
1579 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1580 my $iteminfo = GetItem( $itemnumber );
1581 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1583 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1584 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1585 $field =~ s/^items\.//;
1586 if ( exists $iteminfo->{ $field } ) {
1587 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1590 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1594 =head3 get_authorised_value_images
1596 find a list of icons that are appropriate for display based on the
1597 authorised values for a biblio.
1599 parameters: listref of authorised values, such as comes from
1600 get_item_authorised_values or
1601 from C4::Biblio::get_biblio_authorised_values
1603 returns: listref of hashrefs for each image. Each hashref looks like
1606 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1611 Notes: Currently, I put on the full path to the images on the staff
1612 side. This should either be configurable or not done at all. Since I
1613 have to deal with 'intranet' or 'opac' in
1614 get_biblio_authorised_values, perhaps I should be passing it in.
1618 sub get_authorised_value_images {
1619 my $authorised_values = shift;
1623 my $authorised_value_list = GetAuthorisedValues();
1624 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1625 foreach my $this_authorised_value ( @$authorised_value_list ) {
1626 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1627 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1628 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1629 if ( defined $this_authorised_value->{'imageurl'} ) {
1630 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1631 label => $this_authorised_value->{'lib'},
1632 category => $this_authorised_value->{'category'},
1633 value => $this_authorised_value->{'authorised_value'}, };
1638 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1643 =head1 LIMITED USE FUNCTIONS
1645 The following functions, while part of the public API,
1646 are not exported. This is generally because they are
1647 meant to be used by only one script for a specific
1648 purpose, and should not be used in any other context
1649 without careful thought.
1657 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1661 Returns MARC::Record of the item passed in parameter.
1662 This function is meant for use only in C<cataloguing/additem.pl>,
1663 where it is needed to support that script's MARC-like
1669 my ( $biblionumber, $itemnumber ) = @_;
1671 # GetMarcItem has been revised so that it does the following:
1672 # 1. Gets the item information from the items table.
1673 # 2. Converts it to a MARC field for storage in the bib record.
1675 # The previous behavior was:
1676 # 1. Get the bib record.
1677 # 2. Return the MARC tag corresponding to the item record.
1679 # The difference is that one treats the items row as authoritative,
1680 # while the other treats the MARC representation as authoritative
1681 # under certain circumstances.
1683 my $itemrecord = GetItem($itemnumber);
1685 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1686 # Also, don't emit a subfield if the underlying field is blank.
1689 return Item2Marc($itemrecord,$biblionumber);
1693 my ($itemrecord,$biblionumber)=@_;
1696 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1697 } keys %{ $itemrecord }
1699 my $itemmarc = TransformKohaToMarc($mungeditem);
1700 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1702 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1703 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1704 foreach my $field ($itemmarc->field($itemtag)){
1705 $field->add_subfields(@$unlinked_item_subfields);
1711 =head1 PRIVATE FUNCTIONS AND VARIABLES
1713 The following functions are not meant to be called
1714 directly, but are documented in order to explain
1715 the inner workings of C<C4::Items>.
1719 =head2 %derived_columns
1721 This hash keeps track of item columns that
1722 are strictly derived from other columns in
1723 the item record and are not meant to be set
1726 Each key in the hash should be the name of a
1727 column (as named by TransformMarcToKoha). Each
1728 value should be hashref whose keys are the
1729 columns on which the derived column depends. The
1730 hashref should also contain a 'BUILDER' key
1731 that is a reference to a sub that calculates
1736 my %derived_columns = (
1737 'items.cn_sort' => {
1738 'itemcallnumber' => 1,
1739 'items.cn_source' => 1,
1740 'BUILDER' => \&_calc_items_cn_sort,
1744 =head2 _set_derived_columns_for_add
1748 _set_derived_column_for_add($item);
1752 Given an item hash representing a new item to be added,
1753 calculate any derived columns. Currently the only
1754 such column is C<items.cn_sort>.
1758 sub _set_derived_columns_for_add {
1761 foreach my $column (keys %derived_columns) {
1762 my $builder = $derived_columns{$column}->{'BUILDER'};
1763 my $source_values = {};
1764 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1765 next if $source_column eq 'BUILDER';
1766 $source_values->{$source_column} = $item->{$source_column};
1768 $builder->($item, $source_values);
1772 =head2 _set_derived_columns_for_mod
1776 _set_derived_column_for_mod($item);
1780 Given an item hash representing a new item to be modified.
1781 calculate any derived columns. Currently the only
1782 such column is C<items.cn_sort>.
1784 This routine differs from C<_set_derived_columns_for_add>
1785 in that it needs to handle partial item records. In other
1786 words, the caller of C<ModItem> may have supplied only one
1787 or two columns to be changed, so this function needs to
1788 determine whether any of the columns to be changed affect
1789 any of the derived columns. Also, if a derived column
1790 depends on more than one column, but the caller is not
1791 changing all of then, this routine retrieves the unchanged
1792 values from the database in order to ensure a correct
1797 sub _set_derived_columns_for_mod {
1800 foreach my $column (keys %derived_columns) {
1801 my $builder = $derived_columns{$column}->{'BUILDER'};
1802 my $source_values = {};
1803 my %missing_sources = ();
1804 my $must_recalc = 0;
1805 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1806 next if $source_column eq 'BUILDER';
1807 if (exists $item->{$source_column}) {
1809 $source_values->{$source_column} = $item->{$source_column};
1811 $missing_sources{$source_column} = 1;
1815 foreach my $source_column (keys %missing_sources) {
1816 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1818 $builder->($item, $source_values);
1823 =head2 _do_column_fixes_for_mod
1827 _do_column_fixes_for_mod($item);
1831 Given an item hashref containing one or more
1832 columns to modify, fix up certain values.
1833 Specifically, set to 0 any passed value
1834 of C<notforloan>, C<damaged>, C<itemlost>, or
1835 C<wthdrawn> that is either undefined or
1836 contains the empty string.
1840 sub _do_column_fixes_for_mod {
1843 if (exists $item->{'notforloan'} and
1844 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1845 $item->{'notforloan'} = 0;
1847 if (exists $item->{'damaged'} and
1848 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1849 $item->{'damaged'} = 0;
1851 if (exists $item->{'itemlost'} and
1852 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1853 $item->{'itemlost'} = 0;
1855 if (exists $item->{'wthdrawn'} and
1856 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1857 $item->{'wthdrawn'} = 0;
1859 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1860 $item->{'permanent_location'} = $item->{'location'};
1864 =head2 _get_single_item_column
1868 _get_single_item_column($column, $itemnumber);
1872 Retrieves the value of a single column from an C<items>
1873 row specified by C<$itemnumber>.
1877 sub _get_single_item_column {
1879 my $itemnumber = shift;
1881 my $dbh = C4::Context->dbh;
1882 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1883 $sth->execute($itemnumber);
1884 my ($value) = $sth->fetchrow();
1888 =head2 _calc_items_cn_sort
1892 _calc_items_cn_sort($item, $source_values);
1896 Helper routine to calculate C<items.cn_sort>.
1900 sub _calc_items_cn_sort {
1902 my $source_values = shift;
1904 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1907 =head2 _set_defaults_for_add
1911 _set_defaults_for_add($item_hash);
1915 Given an item hash representing an item to be added, set
1916 correct default values for columns whose default value
1917 is not handled by the DBMS. This includes the following
1924 C<items.dateaccessioned>
1946 sub _set_defaults_for_add {
1948 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1949 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1952 =head2 _koha_new_item
1956 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1960 Perform the actual insert into the C<items> table.
1964 sub _koha_new_item {
1965 my ( $item, $barcode ) = @_;
1966 my $dbh=C4::Context->dbh;
1969 "INSERT INTO items SET
1971 biblioitemnumber = ?,
1973 dateaccessioned = ?,
1977 replacementprice = ?,
1978 replacementpricedate = NOW(),
1979 datelastborrowed = ?,
1980 datelastseen = NOW(),
2003 more_subfields_xml = ?,
2006 my $sth = $dbh->prepare($query);
2008 $item->{'biblionumber'},
2009 $item->{'biblioitemnumber'},
2011 $item->{'dateaccessioned'},
2012 $item->{'booksellerid'},
2013 $item->{'homebranch'},
2015 $item->{'replacementprice'},
2016 $item->{datelastborrowed},
2018 $item->{'notforloan'},
2020 $item->{'itemlost'},
2021 $item->{'wthdrawn'},
2022 $item->{'itemcallnumber'},
2023 $item->{'restricted'},
2024 $item->{'itemnotes'},
2025 $item->{'holdingbranch'},
2027 $item->{'location'},
2030 $item->{'renewals'},
2031 $item->{'reserves'},
2032 $item->{'items.cn_source'},
2033 $item->{'items.cn_sort'},
2036 $item->{'materials'},
2038 $item->{'enumchron'},
2039 $item->{'more_subfields_xml'},
2040 $item->{'copynumber'},
2042 my $itemnumber = $dbh->{'mysql_insertid'};
2043 if ( defined $sth->errstr ) {
2044 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2046 return ( $itemnumber, $error );
2049 =head2 MoveItemFromBiblio
2053 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2057 Moves an item from a biblio to another
2059 Returns undef if the move failed or the biblionumber of the destination record otherwise
2061 sub MoveItemFromBiblio {
2062 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2063 my $dbh = C4::Context->dbh;
2064 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2065 $sth->execute( $tobiblio );
2066 my ( $tobiblioitem ) = $sth->fetchrow();
2067 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2068 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2072 my $frameworkcode = GetFrameworkCode($frombiblio);
2074 # Getting marc field for itemnumber
2075 my ($itemtag, $itemsubfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
2077 # Getting the record we want to move the item from
2078 my $record = GetMarcBiblio($frombiblio);
2080 # The item we want to move
2084 foreach my $fielditem ($record->field($itemtag)){
2085 # If it is the item we want to move
2086 if ($fielditem->subfield($itemsubfield) == $itemnumber) {
2089 # Then delete it from the record
2090 $record->delete_field($fielditem)
2094 # If we found an item (should always true, except in case of database-marcxml inconsistency)
2097 # Checking if the item we want to move is in an order
2098 my $order = GetOrderFromItemnumber($itemnumber);
2100 # Replacing the biblionumber within the order if necessary
2101 $order->{'biblionumber'} = $tobiblio;
2105 # Saving the modification
2106 ModBiblioMarc($record, $frombiblio, $frameworkcode);
2108 # Getting the record we want to move the item to
2109 $record = GetMarcBiblio($tobiblio);
2111 # Inserting the previously saved item
2112 $record->insert_fields_ordered($item);
2114 # Saving the modification
2115 ModBiblioMarc($record, $tobiblio, $frameworkcode);
2129 DelItemCheck($dbh, $biblionumber, $itemnumber);
2133 Exported function (core API) for deleting an item record in Koha if there no current issue.
2138 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2141 # check that there is no issue on this item before deletion.
2142 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2143 $sth->execute($itemnumber);
2145 my $onloan=$sth->fetchrow;
2148 $error = "book_on_loan"
2150 # check it doesnt have a waiting reserve
2151 $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
2152 $sth->execute($itemnumber);
2153 my $reserve=$sth->fetchrow;
2155 $error = "book_reserved";
2157 DelItem($dbh, $biblionumber, $itemnumber);
2164 =head2 _koha_modify_item
2168 my ($itemnumber,$error) =_koha_modify_item( $item );
2172 Perform the actual update of the C<items> row. Note that this
2173 routine accepts a hashref specifying the columns to update.
2177 sub _koha_modify_item {
2179 my $dbh=C4::Context->dbh;
2182 my $query = "UPDATE items SET ";
2184 for my $key ( keys %$item ) {
2186 push @bind, $item->{$key};
2189 $query .= " WHERE itemnumber=?";
2190 push @bind, $item->{'itemnumber'};
2191 my $sth = C4::Context->dbh->prepare($query);
2192 $sth->execute(@bind);
2193 if ( C4::Context->dbh->errstr ) {
2194 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2197 return ($item->{'itemnumber'},$error);
2200 =head2 _koha_delete_item
2204 _koha_delete_item( $dbh, $itemnum );
2208 Internal function to delete an item record from the koha tables
2212 sub _koha_delete_item {
2213 my ( $dbh, $itemnum ) = @_;
2215 # save the deleted item to deleteditems table
2216 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2217 $sth->execute($itemnum);
2218 my $data = $sth->fetchrow_hashref();
2219 my $query = "INSERT INTO deleteditems SET ";
2221 foreach my $key ( keys %$data ) {
2222 $query .= "$key = ?,";
2223 push( @bind, $data->{$key} );
2226 $sth = $dbh->prepare($query);
2227 $sth->execute(@bind);
2229 # delete from items table
2230 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2231 $sth->execute($itemnum);
2235 =head2 _marc_from_item_hash
2239 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2243 Given an item hash representing a complete item record,
2244 create a C<MARC::Record> object containing an embedded
2245 tag representing that item.
2247 The third, optional parameter C<$unlinked_item_subfields> is
2248 an arrayref of subfields (not mapped to C<items> fields per the
2249 framework) to be added to the MARC representation
2254 sub _marc_from_item_hash {
2256 my $frameworkcode = shift;
2257 my $unlinked_item_subfields;
2259 $unlinked_item_subfields = shift;
2262 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2263 # Also, don't emit a subfield if the underlying field is blank.
2264 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2265 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2266 : () } keys %{ $item } };
2268 my $item_marc = MARC::Record->new();
2269 foreach my $item_field (keys %{ $mungeditem }) {
2270 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
2271 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2272 if (my $field = $item_marc->field($tag)) {
2273 $field->add_subfields($subfield => $mungeditem->{$item_field});
2275 my $add_subfields = [];
2276 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2277 $add_subfields = $unlinked_item_subfields;
2279 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
2286 =head2 _add_item_field_to_biblio
2290 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2294 Adds the fields from a MARC record containing the
2295 representation of a Koha item record to the MARC
2296 biblio record. The input C<$item_marc> record
2297 is expect to contain just one field, the embedded
2298 item information field.
2302 sub _add_item_field_to_biblio {
2303 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2305 my $biblio_marc = GetMarcBiblio($biblionumber);
2306 foreach my $field ($item_marc->fields()) {
2307 $biblio_marc->append_fields($field);
2310 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2313 =head2 _replace_item_field_in_biblio
2317 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2321 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2322 representation of the item, examine the biblio MARC
2323 for the corresponding tag for that item and
2324 replace it with the tag from C<$item_marc>.
2328 sub _replace_item_field_in_biblio {
2329 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2330 my $dbh = C4::Context->dbh;
2332 # get complete MARC record & replace the item field by the new one
2333 my $completeRecord = GetMarcBiblio($biblionumber);
2334 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2335 my $itemField = $ItemRecord->field($itemtag);
2336 my @items = $completeRecord->field($itemtag);
2339 if ($_->subfield($itemsubfield) eq $itemnumber) {
2340 $_->replace_with($itemField);
2346 # If we haven't found the matching field,
2347 # just add it. However, this means that
2348 # there is likely a bug.
2349 $completeRecord->append_fields($itemField);
2353 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2356 =head2 _repack_item_errors
2358 Add an error message hash generated by C<CheckItemPreSave>
2359 to a list of errors.
2363 sub _repack_item_errors {
2364 my $item_sequence_num = shift;
2365 my $item_ref = shift;
2366 my $error_ref = shift;
2368 my @repacked_errors = ();
2370 foreach my $error_code (sort keys %{ $error_ref }) {
2371 my $repacked_error = {};
2372 $repacked_error->{'item_sequence'} = $item_sequence_num;
2373 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2374 $repacked_error->{'error_code'} = $error_code;
2375 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2376 push @repacked_errors, $repacked_error;
2379 return @repacked_errors;
2382 =head2 _get_unlinked_item_subfields
2386 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2392 sub _get_unlinked_item_subfields {
2393 my $original_item_marc = shift;
2394 my $frameworkcode = shift;
2396 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2398 # assume that this record has only one field, and that that
2399 # field contains only the item information
2401 my @fields = $original_item_marc->fields();
2402 if ($#fields > -1) {
2403 my $field = $fields[0];
2404 my $tag = $field->tag();
2405 foreach my $subfield ($field->subfields()) {
2406 if (defined $subfield->[1] and
2407 $subfield->[1] ne '' and
2408 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2409 push @$subfields, $subfield->[0] => $subfield->[1];
2416 =head2 _get_unlinked_subfields_xml
2420 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2426 sub _get_unlinked_subfields_xml {
2427 my $unlinked_item_subfields = shift;
2430 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2431 my $marc = MARC::Record->new();
2432 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2433 # used in the framework
2434 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2435 $marc->encoding("UTF-8");
2436 $xml = $marc->as_xml("USMARC");
2442 =head2 _parse_unlinked_item_subfields_from_xml
2446 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2452 sub _parse_unlinked_item_subfields_from_xml {
2455 return unless defined $xml and $xml ne "";
2456 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2457 my $unlinked_subfields = [];
2458 my @fields = $marc->fields();
2459 if ($#fields > -1) {
2460 foreach my $subfield ($fields[0]->subfields()) {
2461 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2464 return $unlinked_subfields;