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
26 use C4
::Dates qw
/format_date format_date_in_iso/;
35 use vars
qw($VERSION @ISA @EXPORT);
41 @ISA = qw( Exporter );
64 GetItemsByBiblioitemnumber
67 GetItemnumberFromBarcode
78 C4::Items - item management functions
82 This module contains an API for manipulating item
83 records in Koha, and is used by cataloguing, circulation,
84 acquisitions, and serials management.
86 A Koha item record is stored in two places: the
87 items table and embedded in a MARC tag in the XML
88 version of the associated bib record in C<biblioitems.marcxml>.
89 This is done to allow the item information to be readily
90 indexed (e.g., by Zebra), but means that each item
91 modification transaction must keep the items table
92 and the MARC XML in sync at all times.
94 Consequently, all code that creates, modifies, or deletes
95 item records B<must> use an appropriate function from
96 C<C4::Items>. If no existing function is suitable, it is
97 better to add one to C<C4::Items> than to use add
98 one-off SQL statements to add or modify items.
100 The items table will be considered authoritative. In other
101 words, if there is ever a discrepancy between the items
102 table and the MARC XML, the items table should be considered
105 =head1 HISTORICAL NOTE
107 Most of the functions in C<C4::Items> were originally in
108 the C<C4::Biblio> module.
110 =head1 CORE EXPORTED FUNCTIONS
112 The following functions are meant for use by users
121 $item = GetItem($itemnumber,$barcode,$serial);
125 Return item information, for a given itemnumber or barcode.
126 The return value is a hashref mapping item column
127 names to values. If C<$serial> is true, include serial publication data.
132 my ($itemnumber,$barcode, $serial) = @_;
133 my $dbh = C4
::Context
->dbh;
136 my $sth = $dbh->prepare("
138 WHERE itemnumber = ?");
139 $sth->execute($itemnumber);
140 $data = $sth->fetchrow_hashref;
142 my $sth = $dbh->prepare("
146 $sth->execute($barcode);
147 $data = $sth->fetchrow_hashref;
150 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
151 $ssth->execute($data->{'itemnumber'}) ;
152 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
153 warn $data->{'serialseq'} , $data->{'publisheddate'};
155 #if we don't have an items.itype, use biblioitems.itemtype.
156 if( ! $data->{'itype'} ) {
157 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
158 $sth->execute($data->{'biblionumber'});
159 ($data->{'itype'}) = $sth->fetchrow_array;
168 CartToShelf($itemnumber);
172 Set the current shelving location of the item record
173 to its stored permanent shelving location. This is
174 primarily used to indicate when an item whose current
175 location is a special processing ('PROC') or shelving cart
176 ('CART') location is back in the stacks.
181 my ( $itemnumber ) = @_;
183 unless ( $itemnumber ) {
184 croak
"FAILED CartToShelf() - no itemnumber supplied";
187 my $item = GetItem
($itemnumber);
188 $item->{location
} = $item->{permanent_location
};
189 ModItem
($item, undef, $itemnumber);
192 =head2 AddItemFromMarc
196 my ($biblionumber, $biblioitemnumber, $itemnumber)
197 = AddItemFromMarc($source_item_marc, $biblionumber);
201 Given a MARC::Record object containing an embedded item
202 record and a biblionumber, create a new item record.
206 sub AddItemFromMarc
{
207 my ( $source_item_marc, $biblionumber ) = @_;
208 my $dbh = C4
::Context
->dbh;
210 # parse item hash from MARC
211 my $frameworkcode = GetFrameworkCode
( $biblionumber );
212 my $item = &TransformMarcToKoha
( $dbh, $source_item_marc, $frameworkcode );
213 my $unlinked_item_subfields = _get_unlinked_item_subfields
($source_item_marc, $frameworkcode);
214 return AddItem
($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
221 my ($biblionumber, $biblioitemnumber, $itemnumber)
222 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
226 Given a hash containing item column names as keys,
227 create a new Koha item record.
229 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
230 do not need to be supplied for general use; they exist
231 simply to allow them to be picked up from AddItemFromMarc.
233 The final optional parameter, C<$unlinked_item_subfields>, contains
234 an arrayref containing subfields present in the original MARC
235 representation of the item (e.g., from the item editor) that are
236 not mapped to C<items> columns directly but should instead
237 be stored in C<items.more_subfields_xml> and included in
238 the biblio items tag for display and indexing.
244 my $biblionumber = shift;
246 my $dbh = @_ ?
shift : C4
::Context
->dbh;
247 my $frameworkcode = @_ ?
shift : GetFrameworkCode
( $biblionumber );
248 my $unlinked_item_subfields;
250 $unlinked_item_subfields = shift
253 # needs old biblionumber and biblioitemnumber
254 $item->{'biblionumber'} = $biblionumber;
255 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
256 $sth->execute( $item->{'biblionumber'} );
257 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
259 _set_defaults_for_add
($item);
260 _set_derived_columns_for_add
($item);
261 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
262 # FIXME - checks here
263 unless ( $item->{itype
} ) { # default to biblioitem.itemtype if no itype
264 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
265 $itype_sth->execute( $item->{'biblionumber'} );
266 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
269 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
270 $item->{'itemnumber'} = $itemnumber;
272 # create MARC tag representing item and add to bib
273 my $new_item_marc = _marc_from_item_hash
($item, $frameworkcode, $unlinked_item_subfields);
274 _add_item_field_to_biblio
($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
276 logaction
("CATALOGUING", "ADD", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
278 return ($item->{biblionumber
}, $item->{biblioitemnumber
}, $itemnumber);
281 =head2 AddItemBatchFromMarc
285 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
289 Efficiently create item records from a MARC biblio record with
290 embedded item fields. This routine is suitable for batch jobs.
292 This API assumes that the bib record has already been
293 saved to the C<biblio> and C<biblioitems> tables. It does
294 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
295 are populated, but it will do so via a call to ModBibiloMarc.
297 The goal of this API is to have a similar effect to using AddBiblio
298 and AddItems in succession, but without inefficient repeated
299 parsing of the MARC XML bib record.
301 This function returns an arrayref of new itemsnumbers and an arrayref of item
302 errors encountered during the processing. Each entry in the errors
303 list is a hashref containing the following keys:
309 Sequence number of original item tag in the MARC record.
313 Item barcode, provide to assist in the construction of
314 useful error messages.
316 =item error_condition
318 Code representing the error condition. Can be 'duplicate_barcode',
319 'invalid_homebranch', or 'invalid_holdingbranch'.
321 =item error_information
323 Additional information appropriate to the error condition.
329 sub AddItemBatchFromMarc
{
330 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
332 my @itemnumbers = ();
334 my $dbh = C4
::Context
->dbh;
336 # loop through the item tags and start creating items
337 my @bad_item_fields = ();
338 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField
("items.itemnumber",'');
339 my $item_sequence_num = 0;
340 ITEMFIELD
: foreach my $item_field ($record->field($itemtag)) {
341 $item_sequence_num++;
342 # we take the item field and stick it into a new
343 # MARC record -- this is required so far because (FIXME)
344 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
345 # and there is no TransformMarcFieldToKoha
346 my $temp_item_marc = MARC
::Record
->new();
347 $temp_item_marc->append_fields($item_field);
349 # add biblionumber and biblioitemnumber
350 my $item = TransformMarcToKoha
( $dbh, $temp_item_marc, $frameworkcode, 'items' );
351 my $unlinked_item_subfields = _get_unlinked_item_subfields
($temp_item_marc, $frameworkcode);
352 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
353 $item->{'biblionumber'} = $biblionumber;
354 $item->{'biblioitemnumber'} = $biblioitemnumber;
356 # check for duplicate barcode
357 my %item_errors = CheckItemPreSave
($item);
359 push @errors, _repack_item_errors
($item_sequence_num, $item, \
%item_errors);
360 push @bad_item_fields, $item_field;
364 _set_defaults_for_add
($item);
365 _set_derived_columns_for_add
($item);
366 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
367 warn $error if $error;
368 push @itemnumbers, $itemnumber; # FIXME not checking error
369 $item->{'itemnumber'} = $itemnumber;
371 logaction
("CATALOGUING", "ADD", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
373 my $new_item_marc = _marc_from_item_hash
($item, $frameworkcode, $unlinked_item_subfields);
374 $item_field->replace_with($new_item_marc->field($itemtag));
377 # remove any MARC item fields for rejected items
378 foreach my $item_field (@bad_item_fields) {
379 $record->delete_field($item_field);
382 # update the MARC biblio
383 $biblionumber = ModBiblioMarc
( $record, $biblionumber, $frameworkcode );
385 return (\
@itemnumbers, \
@errors);
388 =head2 ModItemFromMarc
392 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
396 This function updates an item record based on a supplied
397 C<MARC::Record> object containing an embedded item field.
398 This API is meant for the use of C<additem.pl>; for
399 other purposes, C<ModItem> should be used.
401 This function uses the hash %default_values_for_mod_from_marc,
402 which contains default values for item fields to
403 apply when modifying an item. This is needed beccause
404 if an item field's value is cleared, TransformMarcToKoha
405 does not include the column in the
406 hash that's passed to ModItem, which without
407 use of this hash makes it impossible to clear
408 an item field's value. See bug 2466.
410 Note that only columns that can be directly
411 changed from the cataloging and serials
412 item editors are included in this hash.
416 my %default_values_for_mod_from_marc = (
418 booksellerid
=> undef,
420 'items.cn_source' => undef,
423 dateaccessioned
=> undef,
425 holdingbranch
=> undef,
427 itemcallnumber
=> undef,
436 replacementprice
=> undef,
437 replacementpricedate
=> undef,
444 sub ModItemFromMarc
{
445 my $item_marc = shift;
446 my $biblionumber = shift;
447 my $itemnumber = shift;
449 my $dbh = C4
::Context
->dbh;
450 my $frameworkcode = GetFrameworkCode
( $biblionumber );
451 my ($itemtag,$itemsubfield)=GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
453 my $localitemmarc=MARC
::Record
->new;
454 $localitemmarc->append_fields($item_marc->field($itemtag));
455 my $item = &TransformMarcToKoha
( $dbh, $item_marc, $frameworkcode ,'items');
456 foreach my $item_field (keys %default_values_for_mod_from_marc) {
457 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
459 my $unlinked_item_subfields = _get_unlinked_item_subfields
($item_marc, $frameworkcode);
461 return ModItem
($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
468 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
472 Change one or more columns in an item record and update
473 the MARC representation of the item.
475 The first argument is a hashref mapping from item column
476 names to the new values. The second and third arguments
477 are the biblionumber and itemnumber, respectively.
479 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
480 an arrayref containing subfields present in the original MARC
481 representation of the item (e.g., from the item editor) that are
482 not mapped to C<items> columns directly but should instead
483 be stored in C<items.more_subfields_xml> and included in
484 the biblio items tag for display and indexing.
486 If one of the changed columns is used to calculate
487 the derived value of a column such as C<items.cn_sort>,
488 this routine will perform the necessary calculation
495 my $biblionumber = shift;
496 my $itemnumber = shift;
498 # if $biblionumber is undefined, get it from the current item
499 unless (defined $biblionumber) {
500 $biblionumber = _get_single_item_column
('biblionumber', $itemnumber);
503 my $dbh = @_ ?
shift : C4
::Context
->dbh;
504 my $frameworkcode = @_ ?
shift : GetFrameworkCode
( $biblionumber );
506 my $unlinked_item_subfields;
508 $unlinked_item_subfields = shift;
509 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
512 $item->{'itemnumber'} = $itemnumber or return undef;
513 _set_derived_columns_for_mod
($item);
514 _do_column_fixes_for_mod
($item);
517 # attempt to change itemnumber
518 # attempt to change biblionumber (if we want
519 # an API to relink an item to a different bib,
520 # it should be a separate function)
523 _koha_modify_item
($item);
525 # update biblio MARC XML
526 my $whole_item = GetItem
($itemnumber) or die "FAILED GetItem($itemnumber)";
528 unless (defined $unlinked_item_subfields) {
529 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml
($whole_item->{'more_subfields_xml'});
531 my $new_item_marc = _marc_from_item_hash
($whole_item, $frameworkcode, $unlinked_item_subfields)
532 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
534 _replace_item_field_in_biblio
($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
535 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
536 logaction
("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4
::Context
->preference("CataloguingLog");
539 =head2 ModItemTransfer
543 ModItemTransfer($itenumber, $frombranch, $tobranch);
547 Marks an item as being transferred from one branch
552 sub ModItemTransfer
{
553 my ( $itemnumber, $frombranch, $tobranch ) = @_;
555 my $dbh = C4
::Context
->dbh;
557 #new entry in branchtransfers....
558 my $sth = $dbh->prepare(
559 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
560 VALUES (?, ?, NOW(), ?)");
561 $sth->execute($itemnumber, $frombranch, $tobranch);
563 ModItem
({ holdingbranch
=> $tobranch }, undef, $itemnumber);
564 ModDateLastSeen
($itemnumber);
568 =head2 ModDateLastSeen
572 ModDateLastSeen($itemnum);
576 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
577 C<$itemnum> is the item number
581 sub ModDateLastSeen
{
582 my ($itemnumber) = @_;
584 my $today = C4
::Dates
->new();
585 ModItem
({ itemlost
=> 0, datelastseen
=> $today->output("iso") }, undef, $itemnumber);
592 DelItem($biblionumber, $itemnumber);
596 Exported function (core API) for deleting an item record in Koha.
601 my ( $dbh, $biblionumber, $itemnumber ) = @_;
603 # FIXME check the item has no current issues
605 _koha_delete_item
( $dbh, $itemnumber );
607 # get the MARC record
608 my $record = GetMarcBiblio
($biblionumber);
609 my $frameworkcode = GetFrameworkCode
($biblionumber);
612 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
613 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
615 #search item field code
616 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
617 my @fields = $record->field($itemtag);
619 # delete the item specified
620 foreach my $field (@fields) {
621 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
622 $record->delete_field($field);
625 &ModBiblioMarc
( $record, $biblionumber, $frameworkcode );
626 logaction
("CATALOGUING", "DELETE", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
629 =head2 CheckItemPreSave
633 my $item_ref = TransformMarcToKoha($marc, 'items');
635 my %errors = CheckItemPreSave($item_ref);
636 if (exists $errors{'duplicate_barcode'}) {
637 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
638 } elsif (exists $errors{'invalid_homebranch'}) {
639 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
640 } elsif (exists $errors{'invalid_holdingbranch'}) {
641 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
648 Given a hashref containing item fields, determine if it can be
649 inserted or updated in the database. Specifically, checks for
650 database integrity issues, and returns a hash containing any
651 of the following keys, if applicable.
655 =item duplicate_barcode
657 Barcode, if it duplicates one already found in the database.
659 =item invalid_homebranch
661 Home branch, if not defined in branches table.
663 =item invalid_holdingbranch
665 Holding branch, if not defined in branches table.
669 This function does NOT implement any policy-related checks,
670 e.g., whether current operator is allowed to save an
671 item that has a given branch code.
675 sub CheckItemPreSave
{
676 my $item_ref = shift;
680 # check for duplicate barcode
681 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
682 my $existing_itemnumber = GetItemnumberFromBarcode
($item_ref->{'barcode'});
683 if ($existing_itemnumber) {
684 if (!exists $item_ref->{'itemnumber'} # new item
685 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
686 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
691 # check for valid home branch
692 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
693 my $branch_name = GetBranchName
($item_ref->{'homebranch'});
694 unless (defined $branch_name) {
695 # relies on fact that branches.branchname is a non-NULL column,
696 # so GetBranchName returns undef only if branch does not exist
697 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
701 # check for valid holding branch
702 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
703 my $branch_name = GetBranchName
($item_ref->{'holdingbranch'});
704 unless (defined $branch_name) {
705 # relies on fact that branches.branchname is a non-NULL column,
706 # so GetBranchName returns undef only if branch does not exist
707 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
715 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
717 The following functions provide various ways of
718 getting an item record, a set of item records, or
719 lists of authorized values for certain item fields.
721 Some of the functions in this group are candidates
722 for refactoring -- for example, some of the code
723 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
724 has copy-and-paste work.
732 $itemstatushash = GetItemStatus($fwkcode);
736 Returns a list of valid values for the
737 C<items.notforloan> field.
739 NOTE: does B<not> return an individual item's
742 Can be MARC dependant.
744 But basically could be can be loan or not
745 Create a status selector with the following code
747 =head3 in PERL SCRIPT
751 my $itemstatushash = getitemstatus;
753 foreach my $thisstatus (keys %$itemstatushash) {
754 my %row =(value => $thisstatus,
755 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
757 push @itemstatusloop, \%row;
759 $template->param(statusloop=>\@itemstatusloop);
767 <select name="statusloop">
768 <option value="">Default</option>
769 <!-- TMPL_LOOP name="statusloop" -->
770 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
780 # returns a reference to a hash of references to status...
783 my $dbh = C4
::Context
->dbh;
785 $fwk = '' unless ($fwk);
786 my ( $tag, $subfield ) =
787 GetMarcFromKohaField
( "items.notforloan", $fwk );
788 if ( $tag and $subfield ) {
791 "SELECT authorised_value
792 FROM marc_subfield_structure
798 $sth->execute( $tag, $subfield, $fwk );
799 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
802 "SELECT authorised_value,lib
803 FROM authorised_values
808 $authvalsth->execute($authorisedvaluecat);
809 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
810 $itemstatus{$authorisedvalue} = $lib;
824 $itemstatus{"1"} = "Not For Loan";
828 =head2 GetItemLocation
832 $itemlochash = GetItemLocation($fwk);
836 Returns a list of valid values for the
837 C<items.location> field.
839 NOTE: does B<not> return an individual item's
842 where fwk stands for an optional framework code.
843 Create a location selector with the following code
845 =head3 in PERL SCRIPT
849 my $itemlochash = getitemlocation;
851 foreach my $thisloc (keys %$itemlochash) {
852 my $selected = 1 if $thisbranch eq $branch;
853 my %row =(locval => $thisloc,
854 selected => $selected,
855 locname => $itemlochash->{$thisloc},
857 push @itemlocloop, \%row;
859 $template->param(itemlocationloop => \@itemlocloop);
867 <select name="location">
868 <option value="">Default</option>
869 <!-- TMPL_LOOP name="itemlocationloop" -->
870 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
878 sub GetItemLocation
{
880 # returns a reference to a hash of references to location...
883 my $dbh = C4
::Context
->dbh;
885 $fwk = '' unless ($fwk);
886 my ( $tag, $subfield ) =
887 GetMarcFromKohaField
( "items.location", $fwk );
888 if ( $tag and $subfield ) {
891 "SELECT authorised_value
892 FROM marc_subfield_structure
897 $sth->execute( $tag, $subfield, $fwk );
898 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
901 "SELECT authorised_value,lib
902 FROM authorised_values
906 $authvalsth->execute($authorisedvaluecat);
907 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
908 $itemlocation{$authorisedvalue} = $lib;
910 return \
%itemlocation;
922 $itemlocation{"1"} = "Not For Loan";
923 return \
%itemlocation;
930 $items = GetLostItems( $where, $orderby );
934 This function gets a list of lost items.
940 C<$where> is a hashref. it containts a field of the items table as key
941 and the value to match as value. For example:
943 { barcode => 'abc123',
944 homebranch => 'CPL', }
946 C<$orderby> is a field of the items table by which the resultset
951 C<$items> is a reference to an array full of hashrefs with columns
952 from the "items" table as keys.
954 =item usage in the perl script:
956 my $where = { barcode => '0001548' };
957 my $items = GetLostItems( $where, "homebranch" );
958 $template->param( itemsloop => $items );
965 # Getting input args.
968 my $dbh = C4
::Context
->dbh;
973 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
974 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
975 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
977 authorised_values.category = 'LOST'
978 AND itemlost IS NOT NULL
981 my @query_parameters;
982 foreach my $key (keys %$where) {
983 $query .= " AND $key LIKE ?";
984 push @query_parameters, "%$where->{$key}%";
986 my @ordervalues = qw
/title author homebranch itype barcode price replacementprice lib datelastseen location/;
988 if ( defined $orderby && grep($orderby, @ordervalues)) {
989 $query .= ' ORDER BY '.$orderby;
992 my $sth = $dbh->prepare($query);
993 $sth->execute( @query_parameters );
995 while ( my $row = $sth->fetchrow_hashref ){
1001 =head2 GetItemsForInventory
1005 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size, $statushash);
1009 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1011 The sub returns a reference to a list of hashes, each containing
1012 itemnumber, author, title, barcode, item callnumber, and date last
1013 seen. It is ordered by callnumber then title.
1015 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1016 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1017 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1018 $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.
1022 sub GetItemsForInventory
{
1023 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branch, $offset, $size, $statushash ) = @_;
1024 my $dbh = C4
::Context
->dbh;
1025 my ( @bind_params, @where_strings );
1027 my $query = <<'END_SQL';
1028 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
1030 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1031 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1034 for my $authvfield (keys %$statushash){
1035 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1036 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1037 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1043 push @where_strings, 'itemcallnumber >= ?';
1044 push @bind_params, $minlocation;
1048 push @where_strings, 'itemcallnumber <= ?';
1049 push @bind_params, $maxlocation;
1052 if ($datelastseen) {
1053 $datelastseen = format_date_in_iso($datelastseen);
1054 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1055 push @bind_params, $datelastseen;
1059 push @where_strings, 'items.location = ?';
1060 push @bind_params, $location;
1064 push @where_strings, 'items.homebranch = ?';
1065 push @bind_params, $branch;
1069 push @where_strings, 'biblioitems.itemtype = ?';
1070 push @bind_params, $itemtype;
1073 if ( $ignoreissued) {
1074 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1075 push @where_strings, 'issues.date_due IS NULL';
1078 if ( @where_strings ) {
1080 $query .= join ' AND ', @where_strings;
1082 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1083 my $sth = $dbh->prepare($query);
1084 $sth->execute( @bind_params );
1088 while ( my $row = $sth->fetchrow_hashref ) {
1089 $offset-- if ($offset);
1090 $row->{datelastseen}=format_date($row->{datelastseen});
1091 if ( ( !$offset ) && $size ) {
1092 push @results, $row;
1099 =head2 GetItemsCount
1102 $count = &GetItemsCount( $biblionumber);
1106 This function return count of item with $biblionumber
1111 my ( $biblionumber ) = @_;
1112 my $dbh = C4::Context->dbh;
1113 my $query = "SELECT count(*)
1115 WHERE biblionumber=?";
1116 my $sth = $dbh->prepare($query);
1117 $sth->execute($biblionumber);
1118 my $count = $sth->fetchrow;
1122 =head2 GetItemInfosOf
1126 GetItemInfosOf(@itemnumbers);
1132 sub GetItemInfosOf {
1133 my @itemnumbers = @_;
1138 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1140 return get_infos_of( $query, 'itemnumber' );
1143 =head2 GetItemsByBiblioitemnumber
1147 GetItemsByBiblioitemnumber($biblioitemnumber);
1151 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1152 Called by C<C4::XISBN>
1156 sub GetItemsByBiblioitemnumber {
1157 my ( $bibitem ) = @_;
1158 my $dbh = C4::Context->dbh;
1159 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1160 # Get all items attached to a biblioitem
1163 $sth->execute($bibitem) || die $sth->errstr;
1164 while ( my $data = $sth->fetchrow_hashref ) {
1165 # Foreach item, get circulation information
1166 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1167 WHERE itemnumber = ?
1168 AND issues.borrowernumber = borrowers.borrowernumber"
1170 $sth2->execute( $data->{'itemnumber'} );
1171 if ( my $data2 = $sth2->fetchrow_hashref ) {
1172 # if item is out, set the due date and who it is out too
1173 $data->{'date_due'} = $data2->{'date_due'};
1174 $data->{'cardnumber'} = $data2->{'cardnumber'};
1175 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1178 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1179 $data->{'date_due'} = '';
1181 # Find the last 3 people who borrowed this item.
1182 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1183 AND old_issues.borrowernumber = borrowers.borrowernumber
1184 ORDER BY returndate desc,timestamp desc LIMIT 3";
1185 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1186 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1188 while ( my $data2 = $sth2->fetchrow_hashref ) {
1189 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1190 $data->{"card$i2"} = $data2->{'cardnumber'};
1191 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1194 push(@results,$data);
1203 @results = GetItemsInfo($biblionumber, $type);
1207 Returns information about books with the given biblionumber.
1209 C<$type> may be either C<intra> or anything else. If it is not set to
1210 C<intra>, then the search will exclude lost, very overdue, and
1213 C<GetItemsInfo> returns a list of references-to-hash. Each element
1214 contains a number of keys. Most of them are table items from the
1215 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1216 Koha database. Other keys include:
1220 =item C<$data-E<gt>{branchname}>
1222 The name (not the code) of the branch to which the book belongs.
1224 =item C<$data-E<gt>{datelastseen}>
1226 This is simply C<items.datelastseen>, except that while the date is
1227 stored in YYYY-MM-DD format in the database, here it is converted to
1228 DD/MM/YYYY format. A NULL date is returned as C<//>.
1230 =item C<$data-E<gt>{datedue}>
1232 =item C<$data-E<gt>{class}>
1234 This is the concatenation of C<biblioitems.classification>, the book's
1235 Dewey code, and C<biblioitems.subclass>.
1237 =item C<$data-E<gt>{ocount}>
1239 I think this is the number of copies of the book available.
1241 =item C<$data-E<gt>{order}>
1243 If this is set, it is set to C<One Order>.
1250 my ( $biblionumber, $type ) = @_;
1251 my $dbh = C4::Context->dbh;
1252 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1258 biblioitems.itemtype,
1261 biblioitems.publicationyear,
1262 biblioitems.publishercode,
1263 biblioitems.volumedate,
1264 biblioitems.volumedesc,
1267 items.notforloan as itemnotforloan,
1268 itemtypes.description
1270 LEFT JOIN branches ON items.homebranch = branches.branchcode
1271 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1272 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1273 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1274 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1275 $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1276 my $sth = $dbh->prepare($query);
1277 $sth->execute($biblionumber);
1282 my $isth = $dbh->prepare(
1283 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1284 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1285 WHERE itemnumber = ?"
1287 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1288 while ( my $data = $sth->fetchrow_hashref ) {
1291 $isth->execute( $data->{'itemnumber'} );
1292 if ( my $idata = $isth->fetchrow_hashref ) {
1293 $data->{borrowernumber} = $idata->{borrowernumber};
1294 $data->{cardnumber} = $idata->{cardnumber};
1295 $data->{surname} = $idata->{surname};
1296 $data->{firstname} = $idata->{firstname};
1297 $datedue = $idata->{'date_due'};
1298 if (C4::Context->preference("IndependantBranches")){
1299 my $userenv = C4::Context->userenv;
1300 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1301 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1305 if ( $data->{'serial'}) {
1306 $ssth->execute($data->{'itemnumber'}) ;
1307 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1310 if ( $datedue eq '' ) {
1311 my ( $restype, $reserves ) =
1312 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1313 # Previous conditional check with if ($restype) is not needed because a true
1314 # result for one item will result in subsequent items defaulting to this true
1316 $count_reserves = $restype;
1318 #get branch information.....
1319 my $bsth = $dbh->prepare(
1320 "SELECT * FROM branches WHERE branchcode = ?
1323 $bsth->execute( $data->{'holdingbranch'} );
1324 if ( my $bdata = $bsth->fetchrow_hashref ) {
1325 $data->{'branchname'} = $bdata->{'branchname'};
1327 $data->{'datedue'} = $datedue;
1328 $data->{'count_reserves'} = $count_reserves;
1330 # get notforloan complete status if applicable
1331 my $sthnflstatus = $dbh->prepare(
1332 'SELECT authorised_value
1333 FROM marc_subfield_structure
1334 WHERE kohafield="items.notforloan"
1338 $sthnflstatus->execute;
1339 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1340 if ($authorised_valuecode) {
1341 $sthnflstatus = $dbh->prepare(
1342 "SELECT lib FROM authorised_values
1344 AND authorised_value=?"
1346 $sthnflstatus->execute( $authorised_valuecode,
1347 $data->{itemnotforloan} );
1348 my ($lib) = $sthnflstatus->fetchrow;
1349 $data->{notforloanvalue} = $lib;
1351 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1353 # my stack procedures
1354 my $stackstatus = $dbh->prepare(
1355 'SELECT authorised_value
1356 FROM marc_subfield_structure
1357 WHERE kohafield="items.stack"
1360 $stackstatus->execute;
1362 ($authorised_valuecode) = $stackstatus->fetchrow;
1363 if ($authorised_valuecode) {
1364 $stackstatus = $dbh->prepare(
1366 FROM authorised_values
1368 AND authorised_value=?
1371 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1372 my ($lib) = $stackstatus->fetchrow;
1373 $data->{stack} = $lib;
1375 # Find the last 3 people who borrowed this item.
1376 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1377 WHERE itemnumber = ?
1378 AND old_issues.borrowernumber = borrowers.borrowernumber
1379 ORDER BY returndate DESC
1381 $sth2->execute($data->{'itemnumber'});
1383 while (my $data2 = $sth2->fetchrow_hashref()) {
1384 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1385 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1386 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1390 $results[$i] = $data;
1394 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1400 =head2 GetLastAcquisitions
1404 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 'itemtypes' => ('BK','BD')}, 10);
1410 sub GetLastAcquisitions {
1411 my ($data,$max) = @_;
1413 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1415 my $number_of_branches = @{$data->{branches}};
1416 my $number_of_itemtypes = @{$data->{itemtypes}};
1419 my @where = ('WHERE 1 ');
1420 $number_of_branches and push @where
1421 , 'AND holdingbranch IN ('
1422 , join(',', ('?') x $number_of_branches )
1426 $number_of_itemtypes and push @where
1427 , "AND $itemtype IN ("
1428 , join(',', ('?') x $number_of_itemtypes )
1432 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1433 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1434 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1436 GROUP BY biblio.biblionumber
1437 ORDER BY dateaccessioned DESC LIMIT $max";
1439 my $dbh = C4::Context->dbh;
1440 my $sth = $dbh->prepare($query);
1442 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1445 while( my $row = $sth->fetchrow_hashref){
1446 push @results, {date => $row->{dateaccessioned}
1447 , biblionumber => $row->{biblionumber}
1448 , title => $row->{title}};
1454 =head2 get_itemnumbers_of
1458 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1462 Given a list of biblionumbers, return the list of corresponding itemnumbers
1463 for each biblionumber.
1465 Return a reference on a hash where keys are biblionumbers and values are
1466 references on array of itemnumbers.
1470 sub get_itemnumbers_of {
1471 my @biblionumbers = @_;
1473 my $dbh = C4::Context->dbh;
1479 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1481 my $sth = $dbh->prepare($query);
1482 $sth->execute(@biblionumbers);
1486 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1487 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1490 return \%itemnumbers_of;
1493 =head2 GetItemnumberFromBarcode
1497 $result = GetItemnumberFromBarcode($barcode);
1503 sub GetItemnumberFromBarcode {
1505 my $dbh = C4::Context->dbh;
1508 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1509 $rq->execute($barcode);
1510 my ($result) = $rq->fetchrow;
1514 =head3 get_item_authorised_values
1516 find the types and values for all authorised values assigned to this item.
1521 returns: a hashref malling the authorised value to the value set for this itemnumber
1523 $authorised_values = {
1529 'RESTRICTED' => undef,
1532 'branches' => 'CPL',
1533 'cn_source' => undef,
1534 'itemtypes' => 'SER',
1537 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1541 sub get_item_authorised_values {
1542 my $itemnumber = shift;
1544 # assume that these entries in the authorised_value table are item level.
1545 my $query = q(SELECT distinct authorised_value, kohafield
1546 FROM marc_subfield_structure
1547 WHERE kohafield like 'item%'
1548 AND authorised_value != '' );
1550 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1551 my $iteminfo = GetItem( $itemnumber );
1552 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1554 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1555 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1556 $field =~ s/^items\.//;
1557 if ( exists $iteminfo->{ $field } ) {
1558 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1561 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1565 =head3 get_authorised_value_images
1567 find a list of icons that are appropriate for display based on the
1568 authorised values for a biblio.
1570 parameters: listref of authorised values, such as comes from
1571 get_item_authorised_values or
1572 from C4::Biblio::get_biblio_authorised_values
1574 returns: listref of hashrefs for each image. Each hashref looks like
1577 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1582 Notes: Currently, I put on the full path to the images on the staff
1583 side. This should either be configurable or not done at all. Since I
1584 have to deal with 'intranet' or 'opac' in
1585 get_biblio_authorised_values, perhaps I should be passing it in.
1589 sub get_authorised_value_images {
1590 my $authorised_values = shift;
1594 my $authorised_value_list = GetAuthorisedValues();
1595 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1596 foreach my $this_authorised_value ( @$authorised_value_list ) {
1597 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1598 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1599 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1600 if ( defined $this_authorised_value->{'imageurl'} ) {
1601 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1602 label => $this_authorised_value->{'lib'},
1603 category => $this_authorised_value->{'category'},
1604 value => $this_authorised_value->{'authorised_value'}, };
1609 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1614 =head1 LIMITED USE FUNCTIONS
1616 The following functions, while part of the public API,
1617 are not exported. This is generally because they are
1618 meant to be used by only one script for a specific
1619 purpose, and should not be used in any other context
1620 without careful thought.
1628 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1632 Returns MARC::Record of the item passed in parameter.
1633 This function is meant for use only in C<cataloguing/additem.pl>,
1634 where it is needed to support that script's MARC-like
1640 my ( $biblionumber, $itemnumber ) = @_;
1642 # GetMarcItem has been revised so that it does the following:
1643 # 1. Gets the item information from the items table.
1644 # 2. Converts it to a MARC field for storage in the bib record.
1646 # The previous behavior was:
1647 # 1. Get the bib record.
1648 # 2. Return the MARC tag corresponding to the item record.
1650 # The difference is that one treats the items row as authoritative,
1651 # while the other treats the MARC representation as authoritative
1652 # under certain circumstances.
1654 my $itemrecord = GetItem($itemnumber);
1656 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1657 # Also, don't emit a subfield if the underlying field is blank.
1660 return Item2Marc($itemrecord,$biblionumber);
1664 my ($itemrecord,$biblionumber)=@_;
1667 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1668 } keys %{ $itemrecord }
1670 my $itemmarc = TransformKohaToMarc($mungeditem);
1671 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1673 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1674 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1675 foreach my $field ($itemmarc->field($itemtag)){
1676 $field->add_subfields(@$unlinked_item_subfields);
1682 =head1 PRIVATE FUNCTIONS AND VARIABLES
1684 The following functions are not meant to be called
1685 directly, but are documented in order to explain
1686 the inner workings of C<C4::Items>.
1690 =head2 %derived_columns
1692 This hash keeps track of item columns that
1693 are strictly derived from other columns in
1694 the item record and are not meant to be set
1697 Each key in the hash should be the name of a
1698 column (as named by TransformMarcToKoha). Each
1699 value should be hashref whose keys are the
1700 columns on which the derived column depends. The
1701 hashref should also contain a 'BUILDER' key
1702 that is a reference to a sub that calculates
1707 my %derived_columns = (
1708 'items.cn_sort' => {
1709 'itemcallnumber' => 1,
1710 'items.cn_source' => 1,
1711 'BUILDER' => \&_calc_items_cn_sort,
1715 =head2 _set_derived_columns_for_add
1719 _set_derived_column_for_add($item);
1723 Given an item hash representing a new item to be added,
1724 calculate any derived columns. Currently the only
1725 such column is C<items.cn_sort>.
1729 sub _set_derived_columns_for_add {
1732 foreach my $column (keys %derived_columns) {
1733 my $builder = $derived_columns{$column}->{'BUILDER'};
1734 my $source_values = {};
1735 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1736 next if $source_column eq 'BUILDER';
1737 $source_values->{$source_column} = $item->{$source_column};
1739 $builder->($item, $source_values);
1743 =head2 _set_derived_columns_for_mod
1747 _set_derived_column_for_mod($item);
1751 Given an item hash representing a new item to be modified.
1752 calculate any derived columns. Currently the only
1753 such column is C<items.cn_sort>.
1755 This routine differs from C<_set_derived_columns_for_add>
1756 in that it needs to handle partial item records. In other
1757 words, the caller of C<ModItem> may have supplied only one
1758 or two columns to be changed, so this function needs to
1759 determine whether any of the columns to be changed affect
1760 any of the derived columns. Also, if a derived column
1761 depends on more than one column, but the caller is not
1762 changing all of then, this routine retrieves the unchanged
1763 values from the database in order to ensure a correct
1768 sub _set_derived_columns_for_mod {
1771 foreach my $column (keys %derived_columns) {
1772 my $builder = $derived_columns{$column}->{'BUILDER'};
1773 my $source_values = {};
1774 my %missing_sources = ();
1775 my $must_recalc = 0;
1776 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1777 next if $source_column eq 'BUILDER';
1778 if (exists $item->{$source_column}) {
1780 $source_values->{$source_column} = $item->{$source_column};
1782 $missing_sources{$source_column} = 1;
1786 foreach my $source_column (keys %missing_sources) {
1787 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1789 $builder->($item, $source_values);
1794 =head2 _do_column_fixes_for_mod
1798 _do_column_fixes_for_mod($item);
1802 Given an item hashref containing one or more
1803 columns to modify, fix up certain values.
1804 Specifically, set to 0 any passed value
1805 of C<notforloan>, C<damaged>, C<itemlost>, or
1806 C<wthdrawn> that is either undefined or
1807 contains the empty string.
1811 sub _do_column_fixes_for_mod {
1814 if (exists $item->{'notforloan'} and
1815 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1816 $item->{'notforloan'} = 0;
1818 if (exists $item->{'damaged'} and
1819 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1820 $item->{'damaged'} = 0;
1822 if (exists $item->{'itemlost'} and
1823 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1824 $item->{'itemlost'} = 0;
1826 if (exists $item->{'wthdrawn'} and
1827 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1828 $item->{'wthdrawn'} = 0;
1830 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1831 $item->{'permanent_location'} = $item->{'location'};
1835 =head2 _get_single_item_column
1839 _get_single_item_column($column, $itemnumber);
1843 Retrieves the value of a single column from an C<items>
1844 row specified by C<$itemnumber>.
1848 sub _get_single_item_column {
1850 my $itemnumber = shift;
1852 my $dbh = C4::Context->dbh;
1853 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1854 $sth->execute($itemnumber);
1855 my ($value) = $sth->fetchrow();
1859 =head2 _calc_items_cn_sort
1863 _calc_items_cn_sort($item, $source_values);
1867 Helper routine to calculate C<items.cn_sort>.
1871 sub _calc_items_cn_sort {
1873 my $source_values = shift;
1875 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1878 =head2 _set_defaults_for_add
1882 _set_defaults_for_add($item_hash);
1886 Given an item hash representing an item to be added, set
1887 correct default values for columns whose default value
1888 is not handled by the DBMS. This includes the following
1895 C<items.dateaccessioned>
1917 sub _set_defaults_for_add {
1919 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1920 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1923 =head2 _koha_new_item
1927 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1931 Perform the actual insert into the C<items> table.
1935 sub _koha_new_item
{
1936 my ( $item, $barcode ) = @_;
1937 my $dbh=C4
::Context
->dbh;
1940 "INSERT INTO items SET
1942 biblioitemnumber = ?,
1944 dateaccessioned = ?,
1948 replacementprice = ?,
1949 replacementpricedate = NOW(),
1950 datelastborrowed = ?,
1951 datelastseen = NOW(),
1974 more_subfields_xml = ?,
1977 my $sth = $dbh->prepare($query);
1979 $item->{'biblionumber'},
1980 $item->{'biblioitemnumber'},
1982 $item->{'dateaccessioned'},
1983 $item->{'booksellerid'},
1984 $item->{'homebranch'},
1986 $item->{'replacementprice'},
1987 $item->{datelastborrowed
},
1989 $item->{'notforloan'},
1991 $item->{'itemlost'},
1992 $item->{'wthdrawn'},
1993 $item->{'itemcallnumber'},
1994 $item->{'restricted'},
1995 $item->{'itemnotes'},
1996 $item->{'holdingbranch'},
1998 $item->{'location'},
2001 $item->{'renewals'},
2002 $item->{'reserves'},
2003 $item->{'items.cn_source'},
2004 $item->{'items.cn_sort'},
2007 $item->{'materials'},
2009 $item->{'enumchron'},
2010 $item->{'more_subfields_xml'},
2011 $item->{'copynumber'},
2013 my $itemnumber = $dbh->{'mysql_insertid'};
2014 if ( defined $sth->errstr ) {
2015 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2017 return ( $itemnumber, $error );
2020 =head2 MoveItemFromBiblio
2024 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2028 Moves an item from a biblio to another
2030 Returns undef if the move failed or the biblionumber of the destination record otherwise
2032 sub MoveItemFromBiblio
{
2033 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2034 my $dbh = C4
::Context
->dbh;
2035 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2036 $sth->execute( $tobiblio );
2037 my ( $tobiblioitem ) = $sth->fetchrow();
2038 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2039 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2043 my $frameworkcode = GetFrameworkCode
($frombiblio);
2045 # Getting marc field for itemnumber
2046 my ($itemtag, $itemsubfield) = GetMarcFromKohaField
('items.itemnumber', $frameworkcode);
2048 # Getting the record we want to move the item from
2049 my $record = GetMarcBiblio
($frombiblio);
2051 # The item we want to move
2055 foreach my $fielditem ($record->field($itemtag)){
2056 # If it is the item we want to move
2057 if ($fielditem->subfield($itemsubfield) == $itemnumber) {
2060 # Then delete it from the record
2061 $record->delete_field($fielditem)
2065 # If we found an item (should always true, except in case of database-marcxml inconsistency)
2068 # Checking if the item we want to move is in an order
2069 my $order = GetOrderFromItemnumber
($itemnumber);
2071 # Replacing the biblionumber within the order if necessary
2072 $order->{'biblionumber'} = $tobiblio;
2076 # Saving the modification
2077 ModBiblioMarc
($record, $frombiblio, $frameworkcode);
2079 # Getting the record we want to move the item to
2080 $record = GetMarcBiblio
($tobiblio);
2082 # Inserting the previously saved item
2083 $record->insert_fields_ordered($item);
2085 # Saving the modification
2086 ModBiblioMarc
($record, $tobiblio, $frameworkcode);
2100 DelItemCheck($dbh, $biblionumber, $itemnumber);
2104 Exported function (core API) for deleting an item record in Koha if there no current issue.
2109 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2112 # check that there is no issue on this item before deletion.
2113 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2114 $sth->execute($itemnumber);
2116 my $onloan=$sth->fetchrow;
2119 $error = "book_on_loan"
2121 # check it doesnt have a waiting reserve
2122 $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
2123 $sth->execute($itemnumber);
2124 my $reserve=$sth->fetchrow;
2126 $error = "book_reserved";
2128 DelItem
($dbh, $biblionumber, $itemnumber);
2135 =head2 _koha_modify_item
2139 my ($itemnumber,$error) =_koha_modify_item( $item );
2143 Perform the actual update of the C<items> row. Note that this
2144 routine accepts a hashref specifying the columns to update.
2148 sub _koha_modify_item
{
2150 my $dbh=C4
::Context
->dbh;
2153 my $query = "UPDATE items SET ";
2155 for my $key ( keys %$item ) {
2157 push @bind, $item->{$key};
2160 $query .= " WHERE itemnumber=?";
2161 push @bind, $item->{'itemnumber'};
2162 my $sth = C4
::Context
->dbh->prepare($query);
2163 $sth->execute(@bind);
2164 if ( C4
::Context
->dbh->errstr ) {
2165 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2168 return ($item->{'itemnumber'},$error);
2171 =head2 _koha_delete_item
2175 _koha_delete_item( $dbh, $itemnum );
2179 Internal function to delete an item record from the koha tables
2183 sub _koha_delete_item
{
2184 my ( $dbh, $itemnum ) = @_;
2186 # save the deleted item to deleteditems table
2187 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2188 $sth->execute($itemnum);
2189 my $data = $sth->fetchrow_hashref();
2190 my $query = "INSERT INTO deleteditems SET ";
2192 foreach my $key ( keys %$data ) {
2193 $query .= "$key = ?,";
2194 push( @bind, $data->{$key} );
2197 $sth = $dbh->prepare($query);
2198 $sth->execute(@bind);
2200 # delete from items table
2201 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2202 $sth->execute($itemnum);
2206 =head2 _marc_from_item_hash
2210 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2214 Given an item hash representing a complete item record,
2215 create a C<MARC::Record> object containing an embedded
2216 tag representing that item.
2218 The third, optional parameter C<$unlinked_item_subfields> is
2219 an arrayref of subfields (not mapped to C<items> fields per the
2220 framework) to be added to the MARC representation
2225 sub _marc_from_item_hash
{
2227 my $frameworkcode = shift;
2228 my $unlinked_item_subfields;
2230 $unlinked_item_subfields = shift;
2233 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2234 # Also, don't emit a subfield if the underlying field is blank.
2235 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2236 (/^items\./ ?
($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2237 : () } keys %{ $item } };
2239 my $item_marc = MARC
::Record
->new();
2240 foreach my $item_field (keys %{ $mungeditem }) {
2241 my ($tag, $subfield) = GetMarcFromKohaField
($item_field, $frameworkcode);
2242 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2243 if (my $field = $item_marc->field($tag)) {
2244 $field->add_subfields($subfield => $mungeditem->{$item_field});
2246 my $add_subfields = [];
2247 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2248 $add_subfields = $unlinked_item_subfields;
2250 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @
$add_subfields);
2257 =head2 _add_item_field_to_biblio
2261 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2265 Adds the fields from a MARC record containing the
2266 representation of a Koha item record to the MARC
2267 biblio record. The input C<$item_marc> record
2268 is expect to contain just one field, the embedded
2269 item information field.
2273 sub _add_item_field_to_biblio
{
2274 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2276 my $biblio_marc = GetMarcBiblio
($biblionumber);
2277 foreach my $field ($item_marc->fields()) {
2278 $biblio_marc->append_fields($field);
2281 ModBiblioMarc
($biblio_marc, $biblionumber, $frameworkcode);
2284 =head2 _replace_item_field_in_biblio
2288 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2292 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2293 representation of the item, examine the biblio MARC
2294 for the corresponding tag for that item and
2295 replace it with the tag from C<$item_marc>.
2299 sub _replace_item_field_in_biblio
{
2300 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2301 my $dbh = C4
::Context
->dbh;
2303 # get complete MARC record & replace the item field by the new one
2304 my $completeRecord = GetMarcBiblio
($biblionumber);
2305 my ($itemtag,$itemsubfield) = GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
2306 my $itemField = $ItemRecord->field($itemtag);
2307 my @items = $completeRecord->field($itemtag);
2310 if ($_->subfield($itemsubfield) eq $itemnumber) {
2311 $_->replace_with($itemField);
2317 # If we haven't found the matching field,
2318 # just add it. However, this means that
2319 # there is likely a bug.
2320 $completeRecord->append_fields($itemField);
2324 ModBiblioMarc
($completeRecord, $biblionumber, $frameworkcode);
2327 =head2 _repack_item_errors
2329 Add an error message hash generated by C<CheckItemPreSave>
2330 to a list of errors.
2334 sub _repack_item_errors
{
2335 my $item_sequence_num = shift;
2336 my $item_ref = shift;
2337 my $error_ref = shift;
2339 my @repacked_errors = ();
2341 foreach my $error_code (sort keys %{ $error_ref }) {
2342 my $repacked_error = {};
2343 $repacked_error->{'item_sequence'} = $item_sequence_num;
2344 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ?
$item_ref->{'barcode'} : '';
2345 $repacked_error->{'error_code'} = $error_code;
2346 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2347 push @repacked_errors, $repacked_error;
2350 return @repacked_errors;
2353 =head2 _get_unlinked_item_subfields
2357 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2363 sub _get_unlinked_item_subfields
{
2364 my $original_item_marc = shift;
2365 my $frameworkcode = shift;
2367 my $marcstructure = GetMarcStructure
(1, $frameworkcode);
2369 # assume that this record has only one field, and that that
2370 # field contains only the item information
2372 my @fields = $original_item_marc->fields();
2373 if ($#fields > -1) {
2374 my $field = $fields[0];
2375 my $tag = $field->tag();
2376 foreach my $subfield ($field->subfields()) {
2377 if (defined $subfield->[1] and
2378 $subfield->[1] ne '' and
2379 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2380 push @
$subfields, $subfield->[0] => $subfield->[1];
2387 =head2 _get_unlinked_subfields_xml
2391 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2397 sub _get_unlinked_subfields_xml
{
2398 my $unlinked_item_subfields = shift;
2401 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2402 my $marc = MARC
::Record
->new();
2403 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2404 # used in the framework
2405 $marc->append_fields(MARC
::Field
->new('999', ' ', ' ', @
$unlinked_item_subfields));
2406 $marc->encoding("UTF-8");
2407 $xml = $marc->as_xml("USMARC");
2413 =head2 _parse_unlinked_item_subfields_from_xml
2417 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2423 sub _parse_unlinked_item_subfields_from_xml
{
2426 return unless defined $xml and $xml ne "";
2427 my $marc = MARC
::Record
->new_from_xml(StripNonXmlChars
($xml),'UTF-8');
2428 my $unlinked_subfields = [];
2429 my @fields = $marc->fields();
2430 if ($#fields > -1) {
2431 foreach my $subfield ($fields[0]->subfields()) {
2432 push @
$unlinked_subfields, $subfield->[0] => $subfield->[1];
2435 return $unlinked_subfields;