3 # Copyright 2007 LibLime, Inc.
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
25 use C4::Dates qw/format_date format_date_in_iso/;
32 use vars qw($VERSION @ISA @EXPORT);
38 @ISA = qw( Exporter );
60 GetItemsByBiblioitemnumber
63 GetItemnumberFromBarcode
69 C4::Items - item management functions
73 This module contains an API for manipulating item
74 records in Koha, and is used by cataloguing, circulation,
75 acquisitions, and serials management.
77 A Koha item record is stored in two places: the
78 items table and embedded in a MARC tag in the XML
79 version of the associated bib record in C<biblioitems.marcxml>.
80 This is done to allow the item information to be readily
81 indexed (e.g., by Zebra), but means that each item
82 modification transaction must keep the items table
83 and the MARC XML in sync at all times.
85 Consequently, all code that creates, modifies, or deletes
86 item records B<must> use an appropriate function from
87 C<C4::Items>. If no existing function is suitable, it is
88 better to add one to C<C4::Items> than to use add
89 one-off SQL statements to add or modify items.
91 The items table will be considered authoritative. In other
92 words, if there is ever a discrepancy between the items
93 table and the MARC XML, the items table should be considered
96 =head1 HISTORICAL NOTE
98 Most of the functions in C<C4::Items> were originally in
99 the C<C4::Biblio> module.
101 =head1 CORE EXPORTED FUNCTIONS
103 The following functions are meant for use by users
112 $item = GetItem($itemnumber,$barcode,$serial);
116 Return item information, for a given itemnumber or barcode.
117 The return value is a hashref mapping item column
118 names to values. If C<$serial> is true, include serial publication data.
123 my ($itemnumber,$barcode, $serial) = @_;
124 my $dbh = C4::Context->dbh;
127 my $sth = $dbh->prepare("
129 WHERE itemnumber = ?");
130 $sth->execute($itemnumber);
131 $data = $sth->fetchrow_hashref;
133 my $sth = $dbh->prepare("
137 $sth->execute($barcode);
138 $data = $sth->fetchrow_hashref;
141 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serial where itemnumber=?");
142 $ssth->execute($data->{'itemnumber'}) ;
143 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
148 =head2 AddItemFromMarc
152 my ($biblionumber, $biblioitemnumber, $itemnumber)
153 = AddItemFromMarc($source_item_marc, $biblionumber);
157 Given a MARC::Record object containing an embedded item
158 record and a biblionumber, create a new item record.
162 sub AddItemFromMarc {
163 my ( $source_item_marc, $biblionumber ) = @_;
164 my $dbh = C4::Context->dbh;
166 # parse item hash from MARC
167 my $frameworkcode = GetFrameworkCode( $biblionumber );
168 my $item = &TransformMarcToKoha( $dbh, $source_item_marc, $frameworkcode );
169 return AddItem($item, $biblionumber, $dbh, $frameworkcode);
176 my ($biblionumber, $biblioitemnumber, $itemnumber)
177 = AddItem($item, $biblionumber[, $dbh, $frameworkcode]);
181 Given a hash containing item column names as keys,
182 create a new Koha item record.
184 The two optional parameters (C<$dbh> and C<$frameworkcode>)
185 do not need to be supplied for general use; they exist
186 simply to allow them to be picked up from AddItemFromMarc.
192 my $biblionumber = shift;
194 my $dbh = @_ ? shift : C4::Context->dbh;
195 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
197 # needs old biblionumber and biblioitemnumber
198 $item->{'biblionumber'} = $biblionumber;
199 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
200 $sth->execute( $item->{'biblionumber'} );
201 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
203 _set_defaults_for_add($item);
204 _set_derived_columns_for_add($item);
205 # FIXME - checks here
206 my ( $itemnumber, $error ) = _koha_new_item( $dbh, $item, $item->{barcode} );
207 $item->{'itemnumber'} = $itemnumber;
209 # create MARC tag representing item and add to bib
210 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode);
211 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
213 logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
214 if C4::Context->preference("CataloguingLog");
216 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
219 =head2 AddItemBatchFromMarc
223 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
227 Efficiently create item records from a MARC biblio record with
228 embedded item fields. This routine is suitable for batch jobs.
230 This API assumes that the bib record has already been
231 saved to the C<biblio> and C<biblioitems> tables. It does
232 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
233 are populated, but it will do so via a call to ModBibiloMarc.
235 The goal of this API is to have a similar effect to using AddBiblio
236 and AddItems in succession, but without inefficient repeated
237 parsing of the MARC XML bib record.
239 This function returns an arrayref of new itemsnumbers and an arrayref of item
240 errors encountered during the processing. Each entry in the errors
241 list is a hashref containing the following keys:
247 Sequence number of original item tag in the MARC record.
251 Item barcode, provide to assist in the construction of
252 useful error messages.
254 =item error_condition
256 Code representing the error condition. Can be 'duplicate_barcode',
257 'invalid_homebranch', or 'invalid_holdingbranch'.
259 =item error_information
261 Additional information appropriate to the error condition.
267 sub AddItemBatchFromMarc {
268 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
270 my @itemnumbers = ();
272 my $dbh = C4::Context->dbh;
274 # loop through the item tags and start creating items
275 my @bad_item_fields = ();
276 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
277 my $item_sequence_num = 0;
278 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
279 $item_sequence_num++;
280 # we take the item field and stick it into a new
281 # MARC record -- this is required so far because (FIXME)
282 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
283 # and there is no TransformMarcFieldToKoha
284 my $temp_item_marc = MARC::Record->new();
285 $temp_item_marc->append_fields($item_field);
287 # add biblionumber and biblioitemnumber
288 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
289 $item->{'biblionumber'} = $biblionumber;
290 $item->{'biblioitemnumber'} = $biblioitemnumber;
292 # check for duplicate barcode
293 my %item_errors = CheckItemPreSave($item);
295 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
296 push @bad_item_fields, $item_field;
300 _set_defaults_for_add($item);
301 _set_derived_columns_for_add($item);
302 my ( $itemnumber, $error ) = _koha_new_item( $dbh, $item, $item->{barcode} );
303 warn $error if $error;
304 push @itemnumbers, $itemnumber; # FIXME not checking error
305 $item->{'itemnumber'} = $itemnumber;
307 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
308 if C4::Context->preference("CataloguingLog");
310 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode);
311 $item_field->replace_with($new_item_marc->field($itemtag));
314 # remove any MARC item fields for rejected items
315 foreach my $item_field (@bad_item_fields) {
316 $record->delete_field($item_field);
319 # update the MARC biblio
320 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
322 return (\@itemnumbers, \@errors);
325 =head2 ModItemFromMarc
329 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
333 This function updates an item record based on a supplied
334 C<MARC::Record> object containing an embedded item field.
335 This API is meant for the use of C<additem.pl>; for
336 other purposes, C<ModItem> should be used.
340 sub ModItemFromMarc {
341 my $item_marc = shift;
342 my $biblionumber = shift;
343 my $itemnumber = shift;
345 my $dbh = C4::Context->dbh;
346 my $frameworkcode = GetFrameworkCode( $biblionumber );
347 my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode );
349 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode);
356 ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
360 Change one or more columns in an item record and update
361 the MARC representation of the item.
363 The first argument is a hashref mapping from item column
364 names to the new values. The second and third arguments
365 are the biblionumber and itemnumber, respectively.
367 If one of the changed columns is used to calculate
368 the derived value of a column such as C<items.cn_sort>,
369 this routine will perform the necessary calculation
376 my $biblionumber = shift;
377 my $itemnumber = shift;
379 # if $biblionumber is undefined, get it from the current item
380 unless (defined $biblionumber) {
381 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
384 my $dbh = @_ ? shift : C4::Context->dbh;
385 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
387 $item->{'itemnumber'} = $itemnumber or return undef;
388 _set_derived_columns_for_mod($item);
389 _do_column_fixes_for_mod($item);
392 # attempt to change itemnumber
393 # attempt to change biblionumber (if we want
394 # an API to relink an item to a different bib,
395 # it should be a separate function)
398 _koha_modify_item($dbh, $item);
400 # update biblio MARC XML
401 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
402 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode) or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
403 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
404 (C4::Context->userenv eq '0') and die "userenv is '0', not hashref"; # logaction line would crash anyway
405 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
406 logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$new_item_marc->as_formatted)
407 if C4::Context->preference("CataloguingLog");
410 =head2 ModItemTransfer
414 ModItemTransfer($itenumber, $frombranch, $tobranch);
418 Marks an item as being transferred from one branch
423 sub ModItemTransfer {
424 my ( $itemnumber, $frombranch, $tobranch ) = @_;
426 my $dbh = C4::Context->dbh;
428 #new entry in branchtransfers....
429 my $sth = $dbh->prepare(
430 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
431 VALUES (?, ?, NOW(), ?)");
432 $sth->execute($itemnumber, $frombranch, $tobranch);
434 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
435 ModDateLastSeen($itemnumber);
439 =head2 ModDateLastSeen
443 ModDateLastSeen($itemnum);
447 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
448 C<$itemnum> is the item number
452 sub ModDateLastSeen {
453 my ($itemnumber) = @_;
455 my $today = C4::Dates->new();
456 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
463 DelItem($biblionumber, $itemnumber);
467 Exported function (core API) for deleting an item record in Koha.
472 my ( $dbh, $biblionumber, $itemnumber ) = @_;
474 # FIXME check the item has no current issues
476 _koha_delete_item( $dbh, $itemnumber );
478 # get the MARC record
479 my $record = GetMarcBiblio($biblionumber);
480 my $frameworkcode = GetFrameworkCode($biblionumber);
483 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
484 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
486 #search item field code
487 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
488 my @fields = $record->field($itemtag);
490 # delete the item specified
491 foreach my $field (@fields) {
492 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
493 $record->delete_field($field);
496 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
497 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
498 if C4::Context->preference("CataloguingLog");
501 =head2 CheckItemPreSave
505 my $item_ref = TransformMarcToKoha($marc, 'items');
507 my %errors = CheckItemPreSave($item_ref);
508 if (exists $errors{'duplicate_barcode'}) {
509 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
510 } elsif (exists $errors{'invalid_homebranch'}) {
511 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
512 } elsif (exists $errors{'invalid_holdingbranch'}) {
513 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
520 Given a hashref containing item fields, determine if it can be
521 inserted or updated in the database. Specifically, checks for
522 database integrity issues, and returns a hash containing any
523 of the following keys, if applicable.
527 =item duplicate_barcode
529 Barcode, if it duplicates one already found in the database.
531 =item invalid_homebranch
533 Home branch, if not defined in branches table.
535 =item invalid_holdingbranch
537 Holding branch, if not defined in branches table.
541 This function does NOT implement any policy-related checks,
542 e.g., whether current operator is allowed to save an
543 item that has a given branch code.
547 sub CheckItemPreSave {
548 my $item_ref = shift;
552 # check for duplicate barcode
553 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
554 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
555 if ($existing_itemnumber) {
556 if (!exists $item_ref->{'itemnumber'} # new item
557 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
558 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
563 # check for valid home branch
564 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
565 my $branch_name = GetBranchName($item_ref->{'homebranch'});
566 unless (defined $branch_name) {
567 # relies on fact that branches.branchname is a non-NULL column,
568 # so GetBranchName returns undef only if branch does not exist
569 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
573 # check for valid holding branch
574 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
575 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
576 unless (defined $branch_name) {
577 # relies on fact that branches.branchname is a non-NULL column,
578 # so GetBranchName returns undef only if branch does not exist
579 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
587 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
589 The following functions provide various ways of
590 getting an item record, a set of item records, or
591 lists of authorized values for certain item fields.
593 Some of the functions in this group are candidates
594 for refactoring -- for example, some of the code
595 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
596 has copy-and-paste work.
604 $itemstatushash = GetItemStatus($fwkcode);
608 Returns a list of valid values for the
609 C<items.notforloan> field.
611 NOTE: does B<not> return an individual item's
614 Can be MARC dependant.
616 But basically could be can be loan or not
617 Create a status selector with the following code
619 =head3 in PERL SCRIPT
623 my $itemstatushash = getitemstatus;
625 foreach my $thisstatus (keys %$itemstatushash) {
626 my %row =(value => $thisstatus,
627 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
629 push @itemstatusloop, \%row;
631 $template->param(statusloop=>\@itemstatusloop);
639 <select name="statusloop">
640 <option value="">Default</option>
641 <!-- TMPL_LOOP name="statusloop" -->
642 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
652 # returns a reference to a hash of references to status...
655 my $dbh = C4::Context->dbh;
657 $fwk = '' unless ($fwk);
658 my ( $tag, $subfield ) =
659 GetMarcFromKohaField( "items.notforloan", $fwk );
660 if ( $tag and $subfield ) {
663 "SELECT authorised_value
664 FROM marc_subfield_structure
670 $sth->execute( $tag, $subfield, $fwk );
671 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
674 "SELECT authorised_value,lib
675 FROM authorised_values
680 $authvalsth->execute($authorisedvaluecat);
681 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
682 $itemstatus{$authorisedvalue} = $lib;
698 $itemstatus{"1"} = "Not For Loan";
702 =head2 GetItemLocation
706 $itemlochash = GetItemLocation($fwk);
710 Returns a list of valid values for the
711 C<items.location> field.
713 NOTE: does B<not> return an individual item's
716 where fwk stands for an optional framework code.
717 Create a location selector with the following code
719 =head3 in PERL SCRIPT
723 my $itemlochash = getitemlocation;
725 foreach my $thisloc (keys %$itemlochash) {
726 my $selected = 1 if $thisbranch eq $branch;
727 my %row =(locval => $thisloc,
728 selected => $selected,
729 locname => $itemlochash->{$thisloc},
731 push @itemlocloop, \%row;
733 $template->param(itemlocationloop => \@itemlocloop);
741 <select name="location">
742 <option value="">Default</option>
743 <!-- TMPL_LOOP name="itemlocationloop" -->
744 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
752 sub GetItemLocation {
754 # returns a reference to a hash of references to location...
757 my $dbh = C4::Context->dbh;
759 $fwk = '' unless ($fwk);
760 my ( $tag, $subfield ) =
761 GetMarcFromKohaField( "items.location", $fwk );
762 if ( $tag and $subfield ) {
765 "SELECT authorised_value
766 FROM marc_subfield_structure
771 $sth->execute( $tag, $subfield, $fwk );
772 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
775 "SELECT authorised_value,lib
776 FROM authorised_values
780 $authvalsth->execute($authorisedvaluecat);
781 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
782 $itemlocation{$authorisedvalue} = $lib;
785 return \%itemlocation;
798 $itemlocation{"1"} = "Not For Loan";
799 return \%itemlocation;
806 $items = GetLostItems($where,$orderby);
810 This function get the items lost into C<$items>.
815 C<$where> is a hashref. it containts a field of the items table as key
816 and the value to match as value.
817 C<$orderby> is a field of the items table.
820 C<$items> is a reference to an array full of hasref which keys are items' table column.
822 =item usage in the perl script:
825 $where{barcode} = 0001548;
826 my $items = GetLostItems( \%where, "homebranch" );
827 $template->param(itemsloop => $items);
834 # Getting input args.
837 my $dbh = C4::Context->dbh;
842 WHERE itemlost IS NOT NULL
845 foreach my $key (keys %$where) {
846 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
848 $query .= " ORDER BY ".$orderby if defined $orderby;
850 my $sth = $dbh->prepare($query);
853 while ( my $row = $sth->fetchrow_hashref ){
859 =head2 GetItemsForInventory
863 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
867 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
869 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
870 It is ordered by callnumber,title.
872 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
873 the datelastseen can be used to specify that you want to see items not seen since a past date only.
874 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
878 sub GetItemsForInventory {
879 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
880 my $dbh = C4::Context->dbh;
883 $datelastseen=format_date_in_iso($datelastseen);
885 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
887 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
888 WHERE itemcallnumber>= ?
889 AND itemcallnumber <=?
890 AND (datelastseen< ? OR datelastseen IS NULL)";
891 $query.= " AND items.location=".$dbh->quote($location) if $location;
892 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
893 $query .= " ORDER BY itemcallnumber,title";
894 $sth = $dbh->prepare($query);
895 $sth->execute( $minlocation, $maxlocation, $datelastseen );
899 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
901 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
902 WHERE itemcallnumber>= ?
903 AND itemcallnumber <=?";
904 $query.= " AND items.location=".$dbh->quote($location) if $location;
905 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
906 $query .= " ORDER BY itemcallnumber,title";
907 $sth = $dbh->prepare($query);
908 $sth->execute( $minlocation, $maxlocation );
911 while ( my $row = $sth->fetchrow_hashref ) {
912 $offset-- if ($offset);
913 $row->{datelastseen}=format_date($row->{datelastseen});
914 if ( ( !$offset ) && $size ) {
925 $count = &GetItemsCount( $biblionumber);
929 This function return count of item with $biblionumber
934 my ( $biblionumber ) = @_;
935 my $dbh = C4::Context->dbh;
936 my $query = "SELECT count(*)
938 WHERE biblionumber=?";
939 my $sth = $dbh->prepare($query);
940 $sth->execute($biblionumber);
941 my $count = $sth->fetchrow;
946 =head2 GetItemInfosOf
950 GetItemInfosOf(@itemnumbers);
957 my @itemnumbers = @_;
962 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
964 return get_infos_of( $query, 'itemnumber' );
967 =head2 GetItemsByBiblioitemnumber
971 GetItemsByBiblioitemnumber($biblioitemnumber);
975 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
976 Called by C<C4::XISBN>
980 sub GetItemsByBiblioitemnumber {
981 my ( $bibitem ) = @_;
982 my $dbh = C4::Context->dbh;
983 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
984 # Get all items attached to a biblioitem
987 $sth->execute($bibitem) || die $sth->errstr;
988 while ( my $data = $sth->fetchrow_hashref ) {
989 # Foreach item, get circulation information
990 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
992 AND returndate is NULL
993 AND issues.borrowernumber = borrowers.borrowernumber"
995 $sth2->execute( $data->{'itemnumber'} );
996 if ( my $data2 = $sth2->fetchrow_hashref ) {
997 # if item is out, set the due date and who it is out too
998 $data->{'date_due'} = $data2->{'date_due'};
999 $data->{'cardnumber'} = $data2->{'cardnumber'};
1000 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1003 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1004 $data->{'date_due'} = '';
1007 # Find the last 3 people who borrowed this item.
1008 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1009 AND issues.borrowernumber = borrowers.borrowernumber
1010 AND returndate is not NULL
1011 ORDER BY returndate desc,timestamp desc LIMIT 3";
1012 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1013 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1015 while ( my $data2 = $sth2->fetchrow_hashref ) {
1016 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1017 $data->{"card$i2"} = $data2->{'cardnumber'};
1018 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1022 push(@results,$data);
1032 @results = GetItemsInfo($biblionumber, $type);
1036 Returns information about books with the given biblionumber.
1038 C<$type> may be either C<intra> or anything else. If it is not set to
1039 C<intra>, then the search will exclude lost, very overdue, and
1042 C<GetItemsInfo> returns a list of references-to-hash. Each element
1043 contains a number of keys. Most of them are table items from the
1044 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1045 Koha database. Other keys include:
1049 =item C<$data-E<gt>{branchname}>
1051 The name (not the code) of the branch to which the book belongs.
1053 =item C<$data-E<gt>{datelastseen}>
1055 This is simply C<items.datelastseen>, except that while the date is
1056 stored in YYYY-MM-DD format in the database, here it is converted to
1057 DD/MM/YYYY format. A NULL date is returned as C<//>.
1059 =item C<$data-E<gt>{datedue}>
1061 =item C<$data-E<gt>{class}>
1063 This is the concatenation of C<biblioitems.classification>, the book's
1064 Dewey code, and C<biblioitems.subclass>.
1066 =item C<$data-E<gt>{ocount}>
1068 I think this is the number of copies of the book available.
1070 =item C<$data-E<gt>{order}>
1072 If this is set, it is set to C<One Order>.
1079 my ( $biblionumber, $type ) = @_;
1080 my $dbh = C4::Context->dbh;
1081 my $query = "SELECT *,items.notforloan as itemnotforloan
1083 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1084 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1085 $query .= (C4::Context->preference('item-level_itypes')) ?
1086 " LEFT JOIN itemtypes on items.itype = itemtypes.itemtype "
1087 : " LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype ";
1088 $query .= "WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1089 my $sth = $dbh->prepare($query);
1090 $sth->execute($biblionumber);
1093 my ( $date_due, $count_reserves, $serial );
1095 my $isth = $dbh->prepare(
1096 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1097 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1098 WHERE itemnumber = ?
1099 AND returndate IS NULL"
1101 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serial where itemnumber=?");
1102 while ( my $data = $sth->fetchrow_hashref ) {
1104 $isth->execute( $data->{'itemnumber'} );
1105 if ( my $idata = $isth->fetchrow_hashref ) {
1106 $data->{borrowernumber} = $idata->{borrowernumber};
1107 $data->{cardnumber} = $idata->{cardnumber};
1108 $data->{surname} = $idata->{surname};
1109 $data->{firstname} = $idata->{firstname};
1110 $datedue = $idata->{'date_due'};
1111 if (C4::Context->preference("IndependantBranches")){
1112 my $userenv = C4::Context->userenv;
1113 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1114 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1118 if ( $data->{'serial'}) {
1119 $ssth->execute($data->{'itemnumber'}) ;
1120 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1123 if ( $datedue eq '' ) {
1124 my ( $restype, $reserves ) =
1125 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1127 $count_reserves = $restype;
1132 #get branch information.....
1133 my $bsth = $dbh->prepare(
1134 "SELECT * FROM branches WHERE branchcode = ?
1137 $bsth->execute( $data->{'holdingbranch'} );
1138 if ( my $bdata = $bsth->fetchrow_hashref ) {
1139 $data->{'branchname'} = $bdata->{'branchname'};
1141 $data->{'datedue'} = $datedue;
1142 $data->{'count_reserves'} = $count_reserves;
1144 # get notforloan complete status if applicable
1145 my $sthnflstatus = $dbh->prepare(
1146 'SELECT authorised_value
1147 FROM marc_subfield_structure
1148 WHERE kohafield="items.notforloan"
1152 $sthnflstatus->execute;
1153 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1154 if ($authorised_valuecode) {
1155 $sthnflstatus = $dbh->prepare(
1156 "SELECT lib FROM authorised_values
1158 AND authorised_value=?"
1160 $sthnflstatus->execute( $authorised_valuecode,
1161 $data->{itemnotforloan} );
1162 my ($lib) = $sthnflstatus->fetchrow;
1163 $data->{notforloan} = $lib;
1166 # my stack procedures
1167 my $stackstatus = $dbh->prepare(
1168 'SELECT authorised_value
1169 FROM marc_subfield_structure
1170 WHERE kohafield="items.stack"
1173 $stackstatus->execute;
1175 ($authorised_valuecode) = $stackstatus->fetchrow;
1176 if ($authorised_valuecode) {
1177 $stackstatus = $dbh->prepare(
1179 FROM authorised_values
1181 AND authorised_value=?
1184 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1185 my ($lib) = $stackstatus->fetchrow;
1186 $data->{stack} = $lib;
1188 # Find the last 3 people who borrowed this item.
1189 my $sth2 = $dbh->prepare("SELECT * FROM issues,borrowers
1190 WHERE itemnumber = ?
1191 AND issues.borrowernumber = borrowers.borrowernumber
1192 AND returndate IS NOT NULL LIMIT 3");
1193 $sth2->execute($data->{'itemnumber'});
1195 while (my $data2 = $sth2->fetchrow_hashref()) {
1196 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1197 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1198 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1202 $results[$i] = $data;
1207 return( sort { $b->{'publisheddate'} cmp $a->{'publisheddate'} } @results );
1213 =head2 get_itemnumbers_of
1217 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1221 Given a list of biblionumbers, return the list of corresponding itemnumbers
1222 for each biblionumber.
1224 Return a reference on a hash where keys are biblionumbers and values are
1225 references on array of itemnumbers.
1229 sub get_itemnumbers_of {
1230 my @biblionumbers = @_;
1232 my $dbh = C4::Context->dbh;
1238 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1240 my $sth = $dbh->prepare($query);
1241 $sth->execute(@biblionumbers);
1245 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1246 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1249 return \%itemnumbers_of;
1252 =head2 GetItemnumberFromBarcode
1256 $result = GetItemnumberFromBarcode($barcode);
1262 sub GetItemnumberFromBarcode {
1264 my $dbh = C4::Context->dbh;
1267 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1268 $rq->execute($barcode);
1269 my ($result) = $rq->fetchrow;
1273 =head1 LIMITED USE FUNCTIONS
1275 The following functions, while part of the public API,
1276 are not exported. This is generally because they are
1277 meant to be used by only one script for a specific
1278 purpose, and should not be used in any other context
1279 without careful thought.
1287 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1291 Returns MARC::Record of the item passed in parameter.
1292 This function is meant for use only in C<cataloguing/additem.pl>,
1293 where it is needed to support that script's MARC-like
1299 my ( $biblionumber, $itemnumber ) = @_;
1301 # GetMarcItem has been revised so that it does the following:
1302 # 1. Gets the item information from the items table.
1303 # 2. Converts it to a MARC field for storage in the bib record.
1305 # The previous behavior was:
1306 # 1. Get the bib record.
1307 # 2. Return the MARC tag corresponding to the item record.
1309 # The difference is that one treats the items row as authoritative,
1310 # while the other treats the MARC representation as authoritative
1311 # under certain circumstances.
1313 my $itemrecord = GetItem($itemnumber);
1315 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1316 # Also, don't emit a subfield if the underlying field is blank.
1317 my $mungeditem = { map { $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : () } keys %{ $itemrecord } };
1319 my $itemmarc = TransformKohaToMarc($mungeditem);
1324 =head1 PRIVATE FUNCTIONS AND VARIABLES
1326 The following functions are not meant to be called
1327 directly, but are documented in order to explain
1328 the inner workings of C<C4::Items>.
1332 =head2 %derived_columns
1334 This hash keeps track of item columns that
1335 are strictly derived from other columns in
1336 the item record and are not meant to be set
1339 Each key in the hash should be the name of a
1340 column (as named by TransformMarcToKoha). Each
1341 value should be hashref whose keys are the
1342 columns on which the derived column depends. The
1343 hashref should also contain a 'BUILDER' key
1344 that is a reference to a sub that calculates
1349 my %derived_columns = (
1350 'items.cn_sort' => {
1351 'itemcallnumber' => 1,
1352 'items.cn_source' => 1,
1353 'BUILDER' => \&_calc_items_cn_sort,
1357 =head2 _set_derived_columns_for_add
1361 _set_derived_column_for_add($item);
1365 Given an item hash representing a new item to be added,
1366 calculate any derived columns. Currently the only
1367 such column is C<items.cn_sort>.
1371 sub _set_derived_columns_for_add {
1374 foreach my $column (keys %derived_columns) {
1375 my $builder = $derived_columns{$column}->{'BUILDER'};
1376 my $source_values = {};
1377 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1378 next if $source_column eq 'BUILDER';
1379 $source_values->{$source_column} = $item->{$source_column};
1381 $builder->($item, $source_values);
1385 =head2 _set_derived_columns_for_mod
1389 _set_derived_column_for_mod($item);
1393 Given an item hash representing a new item to be modified.
1394 calculate any derived columns. Currently the only
1395 such column is C<items.cn_sort>.
1397 This routine differs from C<_set_derived_columns_for_add>
1398 in that it needs to handle partial item records. In other
1399 words, the caller of C<ModItem> may have supplied only one
1400 or two columns to be changed, so this function needs to
1401 determine whether any of the columns to be changed affect
1402 any of the derived columns. Also, if a derived column
1403 depends on more than one column, but the caller is not
1404 changing all of then, this routine retrieves the unchanged
1405 values from the database in order to ensure a correct
1410 sub _set_derived_columns_for_mod {
1413 foreach my $column (keys %derived_columns) {
1414 my $builder = $derived_columns{$column}->{'BUILDER'};
1415 my $source_values = {};
1416 my %missing_sources = ();
1417 my $must_recalc = 0;
1418 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1419 next if $source_column eq 'BUILDER';
1420 if (exists $item->{$source_column}) {
1422 $source_values->{$source_column} = $item->{$source_column};
1424 $missing_sources{$source_column} = 1;
1428 foreach my $source_column (keys %missing_sources) {
1429 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1431 $builder->($item, $source_values);
1436 =head2 _do_column_fixes_for_mod
1440 _do_column_fixes_for_mod($item);
1444 Given an item hashref containing one or more
1445 columns to modify, fix up certain values.
1446 Specifically, set to 0 any passed value
1447 of C<notforloan>, C<damaged>, C<itemlost>, or
1448 C<wthdrawn> that is either undefined or
1449 contains the empty string.
1453 sub _do_column_fixes_for_mod {
1456 if (exists $item->{'notforloan'} and
1457 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1458 $item->{'notforloan'} = 0;
1460 if (exists $item->{'damaged'} and
1461 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1462 $item->{'damaged'} = 0;
1464 if (exists $item->{'itemlost'} and
1465 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1466 $item->{'itemlost'} = 0;
1468 if (exists $item->{'wthdrawn'} and
1469 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1470 $item->{'wthdrawn'} = 0;
1474 =head2 _get_single_item_column
1478 _get_single_item_column($column, $itemnumber);
1482 Retrieves the value of a single column from an C<items>
1483 row specified by C<$itemnumber>.
1487 sub _get_single_item_column {
1489 my $itemnumber = shift;
1491 my $dbh = C4::Context->dbh;
1492 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1493 $sth->execute($itemnumber);
1494 my ($value) = $sth->fetchrow();
1498 =head2 _calc_items_cn_sort
1502 _calc_items_cn_sort($item, $source_values);
1506 Helper routine to calculate C<items.cn_sort>.
1510 sub _calc_items_cn_sort {
1512 my $source_values = shift;
1514 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1517 =head2 _set_defaults_for_add
1521 _set_defaults_for_add($item_hash);
1525 Given an item hash representing an item to be added, set
1526 correct default values for columns whose default value
1527 is not handled by the DBMS. This includes the following
1534 C<items.dateaccessioned>
1556 sub _set_defaults_for_add {
1559 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
1560 if (!(exists $item->{'dateaccessioned'}) ||
1561 ($item->{'dateaccessioned'} eq '')) {
1562 # FIXME add check for invalid date
1563 my $today = C4::Dates->new();
1564 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
1567 # various item status fields cannot be null
1568 $item->{'notforloan'} = 0 unless exists $item->{'notforloan'} and defined $item->{'notforloan'} and $item->{'notforloan'} ne '';
1569 $item->{'damaged'} = 0 unless exists $item->{'damaged'} and defined $item->{'damaged'} and $item->{'damaged'} ne '';
1570 $item->{'itemlost'} = 0 unless exists $item->{'itemlost'} and defined $item->{'itemlost'} and $item->{'itemlost'} ne '';
1571 $item->{'wthdrawn'} = 0 unless exists $item->{'wthdrawn'} and defined $item->{'wthdrawn'} and $item->{'wthdrawn'} ne '';
1574 =head2 _koha_new_item
1578 my ($itemnumber,$error) = _koha_new_item( $dbh, $item, $barcode );
1582 Perform the actual insert into the C<items> table.
1586 sub _koha_new_item {
1587 my ( $dbh, $item, $barcode ) = @_;
1593 "INSERT INTO items SET
1595 biblioitemnumber = ?,
1597 dateaccessioned = ?,
1601 replacementprice = ?,
1602 replacementpricedate = NOW(),
1603 datelastborrowed = ?,
1604 datelastseen = NOW(),
1627 my $sth = $dbh->prepare($query);
1629 $item->{'biblionumber'},
1630 $item->{'biblioitemnumber'},
1632 $item->{'dateaccessioned'},
1633 $item->{'booksellerid'},
1634 $item->{'homebranch'},
1636 $item->{'replacementprice'},
1637 $item->{datelastborrowed},
1639 $item->{'notforloan'},
1641 $item->{'itemlost'},
1642 $item->{'wthdrawn'},
1643 $item->{'itemcallnumber'},
1644 $item->{'restricted'},
1645 $item->{'itemnotes'},
1646 $item->{'holdingbranch'},
1648 $item->{'location'},
1651 $item->{'renewals'},
1652 $item->{'reserves'},
1653 $item->{'items.cn_source'},
1654 $item->{'items.cn_sort'},
1657 $item->{'materials'},
1660 my $itemnumber = $dbh->{'mysql_insertid'};
1661 if ( defined $sth->errstr ) {
1662 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1665 return ( $itemnumber, $error );
1668 =head2 _koha_modify_item
1672 my ($itemnumber,$error) =_koha_modify_item( $dbh, $item, $op );
1676 Perform the actual update of the C<items> row. Note that this
1677 routine accepts a hashref specifying the columns to update.
1681 sub _koha_modify_item {
1682 my ( $dbh, $item ) = @_;
1685 my $query = "UPDATE items SET ";
1687 for my $key ( keys %$item ) {
1689 push @bind, $item->{$key};
1692 $query .= " WHERE itemnumber=?";
1693 push @bind, $item->{'itemnumber'};
1694 my $sth = $dbh->prepare($query);
1695 $sth->execute(@bind);
1696 if ( $dbh->errstr ) {
1697 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1701 return ($item->{'itemnumber'},$error);
1704 =head2 _koha_delete_item
1708 _koha_delete_item( $dbh, $itemnum );
1712 Internal function to delete an item record from the koha tables
1716 sub _koha_delete_item {
1717 my ( $dbh, $itemnum ) = @_;
1719 # save the deleted item to deleteditems table
1720 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1721 $sth->execute($itemnum);
1722 my $data = $sth->fetchrow_hashref();
1724 my $query = "INSERT INTO deleteditems SET ";
1726 foreach my $key ( keys %$data ) {
1727 $query .= "$key = ?,";
1728 push( @bind, $data->{$key} );
1731 $sth = $dbh->prepare($query);
1732 $sth->execute(@bind);
1735 # delete from items table
1736 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1737 $sth->execute($itemnum);
1742 =head2 _marc_from_item_hash
1746 my $item_marc = _marc_from_item_hash($item, $frameworkcode);
1750 Given an item hash representing a complete item record,
1751 create a C<MARC::Record> object containing an embedded
1752 tag representing that item.
1756 sub _marc_from_item_hash {
1758 my $frameworkcode = shift;
1760 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1761 # Also, don't emit a subfield if the underlying field is blank.
1762 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1763 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1764 : () } keys %{ $item } };
1766 my $item_marc = MARC::Record->new();
1767 foreach my $item_field (keys %{ $mungeditem }) {
1768 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
1769 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1770 if (my $field = $item_marc->field($tag)) {
1771 $field->add_subfields($subfield => $mungeditem->{$item_field});
1773 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field});
1780 =head2 _add_item_field_to_biblio
1784 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
1788 Adds the fields from a MARC record containing the
1789 representation of a Koha item record to the MARC
1790 biblio record. The input C<$item_marc> record
1791 is expect to contain just one field, the embedded
1792 item information field.
1796 sub _add_item_field_to_biblio {
1797 my ($item_marc, $biblionumber, $frameworkcode) = @_;
1799 my $biblio_marc = GetMarcBiblio($biblionumber);
1801 foreach my $field ($item_marc->fields()) {
1802 $biblio_marc->append_fields($field);
1805 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
1808 =head2 _replace_item_field_in_biblio
1812 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
1816 Given a MARC::Record C<$item_marc> containing one tag with the MARC
1817 representation of the item, examine the biblio MARC
1818 for the corresponding tag for that item and
1819 replace it with the tag from C<$item_marc>.
1823 sub _replace_item_field_in_biblio {
1824 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
1825 my $dbh = C4::Context->dbh;
1827 # get complete MARC record & replace the item field by the new one
1828 my $completeRecord = GetMarcBiblio($biblionumber);
1829 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
1830 my $itemField = $ItemRecord->field($itemtag);
1831 my @items = $completeRecord->field($itemtag);
1834 if ($_->subfield($itemsubfield) eq $itemnumber) {
1835 $_->replace_with($itemField);
1841 # If we haven't found the matching field,
1842 # just add it. However, this means that
1843 # there is likely a bug.
1844 $completeRecord->append_fields($itemField);
1848 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
1851 =head2 _repack_item_errors
1853 Add an error message hash generated by C<CheckItemPreSave>
1854 to a list of errors.
1858 sub _repack_item_errors {
1859 my $item_sequence_num = shift;
1860 my $item_ref = shift;
1861 my $error_ref = shift;
1863 my @repacked_errors = ();
1865 foreach my $error_code (sort keys %{ $error_ref }) {
1866 my $repacked_error = {};
1867 $repacked_error->{'item_sequence'} = $item_sequence_num;
1868 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
1869 $repacked_error->{'error_code'} = $error_code;
1870 $repacked_error->{'error_information'} = $error_ref->{$error_code};
1871 push @repacked_errors, $repacked_error;
1874 return @repacked_errors;