3 # Copyright 2007 LibLime, Inc.
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #use warnings; FIXME - Bug 2505
27 use C4::Dates qw/format_date format_date_in_iso/;
36 use vars qw($VERSION @ISA @EXPORT);
42 @ISA = qw( Exporter );
65 GetItemsByBiblioitemnumber
68 GetItemnumberFromBarcode
69 GetBarcodeFromItemnumber
80 C4::Items - item management functions
84 This module contains an API for manipulating item
85 records in Koha, and is used by cataloguing, circulation,
86 acquisitions, and serials management.
88 A Koha item record is stored in two places: the
89 items table and embedded in a MARC tag in the XML
90 version of the associated bib record in C<biblioitems.marcxml>.
91 This is done to allow the item information to be readily
92 indexed (e.g., by Zebra), but means that each item
93 modification transaction must keep the items table
94 and the MARC XML in sync at all times.
96 Consequently, all code that creates, modifies, or deletes
97 item records B<must> use an appropriate function from
98 C<C4::Items>. If no existing function is suitable, it is
99 better to add one to C<C4::Items> than to use add
100 one-off SQL statements to add or modify items.
102 The items table will be considered authoritative. In other
103 words, if there is ever a discrepancy between the items
104 table and the MARC XML, the items table should be considered
107 =head1 HISTORICAL NOTE
109 Most of the functions in C<C4::Items> were originally in
110 the C<C4::Biblio> module.
112 =head1 CORE EXPORTED FUNCTIONS
114 The following functions are meant for use by users
121 $item = GetItem($itemnumber,$barcode,$serial);
123 Return item information, for a given itemnumber or barcode.
124 The return value is a hashref mapping item column
125 names to values. If C<$serial> is true, include serial publication data.
130 my ($itemnumber,$barcode, $serial) = @_;
131 my $dbh = C4::Context->dbh;
134 my $sth = $dbh->prepare("
136 WHERE itemnumber = ?");
137 $sth->execute($itemnumber);
138 $data = $sth->fetchrow_hashref;
140 my $sth = $dbh->prepare("
144 $sth->execute($barcode);
145 $data = $sth->fetchrow_hashref;
148 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
149 $ssth->execute($data->{'itemnumber'}) ;
150 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
152 #if we don't have an items.itype, use biblioitems.itemtype.
153 if( ! $data->{'itype'} ) {
154 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
155 $sth->execute($data->{'biblionumber'});
156 ($data->{'itype'}) = $sth->fetchrow_array;
163 CartToShelf($itemnumber);
165 Set the current shelving location of the item record
166 to its stored permanent shelving location. This is
167 primarily used to indicate when an item whose current
168 location is a special processing ('PROC') or shelving cart
169 ('CART') location is back in the stacks.
174 my ( $itemnumber ) = @_;
176 unless ( $itemnumber ) {
177 croak "FAILED CartToShelf() - no itemnumber supplied";
180 my $item = GetItem($itemnumber);
181 $item->{location} = $item->{permanent_location};
182 ModItem($item, undef, $itemnumber);
185 =head2 AddItemFromMarc
187 my ($biblionumber, $biblioitemnumber, $itemnumber)
188 = AddItemFromMarc($source_item_marc, $biblionumber);
190 Given a MARC::Record object containing an embedded item
191 record and a biblionumber, create a new item record.
195 sub AddItemFromMarc {
196 my ( $source_item_marc, $biblionumber ) = @_;
197 my $dbh = C4::Context->dbh;
199 # parse item hash from MARC
200 my $frameworkcode = GetFrameworkCode( $biblionumber );
201 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
203 my $localitemmarc=MARC::Record->new;
204 $localitemmarc->append_fields($source_item_marc->field($itemtag));
205 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
206 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
207 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
212 my ($biblionumber, $biblioitemnumber, $itemnumber)
213 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
215 Given a hash containing item column names as keys,
216 create a new Koha item record.
218 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
219 do not need to be supplied for general use; they exist
220 simply to allow them to be picked up from AddItemFromMarc.
222 The final optional parameter, C<$unlinked_item_subfields>, contains
223 an arrayref containing subfields present in the original MARC
224 representation of the item (e.g., from the item editor) that are
225 not mapped to C<items> columns directly but should instead
226 be stored in C<items.more_subfields_xml> and included in
227 the biblio items tag for display and indexing.
233 my $biblionumber = shift;
235 my $dbh = @_ ? shift : C4::Context->dbh;
236 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
237 my $unlinked_item_subfields;
239 $unlinked_item_subfields = shift
242 # needs old biblionumber and biblioitemnumber
243 $item->{'biblionumber'} = $biblionumber;
244 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
245 $sth->execute( $item->{'biblionumber'} );
246 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
248 _set_defaults_for_add($item);
249 _set_derived_columns_for_add($item);
250 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
251 # FIXME - checks here
252 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
253 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
254 $itype_sth->execute( $item->{'biblionumber'} );
255 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
258 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
259 $item->{'itemnumber'} = $itemnumber;
261 # create MARC tag representing item and add to bib
262 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
263 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
265 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
267 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
270 =head2 AddItemBatchFromMarc
272 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
273 $biblionumber, $biblioitemnumber, $frameworkcode);
275 Efficiently create item records from a MARC biblio record with
276 embedded item fields. This routine is suitable for batch jobs.
278 This API assumes that the bib record has already been
279 saved to the C<biblio> and C<biblioitems> tables. It does
280 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
281 are populated, but it will do so via a call to ModBibiloMarc.
283 The goal of this API is to have a similar effect to using AddBiblio
284 and AddItems in succession, but without inefficient repeated
285 parsing of the MARC XML bib record.
287 This function returns an arrayref of new itemsnumbers and an arrayref of item
288 errors encountered during the processing. Each entry in the errors
289 list is a hashref containing the following keys:
295 Sequence number of original item tag in the MARC record.
299 Item barcode, provide to assist in the construction of
300 useful error messages.
302 =item error_condition
304 Code representing the error condition. Can be 'duplicate_barcode',
305 'invalid_homebranch', or 'invalid_holdingbranch'.
307 =item error_information
309 Additional information appropriate to the error condition.
315 sub AddItemBatchFromMarc {
316 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
318 my @itemnumbers = ();
320 my $dbh = C4::Context->dbh;
322 # loop through the item tags and start creating items
323 my @bad_item_fields = ();
324 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
325 my $item_sequence_num = 0;
326 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
327 $item_sequence_num++;
328 # we take the item field and stick it into a new
329 # MARC record -- this is required so far because (FIXME)
330 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
331 # and there is no TransformMarcFieldToKoha
332 my $temp_item_marc = MARC::Record->new();
333 $temp_item_marc->append_fields($item_field);
335 # add biblionumber and biblioitemnumber
336 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
337 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
338 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
339 $item->{'biblionumber'} = $biblionumber;
340 $item->{'biblioitemnumber'} = $biblioitemnumber;
342 # check for duplicate barcode
343 my %item_errors = CheckItemPreSave($item);
345 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
346 push @bad_item_fields, $item_field;
350 _set_defaults_for_add($item);
351 _set_derived_columns_for_add($item);
352 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
353 warn $error if $error;
354 push @itemnumbers, $itemnumber; # FIXME not checking error
355 $item->{'itemnumber'} = $itemnumber;
357 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
359 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
360 $item_field->replace_with($new_item_marc->field($itemtag));
363 # remove any MARC item fields for rejected items
364 foreach my $item_field (@bad_item_fields) {
365 $record->delete_field($item_field);
368 # update the MARC biblio
369 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
371 return (\@itemnumbers, \@errors);
374 =head2 ModItemFromMarc
376 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
378 This function updates an item record based on a supplied
379 C<MARC::Record> object containing an embedded item field.
380 This API is meant for the use of C<additem.pl>; for
381 other purposes, C<ModItem> should be used.
383 This function uses the hash %default_values_for_mod_from_marc,
384 which contains default values for item fields to
385 apply when modifying an item. This is needed beccause
386 if an item field's value is cleared, TransformMarcToKoha
387 does not include the column in the
388 hash that's passed to ModItem, which without
389 use of this hash makes it impossible to clear
390 an item field's value. See bug 2466.
392 Note that only columns that can be directly
393 changed from the cataloging and serials
394 item editors are included in this hash.
398 my %default_values_for_mod_from_marc = (
400 booksellerid => undef,
402 'items.cn_source' => undef,
405 dateaccessioned => undef,
407 holdingbranch => undef,
409 itemcallnumber => undef,
418 replacementprice => undef,
419 replacementpricedate => undef,
422 stocknumber => undef,
427 sub ModItemFromMarc {
428 my $item_marc = shift;
429 my $biblionumber = shift;
430 my $itemnumber = shift;
432 my $dbh = C4::Context->dbh;
433 my $frameworkcode = GetFrameworkCode( $biblionumber );
434 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
436 my $localitemmarc=MARC::Record->new;
437 $localitemmarc->append_fields($item_marc->field($itemtag));
438 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items');
439 foreach my $item_field (keys %default_values_for_mod_from_marc) {
440 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
442 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
444 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
449 ModItem({ column => $newvalue }, $biblionumber,
450 $itemnumber[, $original_item_marc]);
452 Change one or more columns in an item record and update
453 the MARC representation of the item.
455 The first argument is a hashref mapping from item column
456 names to the new values. The second and third arguments
457 are the biblionumber and itemnumber, respectively.
459 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
460 an arrayref containing subfields present in the original MARC
461 representation of the item (e.g., from the item editor) that are
462 not mapped to C<items> columns directly but should instead
463 be stored in C<items.more_subfields_xml> and included in
464 the biblio items tag for display and indexing.
466 If one of the changed columns is used to calculate
467 the derived value of a column such as C<items.cn_sort>,
468 this routine will perform the necessary calculation
475 my $biblionumber = shift;
476 my $itemnumber = shift;
478 # if $biblionumber is undefined, get it from the current item
479 unless (defined $biblionumber) {
480 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
483 my $dbh = @_ ? shift : C4::Context->dbh;
484 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
486 my $unlinked_item_subfields;
488 $unlinked_item_subfields = shift;
489 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
492 $item->{'itemnumber'} = $itemnumber or return undef;
493 _set_derived_columns_for_mod($item);
494 _do_column_fixes_for_mod($item);
497 # attempt to change itemnumber
498 # attempt to change biblionumber (if we want
499 # an API to relink an item to a different bib,
500 # it should be a separate function)
503 _koha_modify_item($item);
505 # update biblio MARC XML
506 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
508 unless (defined $unlinked_item_subfields) {
509 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
511 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
512 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
514 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
515 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
516 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
519 =head2 ModItemTransfer
521 ModItemTransfer($itenumber, $frombranch, $tobranch);
523 Marks an item as being transferred from one branch
528 sub ModItemTransfer {
529 my ( $itemnumber, $frombranch, $tobranch ) = @_;
531 my $dbh = C4::Context->dbh;
533 #new entry in branchtransfers....
534 my $sth = $dbh->prepare(
535 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
536 VALUES (?, ?, NOW(), ?)");
537 $sth->execute($itemnumber, $frombranch, $tobranch);
539 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
540 ModDateLastSeen($itemnumber);
544 =head2 ModDateLastSeen
546 ModDateLastSeen($itemnum);
548 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
549 C<$itemnum> is the item number
553 sub ModDateLastSeen {
554 my ($itemnumber) = @_;
556 my $today = C4::Dates->new();
557 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
562 DelItem($dbh, $biblionumber, $itemnumber);
564 Exported function (core API) for deleting an item record in Koha.
569 my ( $dbh, $biblionumber, $itemnumber ) = @_;
571 # FIXME check the item has no current issues
573 _koha_delete_item( $dbh, $itemnumber );
575 # get the MARC record
576 my $record = GetMarcBiblio($biblionumber);
577 my $frameworkcode = GetFrameworkCode($biblionumber);
580 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
581 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
583 #search item field code
584 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
585 my @fields = $record->field($itemtag);
587 # delete the item specified
588 foreach my $field (@fields) {
589 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
590 $record->delete_field($field);
593 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
594 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
597 =head2 CheckItemPreSave
599 my $item_ref = TransformMarcToKoha($marc, 'items');
601 my %errors = CheckItemPreSave($item_ref);
602 if (exists $errors{'duplicate_barcode'}) {
603 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
604 } elsif (exists $errors{'invalid_homebranch'}) {
605 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
606 } elsif (exists $errors{'invalid_holdingbranch'}) {
607 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
612 Given a hashref containing item fields, determine if it can be
613 inserted or updated in the database. Specifically, checks for
614 database integrity issues, and returns a hash containing any
615 of the following keys, if applicable.
619 =item duplicate_barcode
621 Barcode, if it duplicates one already found in the database.
623 =item invalid_homebranch
625 Home branch, if not defined in branches table.
627 =item invalid_holdingbranch
629 Holding branch, if not defined in branches table.
633 This function does NOT implement any policy-related checks,
634 e.g., whether current operator is allowed to save an
635 item that has a given branch code.
639 sub CheckItemPreSave {
640 my $item_ref = shift;
644 # check for duplicate barcode
645 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
646 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
647 if ($existing_itemnumber) {
648 if (!exists $item_ref->{'itemnumber'} # new item
649 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
650 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
655 # check for valid home branch
656 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
657 my $branch_name = GetBranchName($item_ref->{'homebranch'});
658 unless (defined $branch_name) {
659 # relies on fact that branches.branchname is a non-NULL column,
660 # so GetBranchName returns undef only if branch does not exist
661 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
665 # check for valid holding branch
666 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
667 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
668 unless (defined $branch_name) {
669 # relies on fact that branches.branchname is a non-NULL column,
670 # so GetBranchName returns undef only if branch does not exist
671 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
679 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
681 The following functions provide various ways of
682 getting an item record, a set of item records, or
683 lists of authorized values for certain item fields.
685 Some of the functions in this group are candidates
686 for refactoring -- for example, some of the code
687 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
688 has copy-and-paste work.
694 $itemstatushash = GetItemStatus($fwkcode);
696 Returns a list of valid values for the
697 C<items.notforloan> field.
699 NOTE: does B<not> return an individual item's
702 Can be MARC dependant.
704 But basically could be can be loan or not
705 Create a status selector with the following code
707 =head3 in PERL SCRIPT
709 my $itemstatushash = getitemstatus;
711 foreach my $thisstatus (keys %$itemstatushash) {
712 my %row =(value => $thisstatus,
713 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
715 push @itemstatusloop, \%row;
717 $template->param(statusloop=>\@itemstatusloop);
721 <select name="statusloop">
722 <option value="">Default</option>
723 <!-- TMPL_LOOP name="statusloop" -->
724 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
732 # returns a reference to a hash of references to status...
735 my $dbh = C4::Context->dbh;
737 $fwk = '' unless ($fwk);
738 my ( $tag, $subfield ) =
739 GetMarcFromKohaField( "items.notforloan", $fwk );
740 if ( $tag and $subfield ) {
743 "SELECT authorised_value
744 FROM marc_subfield_structure
750 $sth->execute( $tag, $subfield, $fwk );
751 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
754 "SELECT authorised_value,lib
755 FROM authorised_values
760 $authvalsth->execute($authorisedvaluecat);
761 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
762 $itemstatus{$authorisedvalue} = $lib;
776 $itemstatus{"1"} = "Not For Loan";
780 =head2 GetItemLocation
782 $itemlochash = GetItemLocation($fwk);
784 Returns a list of valid values for the
785 C<items.location> field.
787 NOTE: does B<not> return an individual item's
790 where fwk stands for an optional framework code.
791 Create a location selector with the following code
793 =head3 in PERL SCRIPT
795 my $itemlochash = getitemlocation;
797 foreach my $thisloc (keys %$itemlochash) {
798 my $selected = 1 if $thisbranch eq $branch;
799 my %row =(locval => $thisloc,
800 selected => $selected,
801 locname => $itemlochash->{$thisloc},
803 push @itemlocloop, \%row;
805 $template->param(itemlocationloop => \@itemlocloop);
809 <select name="location">
810 <option value="">Default</option>
811 <!-- TMPL_LOOP name="itemlocationloop" -->
812 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
818 sub GetItemLocation {
820 # returns a reference to a hash of references to location...
823 my $dbh = C4::Context->dbh;
825 $fwk = '' unless ($fwk);
826 my ( $tag, $subfield ) =
827 GetMarcFromKohaField( "items.location", $fwk );
828 if ( $tag and $subfield ) {
831 "SELECT authorised_value
832 FROM marc_subfield_structure
837 $sth->execute( $tag, $subfield, $fwk );
838 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
841 "SELECT authorised_value,lib
842 FROM authorised_values
846 $authvalsth->execute($authorisedvaluecat);
847 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
848 $itemlocation{$authorisedvalue} = $lib;
850 return \%itemlocation;
862 $itemlocation{"1"} = "Not For Loan";
863 return \%itemlocation;
868 $items = GetLostItems( $where, $orderby );
870 This function gets a list of lost items.
876 C<$where> is a hashref. it containts a field of the items table as key
877 and the value to match as value. For example:
879 { barcode => 'abc123',
880 homebranch => 'CPL', }
882 C<$orderby> is a field of the items table by which the resultset
887 C<$items> is a reference to an array full of hashrefs with columns
888 from the "items" table as keys.
890 =item usage in the perl script:
892 my $where = { barcode => '0001548' };
893 my $items = GetLostItems( $where, "homebranch" );
894 $template->param( itemsloop => $items );
901 # Getting input args.
904 my $dbh = C4::Context->dbh;
909 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
910 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
911 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
913 authorised_values.category = 'LOST'
914 AND itemlost IS NOT NULL
917 my @query_parameters;
918 foreach my $key (keys %$where) {
919 $query .= " AND $key LIKE ?";
920 push @query_parameters, "%$where->{$key}%";
922 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
924 if ( defined $orderby && grep($orderby, @ordervalues)) {
925 $query .= ' ORDER BY '.$orderby;
928 my $sth = $dbh->prepare($query);
929 $sth->execute( @query_parameters );
931 while ( my $row = $sth->fetchrow_hashref ){
937 =head2 GetItemsForInventory
939 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
940 $location, $itemtype $datelastseen, $branch,
941 $offset, $size, $statushash);
943 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
945 The sub returns a reference to a list of hashes, each containing
946 itemnumber, author, title, barcode, item callnumber, and date last
947 seen. It is ordered by callnumber then title.
949 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
950 the datelastseen can be used to specify that you want to see items not seen since a past date only.
951 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
952 $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.
956 sub GetItemsForInventory {
957 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
958 my $dbh = C4::Context->dbh;
959 my ( @bind_params, @where_strings );
961 my $query = <<'END_SQL';
962 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
964 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
965 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
968 for my $authvfield (keys %$statushash){
969 if ( scalar @{$statushash->{$authvfield}} > 0 ){
970 my $joinedvals = join ',', @{$statushash->{$authvfield}};
971 push @where_strings, "$authvfield in (" . $joinedvals . ")";
977 push @where_strings, 'itemcallnumber >= ?';
978 push @bind_params, $minlocation;
982 push @where_strings, 'itemcallnumber <= ?';
983 push @bind_params, $maxlocation;
987 $datelastseen = format_date_in_iso($datelastseen);
988 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
989 push @bind_params, $datelastseen;
993 push @where_strings, 'items.location = ?';
994 push @bind_params, $location;
998 if($branch eq "homebranch"){
999 push @where_strings, 'items.homebranch = ?';
1001 push @where_strings, 'items.holdingbranch = ?';
1003 push @bind_params, $branchcode;
1007 push @where_strings, 'biblioitems.itemtype = ?';
1008 push @bind_params, $itemtype;
1011 if ( $ignoreissued) {
1012 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1013 push @where_strings, 'issues.date_due IS NULL';
1016 if ( @where_strings ) {
1018 $query .= join ' AND ', @where_strings;
1020 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1021 my $sth = $dbh->prepare($query);
1022 $sth->execute( @bind_params );
1026 while ( my $row = $sth->fetchrow_hashref ) {
1027 $offset-- if ($offset);
1028 $row->{datelastseen}=format_date($row->{datelastseen});
1029 if ( ( !$offset ) && $size ) {
1030 push @results, $row;
1037 =head2 GetItemsCount
1039 $count = &GetItemsCount( $biblionumber);
1041 This function return count of item with $biblionumber
1046 my ( $biblionumber ) = @_;
1047 my $dbh = C4::Context->dbh;
1048 my $query = "SELECT count(*)
1050 WHERE biblionumber=?";
1051 my $sth = $dbh->prepare($query);
1052 $sth->execute($biblionumber);
1053 my $count = $sth->fetchrow;
1057 =head2 GetItemInfosOf
1059 GetItemInfosOf(@itemnumbers);
1063 sub GetItemInfosOf {
1064 my @itemnumbers = @_;
1069 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1071 return get_infos_of( $query, 'itemnumber' );
1074 =head2 GetItemsByBiblioitemnumber
1076 GetItemsByBiblioitemnumber($biblioitemnumber);
1078 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1079 Called by C<C4::XISBN>
1083 sub GetItemsByBiblioitemnumber {
1084 my ( $bibitem ) = @_;
1085 my $dbh = C4::Context->dbh;
1086 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1087 # Get all items attached to a biblioitem
1090 $sth->execute($bibitem) || die $sth->errstr;
1091 while ( my $data = $sth->fetchrow_hashref ) {
1092 # Foreach item, get circulation information
1093 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1094 WHERE itemnumber = ?
1095 AND issues.borrowernumber = borrowers.borrowernumber"
1097 $sth2->execute( $data->{'itemnumber'} );
1098 if ( my $data2 = $sth2->fetchrow_hashref ) {
1099 # if item is out, set the due date and who it is out too
1100 $data->{'date_due'} = $data2->{'date_due'};
1101 $data->{'cardnumber'} = $data2->{'cardnumber'};
1102 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1105 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1106 $data->{'date_due'} = '';
1108 # Find the last 3 people who borrowed this item.
1109 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1110 AND old_issues.borrowernumber = borrowers.borrowernumber
1111 ORDER BY returndate desc,timestamp desc LIMIT 3";
1112 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1113 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1115 while ( my $data2 = $sth2->fetchrow_hashref ) {
1116 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1117 $data->{"card$i2"} = $data2->{'cardnumber'};
1118 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1121 push(@results,$data);
1128 @results = GetItemsInfo($biblionumber, $type);
1130 Returns information about books with the given biblionumber.
1132 C<$type> may be either C<intra> or anything else. If it is not set to
1133 C<intra>, then the search will exclude lost, very overdue, and
1136 C<GetItemsInfo> returns a list of references-to-hash. Each element
1137 contains a number of keys. Most of them are table items from the
1138 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1139 Koha database. Other keys include:
1143 =item C<$data-E<gt>{branchname}>
1145 The name (not the code) of the branch to which the book belongs.
1147 =item C<$data-E<gt>{datelastseen}>
1149 This is simply C<items.datelastseen>, except that while the date is
1150 stored in YYYY-MM-DD format in the database, here it is converted to
1151 DD/MM/YYYY format. A NULL date is returned as C<//>.
1153 =item C<$data-E<gt>{datedue}>
1155 =item C<$data-E<gt>{class}>
1157 This is the concatenation of C<biblioitems.classification>, the book's
1158 Dewey code, and C<biblioitems.subclass>.
1160 =item C<$data-E<gt>{ocount}>
1162 I think this is the number of copies of the book available.
1164 =item C<$data-E<gt>{order}>
1166 If this is set, it is set to C<One Order>.
1173 my ( $biblionumber, $type ) = @_;
1174 my $dbh = C4::Context->dbh;
1175 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1181 biblioitems.itemtype,
1184 biblioitems.publicationyear,
1185 biblioitems.publishercode,
1186 biblioitems.volumedate,
1187 biblioitems.volumedesc,
1190 items.notforloan as itemnotforloan,
1191 itemtypes.description,
1192 itemtypes.notforloan as notforloan_per_itemtype,
1195 LEFT JOIN branches ON items.homebranch = branches.branchcode
1196 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1197 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1198 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1199 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1200 $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1201 my $sth = $dbh->prepare($query);
1202 $sth->execute($biblionumber);
1207 my $isth = $dbh->prepare(
1208 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1209 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1210 WHERE itemnumber = ?"
1212 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1213 while ( my $data = $sth->fetchrow_hashref ) {
1216 $isth->execute( $data->{'itemnumber'} );
1217 if ( my $idata = $isth->fetchrow_hashref ) {
1218 $data->{borrowernumber} = $idata->{borrowernumber};
1219 $data->{cardnumber} = $idata->{cardnumber};
1220 $data->{surname} = $idata->{surname};
1221 $data->{firstname} = $idata->{firstname};
1222 $datedue = $idata->{'date_due'};
1223 if (C4::Context->preference("IndependantBranches")){
1224 my $userenv = C4::Context->userenv;
1225 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1226 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1230 if ( $data->{'serial'}) {
1231 $ssth->execute($data->{'itemnumber'}) ;
1232 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1235 if ( $datedue eq '' ) {
1236 my ( $restype, $reserves ) =
1237 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1238 # Previous conditional check with if ($restype) is not needed because a true
1239 # result for one item will result in subsequent items defaulting to this true
1241 $count_reserves = $restype;
1243 #get branch information.....
1244 my $bsth = $dbh->prepare(
1245 "SELECT * FROM branches WHERE branchcode = ?
1248 $bsth->execute( $data->{'holdingbranch'} );
1249 if ( my $bdata = $bsth->fetchrow_hashref ) {
1250 $data->{'branchname'} = $bdata->{'branchname'};
1252 $data->{'datedue'} = $datedue;
1253 $data->{'count_reserves'} = $count_reserves;
1255 # get notforloan complete status if applicable
1256 my $sthnflstatus = $dbh->prepare(
1257 'SELECT authorised_value
1258 FROM marc_subfield_structure
1259 WHERE kohafield="items.notforloan"
1263 $sthnflstatus->execute;
1264 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1265 if ($authorised_valuecode) {
1266 $sthnflstatus = $dbh->prepare(
1267 "SELECT lib FROM authorised_values
1269 AND authorised_value=?"
1271 $sthnflstatus->execute( $authorised_valuecode,
1272 $data->{itemnotforloan} );
1273 my ($lib) = $sthnflstatus->fetchrow;
1274 $data->{notforloanvalue} = $lib;
1277 # get restricted status and description if applicable
1278 my $restrictedstatus = $dbh->prepare(
1279 'SELECT authorised_value
1280 FROM marc_subfield_structure
1281 WHERE kohafield="items.restricted"
1285 $restrictedstatus->execute;
1286 ($authorised_valuecode) = $restrictedstatus->fetchrow;
1287 if ($authorised_valuecode) {
1288 $restrictedstatus = $dbh->prepare(
1289 "SELECT lib,lib_opac FROM authorised_values
1291 AND authorised_value=?"
1293 $restrictedstatus->execute( $authorised_valuecode,
1294 $data->{restricted} );
1296 if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1297 $data->{restricted} = $rstdata->{'lib'};
1298 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1302 # my stack procedures
1303 my $stackstatus = $dbh->prepare(
1304 'SELECT authorised_value
1305 FROM marc_subfield_structure
1306 WHERE kohafield="items.stack"
1309 $stackstatus->execute;
1311 ($authorised_valuecode) = $stackstatus->fetchrow;
1312 if ($authorised_valuecode) {
1313 $stackstatus = $dbh->prepare(
1315 FROM authorised_values
1317 AND authorised_value=?
1320 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1321 my ($lib) = $stackstatus->fetchrow;
1322 $data->{stack} = $lib;
1324 # Find the last 3 people who borrowed this item.
1325 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1326 WHERE itemnumber = ?
1327 AND old_issues.borrowernumber = borrowers.borrowernumber
1328 ORDER BY returndate DESC
1330 $sth2->execute($data->{'itemnumber'});
1332 while (my $data2 = $sth2->fetchrow_hashref()) {
1333 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1334 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1335 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1339 $results[$i] = $data;
1343 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1349 =head2 GetLastAcquisitions
1351 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1352 'itemtypes' => ('BK','BD')}, 10);
1356 sub GetLastAcquisitions {
1357 my ($data,$max) = @_;
1359 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1361 my $number_of_branches = @{$data->{branches}};
1362 my $number_of_itemtypes = @{$data->{itemtypes}};
1365 my @where = ('WHERE 1 ');
1366 $number_of_branches and push @where
1367 , 'AND holdingbranch IN ('
1368 , join(',', ('?') x $number_of_branches )
1372 $number_of_itemtypes and push @where
1373 , "AND $itemtype IN ("
1374 , join(',', ('?') x $number_of_itemtypes )
1378 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1379 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1380 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1382 GROUP BY biblio.biblionumber
1383 ORDER BY dateaccessioned DESC LIMIT $max";
1385 my $dbh = C4::Context->dbh;
1386 my $sth = $dbh->prepare($query);
1388 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1391 while( my $row = $sth->fetchrow_hashref){
1392 push @results, {date => $row->{dateaccessioned}
1393 , biblionumber => $row->{biblionumber}
1394 , title => $row->{title}};
1400 =head2 get_itemnumbers_of
1402 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1404 Given a list of biblionumbers, return the list of corresponding itemnumbers
1405 for each biblionumber.
1407 Return a reference on a hash where keys are biblionumbers and values are
1408 references on array of itemnumbers.
1412 sub get_itemnumbers_of {
1413 my @biblionumbers = @_;
1415 my $dbh = C4::Context->dbh;
1421 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1423 my $sth = $dbh->prepare($query);
1424 $sth->execute(@biblionumbers);
1428 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1429 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1432 return \%itemnumbers_of;
1435 =head2 GetItemnumberFromBarcode
1437 $result = GetItemnumberFromBarcode($barcode);
1441 sub GetItemnumberFromBarcode {
1443 my $dbh = C4::Context->dbh;
1446 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1447 $rq->execute($barcode);
1448 my ($result) = $rq->fetchrow;
1452 =head2 GetBarcodeFromItemnumber
1454 $result = GetBarcodeFromItemnumber($itemnumber);
1458 sub GetBarcodeFromItemnumber {
1459 my ($itemnumber) = @_;
1460 my $dbh = C4::Context->dbh;
1463 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1464 $rq->execute($itemnumber);
1465 my ($result) = $rq->fetchrow;
1469 =head3 get_item_authorised_values
1471 find the types and values for all authorised values assigned to this item.
1473 parameters: itemnumber
1475 returns: a hashref malling the authorised value to the value set for this itemnumber
1477 $authorised_values = {
1483 'RESTRICTED' => undef,
1486 'branches' => 'CPL',
1487 'cn_source' => undef,
1488 'itemtypes' => 'SER',
1491 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1495 sub get_item_authorised_values {
1496 my $itemnumber = shift;
1498 # assume that these entries in the authorised_value table are item level.
1499 my $query = q(SELECT distinct authorised_value, kohafield
1500 FROM marc_subfield_structure
1501 WHERE kohafield like 'item%'
1502 AND authorised_value != '' );
1504 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1505 my $iteminfo = GetItem( $itemnumber );
1506 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1508 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1509 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1510 $field =~ s/^items\.//;
1511 if ( exists $iteminfo->{ $field } ) {
1512 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1515 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1519 =head3 get_authorised_value_images
1521 find a list of icons that are appropriate for display based on the
1522 authorised values for a biblio.
1524 parameters: listref of authorised values, such as comes from
1525 get_item_authorised_values or
1526 from C4::Biblio::get_biblio_authorised_values
1528 returns: listref of hashrefs for each image. Each hashref looks like this:
1530 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1535 Notes: Currently, I put on the full path to the images on the staff
1536 side. This should either be configurable or not done at all. Since I
1537 have to deal with 'intranet' or 'opac' in
1538 get_biblio_authorised_values, perhaps I should be passing it in.
1542 sub get_authorised_value_images {
1543 my $authorised_values = shift;
1547 my $authorised_value_list = GetAuthorisedValues();
1548 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1549 foreach my $this_authorised_value ( @$authorised_value_list ) {
1550 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1551 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1552 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1553 if ( defined $this_authorised_value->{'imageurl'} ) {
1554 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1555 label => $this_authorised_value->{'lib'},
1556 category => $this_authorised_value->{'category'},
1557 value => $this_authorised_value->{'authorised_value'}, };
1562 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1567 =head1 LIMITED USE FUNCTIONS
1569 The following functions, while part of the public API,
1570 are not exported. This is generally because they are
1571 meant to be used by only one script for a specific
1572 purpose, and should not be used in any other context
1573 without careful thought.
1579 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1581 Returns MARC::Record of the item passed in parameter.
1582 This function is meant for use only in C<cataloguing/additem.pl>,
1583 where it is needed to support that script's MARC-like
1589 my ( $biblionumber, $itemnumber ) = @_;
1591 # GetMarcItem has been revised so that it does the following:
1592 # 1. Gets the item information from the items table.
1593 # 2. Converts it to a MARC field for storage in the bib record.
1595 # The previous behavior was:
1596 # 1. Get the bib record.
1597 # 2. Return the MARC tag corresponding to the item record.
1599 # The difference is that one treats the items row as authoritative,
1600 # while the other treats the MARC representation as authoritative
1601 # under certain circumstances.
1603 my $itemrecord = GetItem($itemnumber);
1605 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1606 # Also, don't emit a subfield if the underlying field is blank.
1609 return Item2Marc($itemrecord,$biblionumber);
1613 my ($itemrecord,$biblionumber)=@_;
1616 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1617 } keys %{ $itemrecord }
1619 my $itemmarc = TransformKohaToMarc($mungeditem);
1620 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1622 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1623 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1624 foreach my $field ($itemmarc->field($itemtag)){
1625 $field->add_subfields(@$unlinked_item_subfields);
1631 =head1 PRIVATE FUNCTIONS AND VARIABLES
1633 The following functions are not meant to be called
1634 directly, but are documented in order to explain
1635 the inner workings of C<C4::Items>.
1639 =head2 %derived_columns
1641 This hash keeps track of item columns that
1642 are strictly derived from other columns in
1643 the item record and are not meant to be set
1646 Each key in the hash should be the name of a
1647 column (as named by TransformMarcToKoha). Each
1648 value should be hashref whose keys are the
1649 columns on which the derived column depends. The
1650 hashref should also contain a 'BUILDER' key
1651 that is a reference to a sub that calculates
1656 my %derived_columns = (
1657 'items.cn_sort' => {
1658 'itemcallnumber' => 1,
1659 'items.cn_source' => 1,
1660 'BUILDER' => \&_calc_items_cn_sort,
1664 =head2 _set_derived_columns_for_add
1666 _set_derived_column_for_add($item);
1668 Given an item hash representing a new item to be added,
1669 calculate any derived columns. Currently the only
1670 such column is C<items.cn_sort>.
1674 sub _set_derived_columns_for_add {
1677 foreach my $column (keys %derived_columns) {
1678 my $builder = $derived_columns{$column}->{'BUILDER'};
1679 my $source_values = {};
1680 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1681 next if $source_column eq 'BUILDER';
1682 $source_values->{$source_column} = $item->{$source_column};
1684 $builder->($item, $source_values);
1688 =head2 _set_derived_columns_for_mod
1690 _set_derived_column_for_mod($item);
1692 Given an item hash representing a new item to be modified.
1693 calculate any derived columns. Currently the only
1694 such column is C<items.cn_sort>.
1696 This routine differs from C<_set_derived_columns_for_add>
1697 in that it needs to handle partial item records. In other
1698 words, the caller of C<ModItem> may have supplied only one
1699 or two columns to be changed, so this function needs to
1700 determine whether any of the columns to be changed affect
1701 any of the derived columns. Also, if a derived column
1702 depends on more than one column, but the caller is not
1703 changing all of then, this routine retrieves the unchanged
1704 values from the database in order to ensure a correct
1709 sub _set_derived_columns_for_mod {
1712 foreach my $column (keys %derived_columns) {
1713 my $builder = $derived_columns{$column}->{'BUILDER'};
1714 my $source_values = {};
1715 my %missing_sources = ();
1716 my $must_recalc = 0;
1717 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1718 next if $source_column eq 'BUILDER';
1719 if (exists $item->{$source_column}) {
1721 $source_values->{$source_column} = $item->{$source_column};
1723 $missing_sources{$source_column} = 1;
1727 foreach my $source_column (keys %missing_sources) {
1728 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1730 $builder->($item, $source_values);
1735 =head2 _do_column_fixes_for_mod
1737 _do_column_fixes_for_mod($item);
1739 Given an item hashref containing one or more
1740 columns to modify, fix up certain values.
1741 Specifically, set to 0 any passed value
1742 of C<notforloan>, C<damaged>, C<itemlost>, or
1743 C<wthdrawn> that is either undefined or
1744 contains the empty string.
1748 sub _do_column_fixes_for_mod {
1751 if (exists $item->{'notforloan'} and
1752 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1753 $item->{'notforloan'} = 0;
1755 if (exists $item->{'damaged'} and
1756 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1757 $item->{'damaged'} = 0;
1759 if (exists $item->{'itemlost'} and
1760 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1761 $item->{'itemlost'} = 0;
1763 if (exists $item->{'wthdrawn'} and
1764 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1765 $item->{'wthdrawn'} = 0;
1767 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1768 $item->{'permanent_location'} = $item->{'location'};
1772 =head2 _get_single_item_column
1774 _get_single_item_column($column, $itemnumber);
1776 Retrieves the value of a single column from an C<items>
1777 row specified by C<$itemnumber>.
1781 sub _get_single_item_column {
1783 my $itemnumber = shift;
1785 my $dbh = C4::Context->dbh;
1786 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1787 $sth->execute($itemnumber);
1788 my ($value) = $sth->fetchrow();
1792 =head2 _calc_items_cn_sort
1794 _calc_items_cn_sort($item, $source_values);
1796 Helper routine to calculate C<items.cn_sort>.
1800 sub _calc_items_cn_sort {
1802 my $source_values = shift;
1804 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1807 =head2 _set_defaults_for_add
1809 _set_defaults_for_add($item_hash);
1811 Given an item hash representing an item to be added, set
1812 correct default values for columns whose default value
1813 is not handled by the DBMS. This includes the following
1820 C<items.dateaccessioned>
1842 sub _set_defaults_for_add {
1844 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1845 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1848 =head2 _koha_new_item
1850 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1852 Perform the actual insert into the C<items> table.
1856 sub _koha_new_item {
1857 my ( $item, $barcode ) = @_;
1858 my $dbh=C4::Context->dbh;
1861 "INSERT INTO items SET
1863 biblioitemnumber = ?,
1865 dateaccessioned = ?,
1869 replacementprice = ?,
1870 replacementpricedate = NOW(),
1871 datelastborrowed = ?,
1872 datelastseen = NOW(),
1895 more_subfields_xml = ?,
1898 my $sth = $dbh->prepare($query);
1900 $item->{'biblionumber'},
1901 $item->{'biblioitemnumber'},
1903 $item->{'dateaccessioned'},
1904 $item->{'booksellerid'},
1905 $item->{'homebranch'},
1907 $item->{'replacementprice'},
1908 $item->{datelastborrowed},
1910 $item->{'notforloan'},
1912 $item->{'itemlost'},
1913 $item->{'wthdrawn'},
1914 $item->{'itemcallnumber'},
1915 $item->{'restricted'},
1916 $item->{'itemnotes'},
1917 $item->{'holdingbranch'},
1919 $item->{'location'},
1922 $item->{'renewals'},
1923 $item->{'reserves'},
1924 $item->{'items.cn_source'},
1925 $item->{'items.cn_sort'},
1928 $item->{'materials'},
1930 $item->{'enumchron'},
1931 $item->{'more_subfields_xml'},
1932 $item->{'copynumber'},
1934 my $itemnumber = $dbh->{'mysql_insertid'};
1935 if ( defined $sth->errstr ) {
1936 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1938 return ( $itemnumber, $error );
1941 =head2 MoveItemFromBiblio
1943 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
1945 Moves an item from a biblio to another
1947 Returns undef if the move failed or the biblionumber of the destination record otherwise
1951 sub MoveItemFromBiblio {
1952 my ($itemnumber, $frombiblio, $tobiblio) = @_;
1953 my $dbh = C4::Context->dbh;
1954 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
1955 $sth->execute( $tobiblio );
1956 my ( $tobiblioitem ) = $sth->fetchrow();
1957 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
1958 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
1962 my $frameworkcode = GetFrameworkCode($frombiblio);
1964 # Getting marc field for itemnumber
1965 my ($itemtag, $itemsubfield) = GetMarcFromKohaField('items.itemnumber', $frameworkcode);
1967 # Getting the record we want to move the item from
1968 my $record = GetMarcBiblio($frombiblio);
1970 # The item we want to move
1974 foreach my $fielditem ($record->field($itemtag)){
1975 # If it is the item we want to move
1976 if ($fielditem->subfield($itemsubfield) == $itemnumber) {
1979 # Then delete it from the record
1980 $record->delete_field($fielditem)
1984 # If we found an item (should always true, except in case of database-marcxml inconsistency)
1987 # Checking if the item we want to move is in an order
1988 my $order = GetOrderFromItemnumber($itemnumber);
1990 # Replacing the biblionumber within the order if necessary
1991 $order->{'biblionumber'} = $tobiblio;
1995 # Saving the modification
1996 ModBiblioMarc($record, $frombiblio, $frameworkcode);
1998 # Getting the record we want to move the item to
1999 $record = GetMarcBiblio($tobiblio);
2001 # Inserting the previously saved item
2002 $record->insert_fields_ordered($item);
2004 # Saving the modification
2005 ModBiblioMarc($record, $tobiblio, $frameworkcode);
2017 DelItemCheck($dbh, $biblionumber, $itemnumber);
2019 Exported function (core API) for deleting an item record in Koha if there no current issue.
2024 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2027 # check that there is no issue on this item before deletion.
2028 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2029 $sth->execute($itemnumber);
2031 my $onloan=$sth->fetchrow;
2034 $error = "book_on_loan"
2036 # check it doesnt have a waiting reserve
2037 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2038 $sth->execute($itemnumber);
2039 my $reserve=$sth->fetchrow;
2041 $error = "book_reserved";
2043 DelItem($dbh, $biblionumber, $itemnumber);
2050 =head2 _koha_modify_item
2052 my ($itemnumber,$error) =_koha_modify_item( $item );
2054 Perform the actual update of the C<items> row. Note that this
2055 routine accepts a hashref specifying the columns to update.
2059 sub _koha_modify_item {
2061 my $dbh=C4::Context->dbh;
2064 my $query = "UPDATE items SET ";
2066 for my $key ( keys %$item ) {
2068 push @bind, $item->{$key};
2071 $query .= " WHERE itemnumber=?";
2072 push @bind, $item->{'itemnumber'};
2073 my $sth = C4::Context->dbh->prepare($query);
2074 $sth->execute(@bind);
2075 if ( C4::Context->dbh->errstr ) {
2076 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2079 return ($item->{'itemnumber'},$error);
2082 =head2 _koha_delete_item
2084 _koha_delete_item( $dbh, $itemnum );
2086 Internal function to delete an item record from the koha tables
2090 sub _koha_delete_item {
2091 my ( $dbh, $itemnum ) = @_;
2093 # save the deleted item to deleteditems table
2094 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2095 $sth->execute($itemnum);
2096 my $data = $sth->fetchrow_hashref();
2097 my $query = "INSERT INTO deleteditems SET ";
2099 foreach my $key ( keys %$data ) {
2100 $query .= "$key = ?,";
2101 push( @bind, $data->{$key} );
2104 $sth = $dbh->prepare($query);
2105 $sth->execute(@bind);
2107 # delete from items table
2108 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2109 $sth->execute($itemnum);
2113 =head2 _marc_from_item_hash
2115 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2117 Given an item hash representing a complete item record,
2118 create a C<MARC::Record> object containing an embedded
2119 tag representing that item.
2121 The third, optional parameter C<$unlinked_item_subfields> is
2122 an arrayref of subfields (not mapped to C<items> fields per the
2123 framework) to be added to the MARC representation
2128 sub _marc_from_item_hash {
2130 my $frameworkcode = shift;
2131 my $unlinked_item_subfields;
2133 $unlinked_item_subfields = shift;
2136 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2137 # Also, don't emit a subfield if the underlying field is blank.
2138 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2139 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2140 : () } keys %{ $item } };
2142 my $item_marc = MARC::Record->new();
2143 foreach my $item_field (keys %{ $mungeditem }) {
2144 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
2145 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2146 if (my $field = $item_marc->field($tag)) {
2147 $field->add_subfields($subfield => $mungeditem->{$item_field});
2149 my $add_subfields = [];
2150 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2151 $add_subfields = $unlinked_item_subfields;
2153 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
2160 =head2 _add_item_field_to_biblio
2162 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2164 Adds the fields from a MARC record containing the
2165 representation of a Koha item record to the MARC
2166 biblio record. The input C<$item_marc> record
2167 is expect to contain just one field, the embedded
2168 item information field.
2172 sub _add_item_field_to_biblio {
2173 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2175 my $biblio_marc = GetMarcBiblio($biblionumber);
2176 foreach my $field ($item_marc->fields()) {
2177 $biblio_marc->append_fields($field);
2180 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2183 =head2 _replace_item_field_in_biblio
2185 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2187 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2188 representation of the item, examine the biblio MARC
2189 for the corresponding tag for that item and
2190 replace it with the tag from C<$item_marc>.
2194 sub _replace_item_field_in_biblio {
2195 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2196 my $dbh = C4::Context->dbh;
2198 # get complete MARC record & replace the item field by the new one
2199 my $completeRecord = GetMarcBiblio($biblionumber);
2200 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2201 my $itemField = $ItemRecord->field($itemtag);
2202 my @items = $completeRecord->field($itemtag);
2205 if ($_->subfield($itemsubfield) eq $itemnumber) {
2206 $_->replace_with($itemField);
2212 # If we haven't found the matching field,
2213 # just add it. However, this means that
2214 # there is likely a bug.
2215 $completeRecord->append_fields($itemField);
2219 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2222 =head2 _repack_item_errors
2224 Add an error message hash generated by C<CheckItemPreSave>
2225 to a list of errors.
2229 sub _repack_item_errors {
2230 my $item_sequence_num = shift;
2231 my $item_ref = shift;
2232 my $error_ref = shift;
2234 my @repacked_errors = ();
2236 foreach my $error_code (sort keys %{ $error_ref }) {
2237 my $repacked_error = {};
2238 $repacked_error->{'item_sequence'} = $item_sequence_num;
2239 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2240 $repacked_error->{'error_code'} = $error_code;
2241 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2242 push @repacked_errors, $repacked_error;
2245 return @repacked_errors;
2248 =head2 _get_unlinked_item_subfields
2250 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2254 sub _get_unlinked_item_subfields {
2255 my $original_item_marc = shift;
2256 my $frameworkcode = shift;
2258 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2260 # assume that this record has only one field, and that that
2261 # field contains only the item information
2263 my @fields = $original_item_marc->fields();
2264 if ($#fields > -1) {
2265 my $field = $fields[0];
2266 my $tag = $field->tag();
2267 foreach my $subfield ($field->subfields()) {
2268 if (defined $subfield->[1] and
2269 $subfield->[1] ne '' and
2270 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2271 push @$subfields, $subfield->[0] => $subfield->[1];
2278 =head2 _get_unlinked_subfields_xml
2280 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2284 sub _get_unlinked_subfields_xml {
2285 my $unlinked_item_subfields = shift;
2288 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2289 my $marc = MARC::Record->new();
2290 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2291 # used in the framework
2292 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2293 $marc->encoding("UTF-8");
2294 $xml = $marc->as_xml("USMARC");
2300 =head2 _parse_unlinked_item_subfields_from_xml
2302 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2306 sub _parse_unlinked_item_subfields_from_xml {
2309 return unless defined $xml and $xml ne "";
2310 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2311 my $unlinked_subfields = [];
2312 my @fields = $marc->fields();
2313 if ($#fields > -1) {
2314 foreach my $subfield ($fields[0]->subfields()) {
2315 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2318 return $unlinked_subfields;