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/;
37 use vars qw($VERSION @ISA @EXPORT);
43 @ISA = qw( Exporter );
66 GetItemsByBiblioitemnumber
70 GetItemnumberFromBarcode
71 GetBarcodeFromItemnumber
82 C4::Items - item management functions
86 This module contains an API for manipulating item
87 records in Koha, and is used by cataloguing, circulation,
88 acquisitions, and serials management.
90 A Koha item record is stored in two places: the
91 items table and embedded in a MARC tag in the XML
92 version of the associated bib record in C<biblioitems.marcxml>.
93 This is done to allow the item information to be readily
94 indexed (e.g., by Zebra), but means that each item
95 modification transaction must keep the items table
96 and the MARC XML in sync at all times.
98 Consequently, all code that creates, modifies, or deletes
99 item records B<must> use an appropriate function from
100 C<C4::Items>. If no existing function is suitable, it is
101 better to add one to C<C4::Items> than to use add
102 one-off SQL statements to add or modify items.
104 The items table will be considered authoritative. In other
105 words, if there is ever a discrepancy between the items
106 table and the MARC XML, the items table should be considered
109 =head1 HISTORICAL NOTE
111 Most of the functions in C<C4::Items> were originally in
112 the C<C4::Biblio> module.
114 =head1 CORE EXPORTED FUNCTIONS
116 The following functions are meant for use by users
123 $item = GetItem($itemnumber,$barcode,$serial);
125 Return item information, for a given itemnumber or barcode.
126 The return value is a hashref mapping item column
127 names to values. If C<$serial> is true, include serial publication data.
132 my ($itemnumber,$barcode, $serial) = @_;
133 my $dbh = C4::Context->dbh;
136 my $sth = $dbh->prepare("
138 WHERE itemnumber = ?");
139 $sth->execute($itemnumber);
140 $data = $sth->fetchrow_hashref;
142 my $sth = $dbh->prepare("
146 $sth->execute($barcode);
147 $data = $sth->fetchrow_hashref;
150 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
151 $ssth->execute($data->{'itemnumber'}) ;
152 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
154 #if we don't have an items.itype, use biblioitems.itemtype.
155 if( ! $data->{'itype'} ) {
156 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
157 $sth->execute($data->{'biblionumber'});
158 ($data->{'itype'}) = $sth->fetchrow_array;
165 CartToShelf($itemnumber);
167 Set the current shelving location of the item record
168 to its stored permanent shelving location. This is
169 primarily used to indicate when an item whose current
170 location is a special processing ('PROC') or shelving cart
171 ('CART') location is back in the stacks.
176 my ( $itemnumber ) = @_;
178 unless ( $itemnumber ) {
179 croak "FAILED CartToShelf() - no itemnumber supplied";
182 my $item = GetItem($itemnumber);
183 $item->{location} = $item->{permanent_location};
184 ModItem($item, undef, $itemnumber);
187 =head2 AddItemFromMarc
189 my ($biblionumber, $biblioitemnumber, $itemnumber)
190 = AddItemFromMarc($source_item_marc, $biblionumber);
192 Given a MARC::Record object containing an embedded item
193 record and a biblionumber, create a new item record.
197 sub AddItemFromMarc {
198 my ( $source_item_marc, $biblionumber ) = @_;
199 my $dbh = C4::Context->dbh;
201 # parse item hash from MARC
202 my $frameworkcode = GetFrameworkCode( $biblionumber );
203 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
205 my $localitemmarc=MARC::Record->new;
206 $localitemmarc->append_fields($source_item_marc->field($itemtag));
207 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
208 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
209 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
214 my ($biblionumber, $biblioitemnumber, $itemnumber)
215 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
217 Given a hash containing item column names as keys,
218 create a new Koha item record.
220 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
221 do not need to be supplied for general use; they exist
222 simply to allow them to be picked up from AddItemFromMarc.
224 The final optional parameter, C<$unlinked_item_subfields>, contains
225 an arrayref containing subfields present in the original MARC
226 representation of the item (e.g., from the item editor) that are
227 not mapped to C<items> columns directly but should instead
228 be stored in C<items.more_subfields_xml> and included in
229 the biblio items tag for display and indexing.
235 my $biblionumber = shift;
237 my $dbh = @_ ? shift : C4::Context->dbh;
238 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
239 my $unlinked_item_subfields;
241 $unlinked_item_subfields = shift
244 # needs old biblionumber and biblioitemnumber
245 $item->{'biblionumber'} = $biblionumber;
246 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
247 $sth->execute( $item->{'biblionumber'} );
248 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
250 _set_defaults_for_add($item);
251 _set_derived_columns_for_add($item);
252 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
253 # FIXME - checks here
254 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
255 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
256 $itype_sth->execute( $item->{'biblionumber'} );
257 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
260 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
261 $item->{'itemnumber'} = $itemnumber;
263 # create MARC tag representing item and add to bib
264 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
265 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
267 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
269 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
272 =head2 AddItemBatchFromMarc
274 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
275 $biblionumber, $biblioitemnumber, $frameworkcode);
277 Efficiently create item records from a MARC biblio record with
278 embedded item fields. This routine is suitable for batch jobs.
280 This API assumes that the bib record has already been
281 saved to the C<biblio> and C<biblioitems> tables. It does
282 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
283 are populated, but it will do so via a call to ModBibiloMarc.
285 The goal of this API is to have a similar effect to using AddBiblio
286 and AddItems in succession, but without inefficient repeated
287 parsing of the MARC XML bib record.
289 This function returns an arrayref of new itemsnumbers and an arrayref of item
290 errors encountered during the processing. Each entry in the errors
291 list is a hashref containing the following keys:
297 Sequence number of original item tag in the MARC record.
301 Item barcode, provide to assist in the construction of
302 useful error messages.
304 =item error_condition
306 Code representing the error condition. Can be 'duplicate_barcode',
307 'invalid_homebranch', or 'invalid_holdingbranch'.
309 =item error_information
311 Additional information appropriate to the error condition.
317 sub AddItemBatchFromMarc {
318 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
320 my @itemnumbers = ();
322 my $dbh = C4::Context->dbh;
324 # loop through the item tags and start creating items
325 my @bad_item_fields = ();
326 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
327 my $item_sequence_num = 0;
328 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
329 $item_sequence_num++;
330 # we take the item field and stick it into a new
331 # MARC record -- this is required so far because (FIXME)
332 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
333 # and there is no TransformMarcFieldToKoha
334 my $temp_item_marc = MARC::Record->new();
335 $temp_item_marc->append_fields($item_field);
337 # add biblionumber and biblioitemnumber
338 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
339 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
340 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
341 $item->{'biblionumber'} = $biblionumber;
342 $item->{'biblioitemnumber'} = $biblioitemnumber;
344 # check for duplicate barcode
345 my %item_errors = CheckItemPreSave($item);
347 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
348 push @bad_item_fields, $item_field;
352 _set_defaults_for_add($item);
353 _set_derived_columns_for_add($item);
354 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
355 warn $error if $error;
356 push @itemnumbers, $itemnumber; # FIXME not checking error
357 $item->{'itemnumber'} = $itemnumber;
359 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
361 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
362 $item_field->replace_with($new_item_marc->field($itemtag));
365 # remove any MARC item fields for rejected items
366 foreach my $item_field (@bad_item_fields) {
367 $record->delete_field($item_field);
370 # update the MARC biblio
371 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
373 return (\@itemnumbers, \@errors);
376 =head2 ModItemFromMarc
378 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
380 This function updates an item record based on a supplied
381 C<MARC::Record> object containing an embedded item field.
382 This API is meant for the use of C<additem.pl>; for
383 other purposes, C<ModItem> should be used.
385 This function uses the hash %default_values_for_mod_from_marc,
386 which contains default values for item fields to
387 apply when modifying an item. This is needed beccause
388 if an item field's value is cleared, TransformMarcToKoha
389 does not include the column in the
390 hash that's passed to ModItem, which without
391 use of this hash makes it impossible to clear
392 an item field's value. See bug 2466.
394 Note that only columns that can be directly
395 changed from the cataloging and serials
396 item editors are included in this hash.
400 my %default_values_for_mod_from_marc = (
402 booksellerid => undef,
404 'items.cn_source' => undef,
407 # dateaccessioned => undef,
409 holdingbranch => undef,
411 itemcallnumber => undef,
420 replacementprice => undef,
421 replacementpricedate => undef,
424 stocknumber => undef,
429 sub ModItemFromMarc {
430 my $item_marc = shift;
431 my $biblionumber = shift;
432 my $itemnumber = shift;
434 my $dbh = C4::Context->dbh;
435 my $frameworkcode = GetFrameworkCode($biblionumber);
436 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
438 my $localitemmarc = MARC::Record->new;
439 $localitemmarc->append_fields( $item_marc->field($itemtag) );
440 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
441 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
442 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
444 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
446 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
451 ModItem({ column => $newvalue }, $biblionumber,
452 $itemnumber[, $original_item_marc]);
454 Change one or more columns in an item record and update
455 the MARC representation of the item.
457 The first argument is a hashref mapping from item column
458 names to the new values. The second and third arguments
459 are the biblionumber and itemnumber, respectively.
461 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
462 an arrayref containing subfields present in the original MARC
463 representation of the item (e.g., from the item editor) that are
464 not mapped to C<items> columns directly but should instead
465 be stored in C<items.more_subfields_xml> and included in
466 the biblio items tag for display and indexing.
468 If one of the changed columns is used to calculate
469 the derived value of a column such as C<items.cn_sort>,
470 this routine will perform the necessary calculation
477 my $biblionumber = shift;
478 my $itemnumber = shift;
480 # if $biblionumber is undefined, get it from the current item
481 unless (defined $biblionumber) {
482 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
485 my $dbh = @_ ? shift : C4::Context->dbh;
486 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
488 my $unlinked_item_subfields;
490 $unlinked_item_subfields = shift;
491 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
494 $item->{'itemnumber'} = $itemnumber or return undef;
495 _set_derived_columns_for_mod($item);
496 _do_column_fixes_for_mod($item);
499 # attempt to change itemnumber
500 # attempt to change biblionumber (if we want
501 # an API to relink an item to a different bib,
502 # it should be a separate function)
505 _koha_modify_item($item);
507 # update biblio MARC XML
508 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
510 unless (defined $unlinked_item_subfields) {
511 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
513 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
514 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
516 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
517 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
518 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
521 =head2 ModItemTransfer
523 ModItemTransfer($itenumber, $frombranch, $tobranch);
525 Marks an item as being transferred from one branch
530 sub ModItemTransfer {
531 my ( $itemnumber, $frombranch, $tobranch ) = @_;
533 my $dbh = C4::Context->dbh;
535 #new entry in branchtransfers....
536 my $sth = $dbh->prepare(
537 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
538 VALUES (?, ?, NOW(), ?)");
539 $sth->execute($itemnumber, $frombranch, $tobranch);
541 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
542 ModDateLastSeen($itemnumber);
546 =head2 ModDateLastSeen
548 ModDateLastSeen($itemnum);
550 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
551 C<$itemnum> is the item number
555 sub ModDateLastSeen {
556 my ($itemnumber) = @_;
558 my $today = C4::Dates->new();
559 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
564 DelItem($dbh, $biblionumber, $itemnumber);
566 Exported function (core API) for deleting an item record in Koha.
571 my ( $dbh, $biblionumber, $itemnumber ) = @_;
573 # FIXME check the item has no current issues
575 _koha_delete_item( $dbh, $itemnumber );
577 # get the MARC record
578 my $record = GetMarcBiblio($biblionumber);
579 my $frameworkcode = GetFrameworkCode($biblionumber);
582 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
583 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
585 #search item field code
586 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
587 my @fields = $record->field($itemtag);
589 # delete the item specified
590 foreach my $field (@fields) {
591 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
592 $record->delete_field($field);
595 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
596 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
599 =head2 CheckItemPreSave
601 my $item_ref = TransformMarcToKoha($marc, 'items');
603 my %errors = CheckItemPreSave($item_ref);
604 if (exists $errors{'duplicate_barcode'}) {
605 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
606 } elsif (exists $errors{'invalid_homebranch'}) {
607 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
608 } elsif (exists $errors{'invalid_holdingbranch'}) {
609 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
614 Given a hashref containing item fields, determine if it can be
615 inserted or updated in the database. Specifically, checks for
616 database integrity issues, and returns a hash containing any
617 of the following keys, if applicable.
621 =item duplicate_barcode
623 Barcode, if it duplicates one already found in the database.
625 =item invalid_homebranch
627 Home branch, if not defined in branches table.
629 =item invalid_holdingbranch
631 Holding branch, if not defined in branches table.
635 This function does NOT implement any policy-related checks,
636 e.g., whether current operator is allowed to save an
637 item that has a given branch code.
641 sub CheckItemPreSave {
642 my $item_ref = shift;
646 # check for duplicate barcode
647 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
648 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
649 if ($existing_itemnumber) {
650 if (!exists $item_ref->{'itemnumber'} # new item
651 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
652 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
657 # check for valid home branch
658 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
659 my $branch_name = GetBranchName($item_ref->{'homebranch'});
660 unless (defined $branch_name) {
661 # relies on fact that branches.branchname is a non-NULL column,
662 # so GetBranchName returns undef only if branch does not exist
663 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
667 # check for valid holding branch
668 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
669 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
670 unless (defined $branch_name) {
671 # relies on fact that branches.branchname is a non-NULL column,
672 # so GetBranchName returns undef only if branch does not exist
673 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
681 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
683 The following functions provide various ways of
684 getting an item record, a set of item records, or
685 lists of authorized values for certain item fields.
687 Some of the functions in this group are candidates
688 for refactoring -- for example, some of the code
689 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
690 has copy-and-paste work.
696 $itemstatushash = GetItemStatus($fwkcode);
698 Returns a list of valid values for the
699 C<items.notforloan> field.
701 NOTE: does B<not> return an individual item's
704 Can be MARC dependant.
706 But basically could be can be loan or not
707 Create a status selector with the following code
709 =head3 in PERL SCRIPT
711 my $itemstatushash = getitemstatus;
713 foreach my $thisstatus (keys %$itemstatushash) {
714 my %row =(value => $thisstatus,
715 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
717 push @itemstatusloop, \%row;
719 $template->param(statusloop=>\@itemstatusloop);
723 <select name="statusloop">
724 <option value="">Default</option>
725 <!-- TMPL_LOOP name="statusloop" -->
726 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
734 # returns a reference to a hash of references to status...
737 my $dbh = C4::Context->dbh;
739 $fwk = '' unless ($fwk);
740 my ( $tag, $subfield ) =
741 GetMarcFromKohaField( "items.notforloan", $fwk );
742 if ( $tag and $subfield ) {
745 "SELECT authorised_value
746 FROM marc_subfield_structure
752 $sth->execute( $tag, $subfield, $fwk );
753 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
756 "SELECT authorised_value,lib
757 FROM authorised_values
762 $authvalsth->execute($authorisedvaluecat);
763 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
764 $itemstatus{$authorisedvalue} = $lib;
778 $itemstatus{"1"} = "Not For Loan";
782 =head2 GetItemLocation
784 $itemlochash = GetItemLocation($fwk);
786 Returns a list of valid values for the
787 C<items.location> field.
789 NOTE: does B<not> return an individual item's
792 where fwk stands for an optional framework code.
793 Create a location selector with the following code
795 =head3 in PERL SCRIPT
797 my $itemlochash = getitemlocation;
799 foreach my $thisloc (keys %$itemlochash) {
800 my $selected = 1 if $thisbranch eq $branch;
801 my %row =(locval => $thisloc,
802 selected => $selected,
803 locname => $itemlochash->{$thisloc},
805 push @itemlocloop, \%row;
807 $template->param(itemlocationloop => \@itemlocloop);
811 <select name="location">
812 <option value="">Default</option>
813 <!-- TMPL_LOOP name="itemlocationloop" -->
814 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
820 sub GetItemLocation {
822 # returns a reference to a hash of references to location...
825 my $dbh = C4::Context->dbh;
827 $fwk = '' unless ($fwk);
828 my ( $tag, $subfield ) =
829 GetMarcFromKohaField( "items.location", $fwk );
830 if ( $tag and $subfield ) {
833 "SELECT authorised_value
834 FROM marc_subfield_structure
839 $sth->execute( $tag, $subfield, $fwk );
840 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
843 "SELECT authorised_value,lib
844 FROM authorised_values
848 $authvalsth->execute($authorisedvaluecat);
849 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
850 $itemlocation{$authorisedvalue} = $lib;
852 return \%itemlocation;
864 $itemlocation{"1"} = "Not For Loan";
865 return \%itemlocation;
870 $items = GetLostItems( $where, $orderby );
872 This function gets a list of lost items.
878 C<$where> is a hashref. it containts a field of the items table as key
879 and the value to match as value. For example:
881 { barcode => 'abc123',
882 homebranch => 'CPL', }
884 C<$orderby> is a field of the items table by which the resultset
889 C<$items> is a reference to an array full of hashrefs with columns
890 from the "items" table as keys.
892 =item usage in the perl script:
894 my $where = { barcode => '0001548' };
895 my $items = GetLostItems( $where, "homebranch" );
896 $template->param( itemsloop => $items );
903 # Getting input args.
906 my $dbh = C4::Context->dbh;
911 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
912 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
913 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
915 authorised_values.category = 'LOST'
916 AND itemlost IS NOT NULL
919 my @query_parameters;
920 foreach my $key (keys %$where) {
921 $query .= " AND $key LIKE ?";
922 push @query_parameters, "%$where->{$key}%";
924 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
926 if ( defined $orderby && grep($orderby, @ordervalues)) {
927 $query .= ' ORDER BY '.$orderby;
930 my $sth = $dbh->prepare($query);
931 $sth->execute( @query_parameters );
933 while ( my $row = $sth->fetchrow_hashref ){
939 =head2 GetItemsForInventory
941 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
942 $location, $itemtype $datelastseen, $branch,
943 $offset, $size, $statushash);
945 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
947 The sub returns a reference to a list of hashes, each containing
948 itemnumber, author, title, barcode, item callnumber, and date last
949 seen. It is ordered by callnumber then title.
951 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
952 the datelastseen can be used to specify that you want to see items not seen since a past date only.
953 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
954 $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.
958 sub GetItemsForInventory {
959 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
960 my $dbh = C4::Context->dbh;
961 my ( @bind_params, @where_strings );
963 my $query = <<'END_SQL';
964 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
966 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
967 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
970 for my $authvfield (keys %$statushash){
971 if ( scalar @{$statushash->{$authvfield}} > 0 ){
972 my $joinedvals = join ',', @{$statushash->{$authvfield}};
973 push @where_strings, "$authvfield in (" . $joinedvals . ")";
979 push @where_strings, 'itemcallnumber >= ?';
980 push @bind_params, $minlocation;
984 push @where_strings, 'itemcallnumber <= ?';
985 push @bind_params, $maxlocation;
989 $datelastseen = format_date_in_iso($datelastseen);
990 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
991 push @bind_params, $datelastseen;
995 push @where_strings, 'items.location = ?';
996 push @bind_params, $location;
1000 if($branch eq "homebranch"){
1001 push @where_strings, 'items.homebranch = ?';
1003 push @where_strings, 'items.holdingbranch = ?';
1005 push @bind_params, $branchcode;
1009 push @where_strings, 'biblioitems.itemtype = ?';
1010 push @bind_params, $itemtype;
1013 if ( $ignoreissued) {
1014 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1015 push @where_strings, 'issues.date_due IS NULL';
1018 if ( @where_strings ) {
1020 $query .= join ' AND ', @where_strings;
1022 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1023 my $sth = $dbh->prepare($query);
1024 $sth->execute( @bind_params );
1028 while ( my $row = $sth->fetchrow_hashref ) {
1029 $offset-- if ($offset);
1030 $row->{datelastseen}=format_date($row->{datelastseen});
1031 if ( ( !$offset ) && $size ) {
1032 push @results, $row;
1039 =head2 GetItemsCount
1041 $count = &GetItemsCount( $biblionumber);
1043 This function return count of item with $biblionumber
1048 my ( $biblionumber ) = @_;
1049 my $dbh = C4::Context->dbh;
1050 my $query = "SELECT count(*)
1052 WHERE biblionumber=?";
1053 my $sth = $dbh->prepare($query);
1054 $sth->execute($biblionumber);
1055 my $count = $sth->fetchrow;
1059 =head2 GetItemInfosOf
1061 GetItemInfosOf(@itemnumbers);
1065 sub GetItemInfosOf {
1066 my @itemnumbers = @_;
1071 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1073 return get_infos_of( $query, 'itemnumber' );
1076 =head2 GetItemsByBiblioitemnumber
1078 GetItemsByBiblioitemnumber($biblioitemnumber);
1080 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1081 Called by C<C4::XISBN>
1085 sub GetItemsByBiblioitemnumber {
1086 my ( $bibitem ) = @_;
1087 my $dbh = C4::Context->dbh;
1088 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1089 # Get all items attached to a biblioitem
1092 $sth->execute($bibitem) || die $sth->errstr;
1093 while ( my $data = $sth->fetchrow_hashref ) {
1094 # Foreach item, get circulation information
1095 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1096 WHERE itemnumber = ?
1097 AND issues.borrowernumber = borrowers.borrowernumber"
1099 $sth2->execute( $data->{'itemnumber'} );
1100 if ( my $data2 = $sth2->fetchrow_hashref ) {
1101 # if item is out, set the due date and who it is out too
1102 $data->{'date_due'} = $data2->{'date_due'};
1103 $data->{'cardnumber'} = $data2->{'cardnumber'};
1104 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1107 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1108 $data->{'date_due'} = '';
1110 # Find the last 3 people who borrowed this item.
1111 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1112 AND old_issues.borrowernumber = borrowers.borrowernumber
1113 ORDER BY returndate desc,timestamp desc LIMIT 3";
1114 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1115 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1117 while ( my $data2 = $sth2->fetchrow_hashref ) {
1118 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1119 $data->{"card$i2"} = $data2->{'cardnumber'};
1120 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1123 push(@results,$data);
1130 @results = GetItemsInfo($biblionumber, $type);
1132 Returns information about books with the given biblionumber.
1134 C<$type> may be either C<intra> or anything else. If it is not set to
1135 C<intra>, then the search will exclude lost, very overdue, and
1138 C<GetItemsInfo> returns a list of references-to-hash. Each element
1139 contains a number of keys. Most of them are table items from the
1140 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1141 Koha database. Other keys include:
1145 =item C<$data-E<gt>{branchname}>
1147 The name (not the code) of the branch to which the book belongs.
1149 =item C<$data-E<gt>{datelastseen}>
1151 This is simply C<items.datelastseen>, except that while the date is
1152 stored in YYYY-MM-DD format in the database, here it is converted to
1153 DD/MM/YYYY format. A NULL date is returned as C<//>.
1155 =item C<$data-E<gt>{datedue}>
1157 =item C<$data-E<gt>{class}>
1159 This is the concatenation of C<biblioitems.classification>, the book's
1160 Dewey code, and C<biblioitems.subclass>.
1162 =item C<$data-E<gt>{ocount}>
1164 I think this is the number of copies of the book available.
1166 =item C<$data-E<gt>{order}>
1168 If this is set, it is set to C<One Order>.
1175 my ( $biblionumber, $type ) = @_;
1176 my $dbh = C4::Context->dbh;
1177 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1183 biblioitems.itemtype,
1186 biblioitems.publicationyear,
1187 biblioitems.publishercode,
1188 biblioitems.volumedate,
1189 biblioitems.volumedesc,
1192 items.notforloan as itemnotforloan,
1193 itemtypes.description,
1194 itemtypes.notforloan as notforloan_per_itemtype,
1197 LEFT JOIN branches ON items.homebranch = branches.branchcode
1198 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1199 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1200 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1201 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1202 $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1203 my $sth = $dbh->prepare($query);
1204 $sth->execute($biblionumber);
1209 my $isth = $dbh->prepare(
1210 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1211 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1212 WHERE itemnumber = ?"
1214 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1215 while ( my $data = $sth->fetchrow_hashref ) {
1218 $isth->execute( $data->{'itemnumber'} );
1219 if ( my $idata = $isth->fetchrow_hashref ) {
1220 $data->{borrowernumber} = $idata->{borrowernumber};
1221 $data->{cardnumber} = $idata->{cardnumber};
1222 $data->{surname} = $idata->{surname};
1223 $data->{firstname} = $idata->{firstname};
1224 $datedue = $idata->{'date_due'};
1225 if (C4::Context->preference("IndependantBranches")){
1226 my $userenv = C4::Context->userenv;
1227 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1228 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1232 if ( $data->{'serial'}) {
1233 $ssth->execute($data->{'itemnumber'}) ;
1234 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1237 if ( $datedue eq '' ) {
1238 my ( $restype, $reserves ) =
1239 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1240 # Previous conditional check with if ($restype) is not needed because a true
1241 # result for one item will result in subsequent items defaulting to this true
1243 $count_reserves = $restype;
1245 #get branch information.....
1246 my $bsth = $dbh->prepare(
1247 "SELECT * FROM branches WHERE branchcode = ?
1250 $bsth->execute( $data->{'holdingbranch'} );
1251 if ( my $bdata = $bsth->fetchrow_hashref ) {
1252 $data->{'branchname'} = $bdata->{'branchname'};
1254 $data->{'datedue'} = $datedue;
1255 $data->{'count_reserves'} = $count_reserves;
1257 # get notforloan complete status if applicable
1258 my $sthnflstatus = $dbh->prepare(
1259 'SELECT authorised_value
1260 FROM marc_subfield_structure
1261 WHERE kohafield="items.notforloan"
1265 $sthnflstatus->execute;
1266 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1267 if ($authorised_valuecode) {
1268 $sthnflstatus = $dbh->prepare(
1269 "SELECT lib FROM authorised_values
1271 AND authorised_value=?"
1273 $sthnflstatus->execute( $authorised_valuecode,
1274 $data->{itemnotforloan} );
1275 my ($lib) = $sthnflstatus->fetchrow;
1276 $data->{notforloanvalue} = $lib;
1279 # get restricted status and description if applicable
1280 my $restrictedstatus = $dbh->prepare(
1281 'SELECT authorised_value
1282 FROM marc_subfield_structure
1283 WHERE kohafield="items.restricted"
1287 $restrictedstatus->execute;
1288 ($authorised_valuecode) = $restrictedstatus->fetchrow;
1289 if ($authorised_valuecode) {
1290 $restrictedstatus = $dbh->prepare(
1291 "SELECT lib,lib_opac FROM authorised_values
1293 AND authorised_value=?"
1295 $restrictedstatus->execute( $authorised_valuecode,
1296 $data->{restricted} );
1298 if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1299 $data->{restricted} = $rstdata->{'lib'};
1300 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1304 # my stack procedures
1305 my $stackstatus = $dbh->prepare(
1306 'SELECT authorised_value
1307 FROM marc_subfield_structure
1308 WHERE kohafield="items.stack"
1311 $stackstatus->execute;
1313 ($authorised_valuecode) = $stackstatus->fetchrow;
1314 if ($authorised_valuecode) {
1315 $stackstatus = $dbh->prepare(
1317 FROM authorised_values
1319 AND authorised_value=?
1322 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1323 my ($lib) = $stackstatus->fetchrow;
1324 $data->{stack} = $lib;
1326 # Find the last 3 people who borrowed this item.
1327 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1328 WHERE itemnumber = ?
1329 AND old_issues.borrowernumber = borrowers.borrowernumber
1330 ORDER BY returndate DESC
1332 $sth2->execute($data->{'itemnumber'});
1334 while (my $data2 = $sth2->fetchrow_hashref()) {
1335 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1336 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1337 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1341 $results[$i] = $data;
1345 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1351 =head2 GetItemsLocationInfo
1353 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1355 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1357 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1361 =item C<$data-E<gt>{homebranch}>
1363 Branch Name of the item's homebranch
1365 =item C<$data-E<gt>{holdingbranch}>
1367 Branch Name of the item's holdingbranch
1369 =item C<$data-E<gt>{location}>
1371 Item's shelving location code
1373 =item C<$data-E<gt>{location_intranet}>
1375 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1377 =item C<$data-E<gt>{location_opac}>
1379 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1382 =item C<$data-E<gt>{itemcallnumber}>
1384 Item's itemcallnumber
1386 =item C<$data-E<gt>{cn_sort}>
1388 Item's call number normalized for sorting
1394 sub GetItemsLocationInfo {
1395 my $biblionumber = shift;
1398 my $dbh = C4::Context->dbh;
1399 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1400 location, itemcallnumber, cn_sort
1401 FROM items, branches as a, branches as b
1402 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1403 AND biblionumber = ?
1404 ORDER BY cn_sort ASC";
1405 my $sth = $dbh->prepare($query);
1406 $sth->execute($biblionumber);
1408 while ( my $data = $sth->fetchrow_hashref ) {
1409 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1410 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1411 push @results, $data;
1417 =head2 GetLastAcquisitions
1419 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1420 'itemtypes' => ('BK','BD')}, 10);
1424 sub GetLastAcquisitions {
1425 my ($data,$max) = @_;
1427 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1429 my $number_of_branches = @{$data->{branches}};
1430 my $number_of_itemtypes = @{$data->{itemtypes}};
1433 my @where = ('WHERE 1 ');
1434 $number_of_branches and push @where
1435 , 'AND holdingbranch IN ('
1436 , join(',', ('?') x $number_of_branches )
1440 $number_of_itemtypes and push @where
1441 , "AND $itemtype IN ("
1442 , join(',', ('?') x $number_of_itemtypes )
1446 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1447 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1448 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1450 GROUP BY biblio.biblionumber
1451 ORDER BY dateaccessioned DESC LIMIT $max";
1453 my $dbh = C4::Context->dbh;
1454 my $sth = $dbh->prepare($query);
1456 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1459 while( my $row = $sth->fetchrow_hashref){
1460 push @results, {date => $row->{dateaccessioned}
1461 , biblionumber => $row->{biblionumber}
1462 , title => $row->{title}};
1468 =head2 get_itemnumbers_of
1470 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1472 Given a list of biblionumbers, return the list of corresponding itemnumbers
1473 for each biblionumber.
1475 Return a reference on a hash where keys are biblionumbers and values are
1476 references on array of itemnumbers.
1480 sub get_itemnumbers_of {
1481 my @biblionumbers = @_;
1483 my $dbh = C4::Context->dbh;
1489 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1491 my $sth = $dbh->prepare($query);
1492 $sth->execute(@biblionumbers);
1496 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1497 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1500 return \%itemnumbers_of;
1503 =head2 GetItemnumberFromBarcode
1505 $result = GetItemnumberFromBarcode($barcode);
1509 sub GetItemnumberFromBarcode {
1511 my $dbh = C4::Context->dbh;
1514 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1515 $rq->execute($barcode);
1516 my ($result) = $rq->fetchrow;
1520 =head2 GetBarcodeFromItemnumber
1522 $result = GetBarcodeFromItemnumber($itemnumber);
1526 sub GetBarcodeFromItemnumber {
1527 my ($itemnumber) = @_;
1528 my $dbh = C4::Context->dbh;
1531 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1532 $rq->execute($itemnumber);
1533 my ($result) = $rq->fetchrow;
1537 =head3 get_item_authorised_values
1539 find the types and values for all authorised values assigned to this item.
1541 parameters: itemnumber
1543 returns: a hashref malling the authorised value to the value set for this itemnumber
1545 $authorised_values = {
1551 'RESTRICTED' => undef,
1554 'branches' => 'CPL',
1555 'cn_source' => undef,
1556 'itemtypes' => 'SER',
1559 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1563 sub get_item_authorised_values {
1564 my $itemnumber = shift;
1566 # assume that these entries in the authorised_value table are item level.
1567 my $query = q(SELECT distinct authorised_value, kohafield
1568 FROM marc_subfield_structure
1569 WHERE kohafield like 'item%'
1570 AND authorised_value != '' );
1572 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1573 my $iteminfo = GetItem( $itemnumber );
1574 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1576 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1577 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1578 $field =~ s/^items\.//;
1579 if ( exists $iteminfo->{ $field } ) {
1580 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1583 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1587 =head3 get_authorised_value_images
1589 find a list of icons that are appropriate for display based on the
1590 authorised values for a biblio.
1592 parameters: listref of authorised values, such as comes from
1593 get_item_authorised_values or
1594 from C4::Biblio::get_biblio_authorised_values
1596 returns: listref of hashrefs for each image. Each hashref looks like this:
1598 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1603 Notes: Currently, I put on the full path to the images on the staff
1604 side. This should either be configurable or not done at all. Since I
1605 have to deal with 'intranet' or 'opac' in
1606 get_biblio_authorised_values, perhaps I should be passing it in.
1610 sub get_authorised_value_images {
1611 my $authorised_values = shift;
1615 my $authorised_value_list = GetAuthorisedValues();
1616 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1617 foreach my $this_authorised_value ( @$authorised_value_list ) {
1618 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1619 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1620 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1621 if ( defined $this_authorised_value->{'imageurl'} ) {
1622 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1623 label => $this_authorised_value->{'lib'},
1624 category => $this_authorised_value->{'category'},
1625 value => $this_authorised_value->{'authorised_value'}, };
1630 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1635 =head1 LIMITED USE FUNCTIONS
1637 The following functions, while part of the public API,
1638 are not exported. This is generally because they are
1639 meant to be used by only one script for a specific
1640 purpose, and should not be used in any other context
1641 without careful thought.
1647 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1649 Returns MARC::Record of the item passed in parameter.
1650 This function is meant for use only in C<cataloguing/additem.pl>,
1651 where it is needed to support that script's MARC-like
1657 my ( $biblionumber, $itemnumber ) = @_;
1659 # GetMarcItem has been revised so that it does the following:
1660 # 1. Gets the item information from the items table.
1661 # 2. Converts it to a MARC field for storage in the bib record.
1663 # The previous behavior was:
1664 # 1. Get the bib record.
1665 # 2. Return the MARC tag corresponding to the item record.
1667 # The difference is that one treats the items row as authoritative,
1668 # while the other treats the MARC representation as authoritative
1669 # under certain circumstances.
1671 my $itemrecord = GetItem($itemnumber);
1673 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1674 # Also, don't emit a subfield if the underlying field is blank.
1677 return Item2Marc($itemrecord,$biblionumber);
1681 my ($itemrecord,$biblionumber)=@_;
1684 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1685 } keys %{ $itemrecord }
1687 my $itemmarc = TransformKohaToMarc($mungeditem);
1688 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1690 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1691 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1692 foreach my $field ($itemmarc->field($itemtag)){
1693 $field->add_subfields(@$unlinked_item_subfields);
1699 =head1 PRIVATE FUNCTIONS AND VARIABLES
1701 The following functions are not meant to be called
1702 directly, but are documented in order to explain
1703 the inner workings of C<C4::Items>.
1707 =head2 %derived_columns
1709 This hash keeps track of item columns that
1710 are strictly derived from other columns in
1711 the item record and are not meant to be set
1714 Each key in the hash should be the name of a
1715 column (as named by TransformMarcToKoha). Each
1716 value should be hashref whose keys are the
1717 columns on which the derived column depends. The
1718 hashref should also contain a 'BUILDER' key
1719 that is a reference to a sub that calculates
1724 my %derived_columns = (
1725 'items.cn_sort' => {
1726 'itemcallnumber' => 1,
1727 'items.cn_source' => 1,
1728 'BUILDER' => \&_calc_items_cn_sort,
1732 =head2 _set_derived_columns_for_add
1734 _set_derived_column_for_add($item);
1736 Given an item hash representing a new item to be added,
1737 calculate any derived columns. Currently the only
1738 such column is C<items.cn_sort>.
1742 sub _set_derived_columns_for_add {
1745 foreach my $column (keys %derived_columns) {
1746 my $builder = $derived_columns{$column}->{'BUILDER'};
1747 my $source_values = {};
1748 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1749 next if $source_column eq 'BUILDER';
1750 $source_values->{$source_column} = $item->{$source_column};
1752 $builder->($item, $source_values);
1756 =head2 _set_derived_columns_for_mod
1758 _set_derived_column_for_mod($item);
1760 Given an item hash representing a new item to be modified.
1761 calculate any derived columns. Currently the only
1762 such column is C<items.cn_sort>.
1764 This routine differs from C<_set_derived_columns_for_add>
1765 in that it needs to handle partial item records. In other
1766 words, the caller of C<ModItem> may have supplied only one
1767 or two columns to be changed, so this function needs to
1768 determine whether any of the columns to be changed affect
1769 any of the derived columns. Also, if a derived column
1770 depends on more than one column, but the caller is not
1771 changing all of then, this routine retrieves the unchanged
1772 values from the database in order to ensure a correct
1777 sub _set_derived_columns_for_mod {
1780 foreach my $column (keys %derived_columns) {
1781 my $builder = $derived_columns{$column}->{'BUILDER'};
1782 my $source_values = {};
1783 my %missing_sources = ();
1784 my $must_recalc = 0;
1785 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1786 next if $source_column eq 'BUILDER';
1787 if (exists $item->{$source_column}) {
1789 $source_values->{$source_column} = $item->{$source_column};
1791 $missing_sources{$source_column} = 1;
1795 foreach my $source_column (keys %missing_sources) {
1796 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1798 $builder->($item, $source_values);
1803 =head2 _do_column_fixes_for_mod
1805 _do_column_fixes_for_mod($item);
1807 Given an item hashref containing one or more
1808 columns to modify, fix up certain values.
1809 Specifically, set to 0 any passed value
1810 of C<notforloan>, C<damaged>, C<itemlost>, or
1811 C<wthdrawn> that is either undefined or
1812 contains the empty string.
1816 sub _do_column_fixes_for_mod {
1819 if (exists $item->{'notforloan'} and
1820 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1821 $item->{'notforloan'} = 0;
1823 if (exists $item->{'damaged'} and
1824 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1825 $item->{'damaged'} = 0;
1827 if (exists $item->{'itemlost'} and
1828 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1829 $item->{'itemlost'} = 0;
1831 if (exists $item->{'wthdrawn'} and
1832 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1833 $item->{'wthdrawn'} = 0;
1835 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1836 $item->{'permanent_location'} = $item->{'location'};
1838 if (exists $item->{'timestamp'}) {
1839 delete $item->{'timestamp'};
1843 =head2 _get_single_item_column
1845 _get_single_item_column($column, $itemnumber);
1847 Retrieves the value of a single column from an C<items>
1848 row specified by C<$itemnumber>.
1852 sub _get_single_item_column {
1854 my $itemnumber = shift;
1856 my $dbh = C4::Context->dbh;
1857 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1858 $sth->execute($itemnumber);
1859 my ($value) = $sth->fetchrow();
1863 =head2 _calc_items_cn_sort
1865 _calc_items_cn_sort($item, $source_values);
1867 Helper routine to calculate C<items.cn_sort>.
1871 sub _calc_items_cn_sort {
1873 my $source_values = shift;
1875 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1878 =head2 _set_defaults_for_add
1880 _set_defaults_for_add($item_hash);
1882 Given an item hash representing an item to be added, set
1883 correct default values for columns whose default value
1884 is not handled by the DBMS. This includes the following
1891 C<items.dateaccessioned>
1913 sub _set_defaults_for_add {
1915 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1916 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1919 =head2 _koha_new_item
1921 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1923 Perform the actual insert into the C<items> table.
1927 sub _koha_new_item {
1928 my ( $item, $barcode ) = @_;
1929 my $dbh=C4::Context->dbh;
1932 "INSERT INTO items SET
1934 biblioitemnumber = ?,
1936 dateaccessioned = ?,
1940 replacementprice = ?,
1941 replacementpricedate = NOW(),
1942 datelastborrowed = ?,
1943 datelastseen = NOW(),
1966 more_subfields_xml = ?,
1970 my $sth = $dbh->prepare($query);
1972 $item->{'biblionumber'},
1973 $item->{'biblioitemnumber'},
1975 $item->{'dateaccessioned'},
1976 $item->{'booksellerid'},
1977 $item->{'homebranch'},
1979 $item->{'replacementprice'},
1980 $item->{datelastborrowed},
1982 $item->{'notforloan'},
1984 $item->{'itemlost'},
1985 $item->{'wthdrawn'},
1986 $item->{'itemcallnumber'},
1987 $item->{'restricted'},
1988 $item->{'itemnotes'},
1989 $item->{'holdingbranch'},
1991 $item->{'location'},
1994 $item->{'renewals'},
1995 $item->{'reserves'},
1996 $item->{'items.cn_source'},
1997 $item->{'items.cn_sort'},
2000 $item->{'materials'},
2002 $item->{'enumchron'},
2003 $item->{'more_subfields_xml'},
2004 $item->{'copynumber'},
2005 $item->{'stocknumber'},
2007 my $itemnumber = $dbh->{'mysql_insertid'};
2008 if ( defined $sth->errstr ) {
2009 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2011 return ( $itemnumber, $error );
2014 =head2 MoveItemFromBiblio
2016 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2018 Moves an item from a biblio to another
2020 Returns undef if the move failed or the biblionumber of the destination record otherwise
2024 sub MoveItemFromBiblio {
2025 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2026 my $dbh = C4::Context->dbh;
2027 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2028 $sth->execute( $tobiblio );
2029 my ( $tobiblioitem ) = $sth->fetchrow();
2030 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2031 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2035 my $frameworkcode = GetFrameworkCode($frombiblio);
2037 # Getting marc field for itemnumber
2038 my ($itemtag, $itemsubfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
2040 # Getting the record we want to move the item from
2041 my $record = GetMarcBiblio($frombiblio);
2043 # The item we want to move
2047 foreach my $fielditem ($record->field($itemtag)){
2048 # If it is the item we want to move
2049 if ($fielditem->subfield($itemsubfield) == $itemnumber) {
2052 # Then delete it from the record
2053 $record->delete_field($fielditem)
2057 # If we found an item (should always true, except in case of database-marcxml inconsistency)
2060 # Checking if the item we want to move is in an order
2061 my $order = GetOrderFromItemnumber($itemnumber);
2063 # Replacing the biblionumber within the order if necessary
2064 $order->{'biblionumber'} = $tobiblio;
2068 # Saving the modification
2069 ModBiblioMarc($record, $frombiblio, $frameworkcode);
2071 # Getting the record we want to move the item to
2072 $record = GetMarcBiblio($tobiblio);
2074 # Inserting the previously saved item
2075 $record->insert_fields_ordered($item);
2077 # Saving the modification
2078 ModBiblioMarc($record, $tobiblio, $frameworkcode);
2090 DelItemCheck($dbh, $biblionumber, $itemnumber);
2092 Exported function (core API) for deleting an item record in Koha if there no current issue.
2097 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2100 # check that there is no issue on this item before deletion.
2101 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2102 $sth->execute($itemnumber);
2104 my $item = GetItem($itemnumber);
2105 my $onloan = $sth->fetchrow;
2107 $error = "book_on_loan";
2109 elsif (C4::Context->preference("IndependantBranches") and (C4::Context->userenv->{branch} ne $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'})){
2110 $error = "not_same_branch";
2114 $error = "book_on_loan"
2117 # check it doesnt have a waiting reserve
2118 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2119 $sth->execute($itemnumber);
2120 my $reserve=$sth->fetchrow;
2122 $error = "book_reserved";
2125 DelItem($dbh, $biblionumber, $itemnumber);
2133 =head2 _koha_modify_item
2135 my ($itemnumber,$error) =_koha_modify_item( $item );
2137 Perform the actual update of the C<items> row. Note that this
2138 routine accepts a hashref specifying the columns to update.
2142 sub _koha_modify_item {
2144 my $dbh=C4::Context->dbh;
2147 my $query = "UPDATE items SET ";
2149 for my $key ( keys %$item ) {
2151 push @bind, $item->{$key};
2154 $query .= " WHERE itemnumber=?";
2155 push @bind, $item->{'itemnumber'};
2156 my $sth = C4::Context->dbh->prepare($query);
2157 $sth->execute(@bind);
2158 if ( C4::Context->dbh->errstr ) {
2159 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2162 return ($item->{'itemnumber'},$error);
2165 =head2 _koha_delete_item
2167 _koha_delete_item( $dbh, $itemnum );
2169 Internal function to delete an item record from the koha tables
2173 sub _koha_delete_item {
2174 my ( $dbh, $itemnum ) = @_;
2176 # save the deleted item to deleteditems table
2177 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2178 $sth->execute($itemnum);
2179 my $data = $sth->fetchrow_hashref();
2180 my $query = "INSERT INTO deleteditems SET ";
2182 foreach my $key ( keys %$data ) {
2183 $query .= "$key = ?,";
2184 push( @bind, $data->{$key} );
2187 $sth = $dbh->prepare($query);
2188 $sth->execute(@bind);
2190 # delete from items table
2191 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2192 $sth->execute($itemnum);
2196 =head2 _marc_from_item_hash
2198 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2200 Given an item hash representing a complete item record,
2201 create a C<MARC::Record> object containing an embedded
2202 tag representing that item.
2204 The third, optional parameter C<$unlinked_item_subfields> is
2205 an arrayref of subfields (not mapped to C<items> fields per the
2206 framework) to be added to the MARC representation
2211 sub _marc_from_item_hash {
2213 my $frameworkcode = shift;
2214 my $unlinked_item_subfields;
2216 $unlinked_item_subfields = shift;
2219 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2220 # Also, don't emit a subfield if the underlying field is blank.
2221 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2222 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2223 : () } keys %{ $item } };
2225 my $item_marc = MARC::Record->new();
2226 foreach my $item_field ( keys %{$mungeditem} ) {
2227 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2228 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2229 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2230 foreach my $value (@values){
2231 if ( my $field = $item_marc->field($tag) ) {
2232 $field->add_subfields( $subfield => $value );
2234 my $add_subfields = [];
2235 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2236 $add_subfields = $unlinked_item_subfields;
2238 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2246 =head2 _add_item_field_to_biblio
2248 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2250 Adds the fields from a MARC record containing the
2251 representation of a Koha item record to the MARC
2252 biblio record. The input C<$item_marc> record
2253 is expect to contain just one field, the embedded
2254 item information field.
2258 sub _add_item_field_to_biblio {
2259 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2261 my $biblio_marc = GetMarcBiblio($biblionumber);
2262 foreach my $field ($item_marc->fields()) {
2263 $biblio_marc->append_fields($field);
2266 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2269 =head2 _replace_item_field_in_biblio
2271 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2273 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2274 representation of the item, examine the biblio MARC
2275 for the corresponding tag for that item and
2276 replace it with the tag from C<$item_marc>.
2280 sub _replace_item_field_in_biblio {
2281 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2282 my $dbh = C4::Context->dbh;
2284 # get complete MARC record & replace the item field by the new one
2285 my $completeRecord = GetMarcBiblio($biblionumber);
2286 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2287 my $itemField = $ItemRecord->field($itemtag);
2288 my @items = $completeRecord->field($itemtag);
2291 if ($_->subfield($itemsubfield) eq $itemnumber) {
2292 $_->replace_with($itemField);
2298 # If we haven't found the matching field,
2299 # just add it. However, this means that
2300 # there is likely a bug.
2301 $completeRecord->append_fields($itemField);
2305 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2308 =head2 _repack_item_errors
2310 Add an error message hash generated by C<CheckItemPreSave>
2311 to a list of errors.
2315 sub _repack_item_errors {
2316 my $item_sequence_num = shift;
2317 my $item_ref = shift;
2318 my $error_ref = shift;
2320 my @repacked_errors = ();
2322 foreach my $error_code (sort keys %{ $error_ref }) {
2323 my $repacked_error = {};
2324 $repacked_error->{'item_sequence'} = $item_sequence_num;
2325 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2326 $repacked_error->{'error_code'} = $error_code;
2327 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2328 push @repacked_errors, $repacked_error;
2331 return @repacked_errors;
2334 =head2 _get_unlinked_item_subfields
2336 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2340 sub _get_unlinked_item_subfields {
2341 my $original_item_marc = shift;
2342 my $frameworkcode = shift;
2344 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2346 # assume that this record has only one field, and that that
2347 # field contains only the item information
2349 my @fields = $original_item_marc->fields();
2350 if ($#fields > -1) {
2351 my $field = $fields[0];
2352 my $tag = $field->tag();
2353 foreach my $subfield ($field->subfields()) {
2354 if (defined $subfield->[1] and
2355 $subfield->[1] ne '' and
2356 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2357 push @$subfields, $subfield->[0] => $subfield->[1];
2364 =head2 _get_unlinked_subfields_xml
2366 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2370 sub _get_unlinked_subfields_xml {
2371 my $unlinked_item_subfields = shift;
2374 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2375 my $marc = MARC::Record->new();
2376 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2377 # used in the framework
2378 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2379 $marc->encoding("UTF-8");
2380 $xml = $marc->as_xml("USMARC");
2386 =head2 _parse_unlinked_item_subfields_from_xml
2388 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2392 sub _parse_unlinked_item_subfields_from_xml {
2395 return unless defined $xml and $xml ne "";
2396 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2397 my $unlinked_subfields = [];
2398 my @fields = $marc->fields();
2399 if ($#fields > -1) {
2400 foreach my $subfield ($fields[0]->subfields()) {
2401 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2404 return $unlinked_subfields;