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/;
34 use vars
qw($VERSION @ISA @EXPORT);
40 @ISA = qw( Exporter );
63 GetItemsByBiblioitemnumber
66 GetItemnumberFromBarcode
77 C4::Items - item management functions
81 This module contains an API for manipulating item
82 records in Koha, and is used by cataloguing, circulation,
83 acquisitions, and serials management.
85 A Koha item record is stored in two places: the
86 items table and embedded in a MARC tag in the XML
87 version of the associated bib record in C<biblioitems.marcxml>.
88 This is done to allow the item information to be readily
89 indexed (e.g., by Zebra), but means that each item
90 modification transaction must keep the items table
91 and the MARC XML in sync at all times.
93 Consequently, all code that creates, modifies, or deletes
94 item records B<must> use an appropriate function from
95 C<C4::Items>. If no existing function is suitable, it is
96 better to add one to C<C4::Items> than to use add
97 one-off SQL statements to add or modify items.
99 The items table will be considered authoritative. In other
100 words, if there is ever a discrepancy between the items
101 table and the MARC XML, the items table should be considered
104 =head1 HISTORICAL NOTE
106 Most of the functions in C<C4::Items> were originally in
107 the C<C4::Biblio> module.
109 =head1 CORE EXPORTED FUNCTIONS
111 The following functions are meant for use by users
120 $item = GetItem($itemnumber,$barcode,$serial);
124 Return item information, for a given itemnumber or barcode.
125 The return value is a hashref mapping item column
126 names to values. If C<$serial> is true, include serial publication data.
131 my ($itemnumber,$barcode, $serial) = @_;
132 my $dbh = C4
::Context
->dbh;
135 my $sth = $dbh->prepare("
137 WHERE itemnumber = ?");
138 $sth->execute($itemnumber);
139 $data = $sth->fetchrow_hashref;
141 my $sth = $dbh->prepare("
145 $sth->execute($barcode);
146 $data = $sth->fetchrow_hashref;
149 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
150 $ssth->execute($data->{'itemnumber'}) ;
151 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
152 warn $data->{'serialseq'} , $data->{'publisheddate'};
154 #if we don't have an items.itype, use biblioitems.itemtype.
155 if( ! $data->{'itype'} ) {
156 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
157 $sth->execute($data->{'biblionumber'});
158 ($data->{'itype'}) = $sth->fetchrow_array;
167 CartToShelf($itemnumber);
171 Set the current shelving location of the item record
172 to its stored permanent shelving location. This is
173 primarily used to indicate when an item whose current
174 location is a special processing ('PROC') or shelving cart
175 ('CART') location is back in the stacks.
180 my ( $itemnumber ) = @_;
182 unless ( $itemnumber ) {
183 croak
"FAILED CartToShelf() - no itemnumber supplied";
186 my $item = GetItem
($itemnumber);
187 $item->{location
} = $item->{permanent_location
};
188 ModItem
($item, undef, $itemnumber);
191 =head2 AddItemFromMarc
195 my ($biblionumber, $biblioitemnumber, $itemnumber)
196 = AddItemFromMarc($source_item_marc, $biblionumber);
200 Given a MARC::Record object containing an embedded item
201 record and a biblionumber, create a new item record.
205 sub AddItemFromMarc
{
206 my ( $source_item_marc, $biblionumber ) = @_;
207 my $dbh = C4
::Context
->dbh;
209 # parse item hash from MARC
210 my $frameworkcode = GetFrameworkCode
( $biblionumber );
211 my $item = &TransformMarcToKoha
( $dbh, $source_item_marc, $frameworkcode );
212 my $unlinked_item_subfields = _get_unlinked_item_subfields
($source_item_marc, $frameworkcode);
213 return AddItem
($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
220 my ($biblionumber, $biblioitemnumber, $itemnumber)
221 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
225 Given a hash containing item column names as keys,
226 create a new Koha item record.
228 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
229 do not need to be supplied for general use; they exist
230 simply to allow them to be picked up from AddItemFromMarc.
232 The final optional parameter, C<$unlinked_item_subfields>, contains
233 an arrayref containing subfields present in the original MARC
234 representation of the item (e.g., from the item editor) that are
235 not mapped to C<items> columns directly but should instead
236 be stored in C<items.more_subfields_xml> and included in
237 the biblio items tag for display and indexing.
243 my $biblionumber = shift;
245 my $dbh = @_ ?
shift : C4
::Context
->dbh;
246 my $frameworkcode = @_ ?
shift : GetFrameworkCode
( $biblionumber );
247 my $unlinked_item_subfields;
249 $unlinked_item_subfields = shift
252 # needs old biblionumber and biblioitemnumber
253 $item->{'biblionumber'} = $biblionumber;
254 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
255 $sth->execute( $item->{'biblionumber'} );
256 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
258 _set_defaults_for_add
($item);
259 _set_derived_columns_for_add
($item);
260 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
261 # FIXME - checks here
262 unless ( $item->{itype
} ) { # default to biblioitem.itemtype if no itype
263 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
264 $itype_sth->execute( $item->{'biblionumber'} );
265 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
268 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
269 $item->{'itemnumber'} = $itemnumber;
271 # create MARC tag representing item and add to bib
272 my $new_item_marc = _marc_from_item_hash
($item, $frameworkcode, $unlinked_item_subfields);
273 _add_item_field_to_biblio
($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
275 logaction
("CATALOGUING", "ADD", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
277 return ($item->{biblionumber
}, $item->{biblioitemnumber
}, $itemnumber);
280 =head2 AddItemBatchFromMarc
284 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
288 Efficiently create item records from a MARC biblio record with
289 embedded item fields. This routine is suitable for batch jobs.
291 This API assumes that the bib record has already been
292 saved to the C<biblio> and C<biblioitems> tables. It does
293 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
294 are populated, but it will do so via a call to ModBibiloMarc.
296 The goal of this API is to have a similar effect to using AddBiblio
297 and AddItems in succession, but without inefficient repeated
298 parsing of the MARC XML bib record.
300 This function returns an arrayref of new itemsnumbers and an arrayref of item
301 errors encountered during the processing. Each entry in the errors
302 list is a hashref containing the following keys:
308 Sequence number of original item tag in the MARC record.
312 Item barcode, provide to assist in the construction of
313 useful error messages.
315 =item error_condition
317 Code representing the error condition. Can be 'duplicate_barcode',
318 'invalid_homebranch', or 'invalid_holdingbranch'.
320 =item error_information
322 Additional information appropriate to the error condition.
328 sub AddItemBatchFromMarc
{
329 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
331 my @itemnumbers = ();
333 my $dbh = C4
::Context
->dbh;
335 # loop through the item tags and start creating items
336 my @bad_item_fields = ();
337 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField
("items.itemnumber",'');
338 my $item_sequence_num = 0;
339 ITEMFIELD
: foreach my $item_field ($record->field($itemtag)) {
340 $item_sequence_num++;
341 # we take the item field and stick it into a new
342 # MARC record -- this is required so far because (FIXME)
343 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
344 # and there is no TransformMarcFieldToKoha
345 my $temp_item_marc = MARC
::Record
->new();
346 $temp_item_marc->append_fields($item_field);
348 # add biblionumber and biblioitemnumber
349 my $item = TransformMarcToKoha
( $dbh, $temp_item_marc, $frameworkcode, 'items' );
350 my $unlinked_item_subfields = _get_unlinked_item_subfields
($temp_item_marc, $frameworkcode);
351 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
352 $item->{'biblionumber'} = $biblionumber;
353 $item->{'biblioitemnumber'} = $biblioitemnumber;
355 # check for duplicate barcode
356 my %item_errors = CheckItemPreSave
($item);
358 push @errors, _repack_item_errors
($item_sequence_num, $item, \
%item_errors);
359 push @bad_item_fields, $item_field;
363 _set_defaults_for_add
($item);
364 _set_derived_columns_for_add
($item);
365 my ( $itemnumber, $error ) = _koha_new_item
( $item, $item->{barcode
} );
366 warn $error if $error;
367 push @itemnumbers, $itemnumber; # FIXME not checking error
368 $item->{'itemnumber'} = $itemnumber;
370 logaction
("CATALOGUING", "ADD", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
372 my $new_item_marc = _marc_from_item_hash
($item, $frameworkcode, $unlinked_item_subfields);
373 $item_field->replace_with($new_item_marc->field($itemtag));
376 # remove any MARC item fields for rejected items
377 foreach my $item_field (@bad_item_fields) {
378 $record->delete_field($item_field);
381 # update the MARC biblio
382 $biblionumber = ModBiblioMarc
( $record, $biblionumber, $frameworkcode );
384 return (\
@itemnumbers, \
@errors);
387 =head2 ModItemFromMarc
391 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
395 This function updates an item record based on a supplied
396 C<MARC::Record> object containing an embedded item field.
397 This API is meant for the use of C<additem.pl>; for
398 other purposes, C<ModItem> should be used.
400 This function uses the hash %default_values_for_mod_from_marc,
401 which contains default values for item fields to
402 apply when modifying an item. This is needed beccause
403 if an item field's value is cleared, TransformMarcToKoha
404 does not include the column in the
405 hash that's passed to ModItem, which without
406 use of this hash makes it impossible to clear
407 an item field's value. See bug 2466.
409 Note that only columns that can be directly
410 changed from the cataloging and serials
411 item editors are included in this hash.
415 my %default_values_for_mod_from_marc = (
417 booksellerid
=> undef,
419 'items.cn_source' => undef,
422 dateaccessioned
=> undef,
424 holdingbranch
=> undef,
426 itemcallnumber
=> undef,
435 replacementprice
=> undef,
436 replacementpricedate
=> undef,
443 sub ModItemFromMarc
{
444 my $item_marc = shift;
445 my $biblionumber = shift;
446 my $itemnumber = shift;
448 my $dbh = C4
::Context
->dbh;
449 my $frameworkcode = GetFrameworkCode
( $biblionumber );
450 my ($itemtag,$itemsubfield)=GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
452 my $localitemmarc=MARC
::Record
->new;
453 $localitemmarc->append_fields($item_marc->field($itemtag));
454 my $item = &TransformMarcToKoha
( $dbh, $item_marc, $frameworkcode ,'items');
455 foreach my $item_field (keys %default_values_for_mod_from_marc) {
456 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
458 my $unlinked_item_subfields = _get_unlinked_item_subfields
($item_marc, $frameworkcode);
460 return ModItem
($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
467 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
471 Change one or more columns in an item record and update
472 the MARC representation of the item.
474 The first argument is a hashref mapping from item column
475 names to the new values. The second and third arguments
476 are the biblionumber and itemnumber, respectively.
478 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
479 an arrayref containing subfields present in the original MARC
480 representation of the item (e.g., from the item editor) that are
481 not mapped to C<items> columns directly but should instead
482 be stored in C<items.more_subfields_xml> and included in
483 the biblio items tag for display and indexing.
485 If one of the changed columns is used to calculate
486 the derived value of a column such as C<items.cn_sort>,
487 this routine will perform the necessary calculation
494 my $biblionumber = shift;
495 my $itemnumber = shift;
497 # if $biblionumber is undefined, get it from the current item
498 unless (defined $biblionumber) {
499 $biblionumber = _get_single_item_column
('biblionumber', $itemnumber);
502 my $dbh = @_ ?
shift : C4
::Context
->dbh;
503 my $frameworkcode = @_ ?
shift : GetFrameworkCode
( $biblionumber );
505 my $unlinked_item_subfields;
507 $unlinked_item_subfields = shift;
508 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml
($unlinked_item_subfields);
511 $item->{'itemnumber'} = $itemnumber or return undef;
512 _set_derived_columns_for_mod
($item);
513 _do_column_fixes_for_mod
($item);
516 # attempt to change itemnumber
517 # attempt to change biblionumber (if we want
518 # an API to relink an item to a different bib,
519 # it should be a separate function)
522 _koha_modify_item
($item);
524 # update biblio MARC XML
525 my $whole_item = GetItem
($itemnumber) or die "FAILED GetItem($itemnumber)";
527 unless (defined $unlinked_item_subfields) {
528 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml
($whole_item->{'more_subfields_xml'});
530 my $new_item_marc = _marc_from_item_hash
($whole_item, $frameworkcode, $unlinked_item_subfields)
531 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
533 _replace_item_field_in_biblio
($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
534 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
535 logaction
("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4
::Context
->preference("CataloguingLog");
538 =head2 ModItemTransfer
542 ModItemTransfer($itenumber, $frombranch, $tobranch);
546 Marks an item as being transferred from one branch
551 sub ModItemTransfer
{
552 my ( $itemnumber, $frombranch, $tobranch ) = @_;
554 my $dbh = C4
::Context
->dbh;
556 #new entry in branchtransfers....
557 my $sth = $dbh->prepare(
558 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
559 VALUES (?, ?, NOW(), ?)");
560 $sth->execute($itemnumber, $frombranch, $tobranch);
562 ModItem
({ holdingbranch
=> $tobranch }, undef, $itemnumber);
563 ModDateLastSeen
($itemnumber);
567 =head2 ModDateLastSeen
571 ModDateLastSeen($itemnum);
575 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
576 C<$itemnum> is the item number
580 sub ModDateLastSeen
{
581 my ($itemnumber) = @_;
583 my $today = C4
::Dates
->new();
584 ModItem
({ itemlost
=> 0, datelastseen
=> $today->output("iso") }, undef, $itemnumber);
591 DelItem($biblionumber, $itemnumber);
595 Exported function (core API) for deleting an item record in Koha.
600 my ( $dbh, $biblionumber, $itemnumber ) = @_;
602 # FIXME check the item has no current issues
604 _koha_delete_item
( $dbh, $itemnumber );
606 # get the MARC record
607 my $record = GetMarcBiblio
($biblionumber);
608 my $frameworkcode = GetFrameworkCode
($biblionumber);
611 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
612 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
614 #search item field code
615 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
616 my @fields = $record->field($itemtag);
618 # delete the item specified
619 foreach my $field (@fields) {
620 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
621 $record->delete_field($field);
624 &ModBiblioMarc
( $record, $biblionumber, $frameworkcode );
625 logaction
("CATALOGUING", "DELETE", $itemnumber, "item") if C4
::Context
->preference("CataloguingLog");
628 =head2 CheckItemPreSave
632 my $item_ref = TransformMarcToKoha($marc, 'items');
634 my %errors = CheckItemPreSave($item_ref);
635 if (exists $errors{'duplicate_barcode'}) {
636 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
637 } elsif (exists $errors{'invalid_homebranch'}) {
638 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
639 } elsif (exists $errors{'invalid_holdingbranch'}) {
640 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
647 Given a hashref containing item fields, determine if it can be
648 inserted or updated in the database. Specifically, checks for
649 database integrity issues, and returns a hash containing any
650 of the following keys, if applicable.
654 =item duplicate_barcode
656 Barcode, if it duplicates one already found in the database.
658 =item invalid_homebranch
660 Home branch, if not defined in branches table.
662 =item invalid_holdingbranch
664 Holding branch, if not defined in branches table.
668 This function does NOT implement any policy-related checks,
669 e.g., whether current operator is allowed to save an
670 item that has a given branch code.
674 sub CheckItemPreSave
{
675 my $item_ref = shift;
679 # check for duplicate barcode
680 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
681 my $existing_itemnumber = GetItemnumberFromBarcode
($item_ref->{'barcode'});
682 if ($existing_itemnumber) {
683 if (!exists $item_ref->{'itemnumber'} # new item
684 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
685 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
690 # check for valid home branch
691 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
692 my $branch_name = GetBranchName
($item_ref->{'homebranch'});
693 unless (defined $branch_name) {
694 # relies on fact that branches.branchname is a non-NULL column,
695 # so GetBranchName returns undef only if branch does not exist
696 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
700 # check for valid holding branch
701 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
702 my $branch_name = GetBranchName
($item_ref->{'holdingbranch'});
703 unless (defined $branch_name) {
704 # relies on fact that branches.branchname is a non-NULL column,
705 # so GetBranchName returns undef only if branch does not exist
706 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
714 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
716 The following functions provide various ways of
717 getting an item record, a set of item records, or
718 lists of authorized values for certain item fields.
720 Some of the functions in this group are candidates
721 for refactoring -- for example, some of the code
722 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
723 has copy-and-paste work.
731 $itemstatushash = GetItemStatus($fwkcode);
735 Returns a list of valid values for the
736 C<items.notforloan> field.
738 NOTE: does B<not> return an individual item's
741 Can be MARC dependant.
743 But basically could be can be loan or not
744 Create a status selector with the following code
746 =head3 in PERL SCRIPT
750 my $itemstatushash = getitemstatus;
752 foreach my $thisstatus (keys %$itemstatushash) {
753 my %row =(value => $thisstatus,
754 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
756 push @itemstatusloop, \%row;
758 $template->param(statusloop=>\@itemstatusloop);
766 <select name="statusloop">
767 <option value="">Default</option>
768 <!-- TMPL_LOOP name="statusloop" -->
769 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
779 # returns a reference to a hash of references to status...
782 my $dbh = C4
::Context
->dbh;
784 $fwk = '' unless ($fwk);
785 my ( $tag, $subfield ) =
786 GetMarcFromKohaField
( "items.notforloan", $fwk );
787 if ( $tag and $subfield ) {
790 "SELECT authorised_value
791 FROM marc_subfield_structure
797 $sth->execute( $tag, $subfield, $fwk );
798 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
801 "SELECT authorised_value,lib
802 FROM authorised_values
807 $authvalsth->execute($authorisedvaluecat);
808 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
809 $itemstatus{$authorisedvalue} = $lib;
823 $itemstatus{"1"} = "Not For Loan";
827 =head2 GetItemLocation
831 $itemlochash = GetItemLocation($fwk);
835 Returns a list of valid values for the
836 C<items.location> field.
838 NOTE: does B<not> return an individual item's
841 where fwk stands for an optional framework code.
842 Create a location selector with the following code
844 =head3 in PERL SCRIPT
848 my $itemlochash = getitemlocation;
850 foreach my $thisloc (keys %$itemlochash) {
851 my $selected = 1 if $thisbranch eq $branch;
852 my %row =(locval => $thisloc,
853 selected => $selected,
854 locname => $itemlochash->{$thisloc},
856 push @itemlocloop, \%row;
858 $template->param(itemlocationloop => \@itemlocloop);
866 <select name="location">
867 <option value="">Default</option>
868 <!-- TMPL_LOOP name="itemlocationloop" -->
869 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
877 sub GetItemLocation
{
879 # returns a reference to a hash of references to location...
882 my $dbh = C4
::Context
->dbh;
884 $fwk = '' unless ($fwk);
885 my ( $tag, $subfield ) =
886 GetMarcFromKohaField
( "items.location", $fwk );
887 if ( $tag and $subfield ) {
890 "SELECT authorised_value
891 FROM marc_subfield_structure
896 $sth->execute( $tag, $subfield, $fwk );
897 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
900 "SELECT authorised_value,lib
901 FROM authorised_values
905 $authvalsth->execute($authorisedvaluecat);
906 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
907 $itemlocation{$authorisedvalue} = $lib;
909 return \
%itemlocation;
921 $itemlocation{"1"} = "Not For Loan";
922 return \
%itemlocation;
929 $items = GetLostItems( $where, $orderby );
933 This function gets a list of lost items.
939 C<$where> is a hashref. it containts a field of the items table as key
940 and the value to match as value. For example:
942 { barcode => 'abc123',
943 homebranch => 'CPL', }
945 C<$orderby> is a field of the items table by which the resultset
950 C<$items> is a reference to an array full of hashrefs with columns
951 from the "items" table as keys.
953 =item usage in the perl script:
955 my $where = { barcode => '0001548' };
956 my $items = GetLostItems( $where, "homebranch" );
957 $template->param( itemsloop => $items );
964 # Getting input args.
967 my $dbh = C4
::Context
->dbh;
972 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
973 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
974 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
976 authorised_values.category = 'LOST'
977 AND itemlost IS NOT NULL
980 my @query_parameters;
981 foreach my $key (keys %$where) {
982 $query .= " AND $key LIKE ?";
983 push @query_parameters, "%$where->{$key}%";
985 my @ordervalues = qw
/title author homebranch itype barcode price replacementprice lib datelastseen location/;
987 if ( defined $orderby && grep($orderby, @ordervalues)) {
988 $query .= ' ORDER BY '.$orderby;
991 my $sth = $dbh->prepare($query);
992 $sth->execute( @query_parameters );
994 while ( my $row = $sth->fetchrow_hashref ){
1000 =head2 GetItemsForInventory
1004 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size, $statushash);
1008 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1010 The sub returns a reference to a list of hashes, each containing
1011 itemnumber, author, title, barcode, item callnumber, and date last
1012 seen. It is ordered by callnumber then title.
1014 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1015 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1016 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1017 $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.
1021 sub GetItemsForInventory
{
1022 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branch, $offset, $size, $statushash ) = @_;
1023 my $dbh = C4
::Context
->dbh;
1024 my ( @bind_params, @where_strings );
1026 my $query = <<'END_SQL';
1027 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
1029 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1030 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1033 for my $authvfield (keys %$statushash){
1034 if ( scalar @{$statushash->{$authvfield}} > 0 ){
1035 my $joinedvals = join ',', @{$statushash->{$authvfield}};
1036 push @where_strings, "$authvfield in (" . $joinedvals . ")";
1042 push @where_strings, 'itemcallnumber >= ?';
1043 push @bind_params, $minlocation;
1047 push @where_strings, 'itemcallnumber <= ?';
1048 push @bind_params, $maxlocation;
1051 if ($datelastseen) {
1052 $datelastseen = format_date_in_iso($datelastseen);
1053 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1054 push @bind_params, $datelastseen;
1058 push @where_strings, 'items.location = ?';
1059 push @bind_params, $location;
1063 push @where_strings, 'items.homebranch = ?';
1064 push @bind_params, $branch;
1068 push @where_strings, 'biblioitems.itemtype = ?';
1069 push @bind_params, $itemtype;
1072 if ( $ignoreissued) {
1073 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1074 push @where_strings, 'issues.date_due IS NULL';
1077 if ( @where_strings ) {
1079 $query .= join ' AND ', @where_strings;
1081 $query .= ' ORDER BY itemcallnumber, title';
1082 my $sth = $dbh->prepare($query);
1083 $sth->execute( @bind_params );
1087 while ( my $row = $sth->fetchrow_hashref ) {
1088 $offset-- if ($offset);
1089 $row->{datelastseen}=format_date($row->{datelastseen});
1090 if ( ( !$offset ) && $size ) {
1091 push @results, $row;
1098 =head2 GetItemsCount
1101 $count = &GetItemsCount( $biblionumber);
1105 This function return count of item with $biblionumber
1110 my ( $biblionumber ) = @_;
1111 my $dbh = C4::Context->dbh;
1112 my $query = "SELECT count(*)
1114 WHERE biblionumber=?";
1115 my $sth = $dbh->prepare($query);
1116 $sth->execute($biblionumber);
1117 my $count = $sth->fetchrow;
1121 =head2 GetItemInfosOf
1125 GetItemInfosOf(@itemnumbers);
1131 sub GetItemInfosOf {
1132 my @itemnumbers = @_;
1137 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1139 return get_infos_of( $query, 'itemnumber' );
1142 =head2 GetItemsByBiblioitemnumber
1146 GetItemsByBiblioitemnumber($biblioitemnumber);
1150 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1151 Called by C<C4::XISBN>
1155 sub GetItemsByBiblioitemnumber {
1156 my ( $bibitem ) = @_;
1157 my $dbh = C4::Context->dbh;
1158 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1159 # Get all items attached to a biblioitem
1162 $sth->execute($bibitem) || die $sth->errstr;
1163 while ( my $data = $sth->fetchrow_hashref ) {
1164 # Foreach item, get circulation information
1165 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1166 WHERE itemnumber = ?
1167 AND issues.borrowernumber = borrowers.borrowernumber"
1169 $sth2->execute( $data->{'itemnumber'} );
1170 if ( my $data2 = $sth2->fetchrow_hashref ) {
1171 # if item is out, set the due date and who it is out too
1172 $data->{'date_due'} = $data2->{'date_due'};
1173 $data->{'cardnumber'} = $data2->{'cardnumber'};
1174 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1177 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1178 $data->{'date_due'} = '';
1180 # Find the last 3 people who borrowed this item.
1181 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1182 AND old_issues.borrowernumber = borrowers.borrowernumber
1183 ORDER BY returndate desc,timestamp desc LIMIT 3";
1184 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1185 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1187 while ( my $data2 = $sth2->fetchrow_hashref ) {
1188 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1189 $data->{"card$i2"} = $data2->{'cardnumber'};
1190 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1193 push(@results,$data);
1202 @results = GetItemsInfo($biblionumber, $type);
1206 Returns information about books with the given biblionumber.
1208 C<$type> may be either C<intra> or anything else. If it is not set to
1209 C<intra>, then the search will exclude lost, very overdue, and
1212 C<GetItemsInfo> returns a list of references-to-hash. Each element
1213 contains a number of keys. Most of them are table items from the
1214 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1215 Koha database. Other keys include:
1219 =item C<$data-E<gt>{branchname}>
1221 The name (not the code) of the branch to which the book belongs.
1223 =item C<$data-E<gt>{datelastseen}>
1225 This is simply C<items.datelastseen>, except that while the date is
1226 stored in YYYY-MM-DD format in the database, here it is converted to
1227 DD/MM/YYYY format. A NULL date is returned as C<//>.
1229 =item C<$data-E<gt>{datedue}>
1231 =item C<$data-E<gt>{class}>
1233 This is the concatenation of C<biblioitems.classification>, the book's
1234 Dewey code, and C<biblioitems.subclass>.
1236 =item C<$data-E<gt>{ocount}>
1238 I think this is the number of copies of the book available.
1240 =item C<$data-E<gt>{order}>
1242 If this is set, it is set to C<One Order>.
1249 my ( $biblionumber, $type ) = @_;
1250 my $dbh = C4::Context->dbh;
1251 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1257 biblioitems.itemtype,
1260 biblioitems.publicationyear,
1261 biblioitems.publishercode,
1262 biblioitems.volumedate,
1263 biblioitems.volumedesc,
1266 items.notforloan as itemnotforloan,
1267 itemtypes.description
1269 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1270 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1271 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1272 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1273 $query .= " WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1274 my $sth = $dbh->prepare($query);
1275 $sth->execute($biblionumber);
1280 my $isth = $dbh->prepare(
1281 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1282 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1283 WHERE itemnumber = ?"
1285 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1286 while ( my $data = $sth->fetchrow_hashref ) {
1289 $isth->execute( $data->{'itemnumber'} );
1290 if ( my $idata = $isth->fetchrow_hashref ) {
1291 $data->{borrowernumber} = $idata->{borrowernumber};
1292 $data->{cardnumber} = $idata->{cardnumber};
1293 $data->{surname} = $idata->{surname};
1294 $data->{firstname} = $idata->{firstname};
1295 $datedue = $idata->{'date_due'};
1296 if (C4::Context->preference("IndependantBranches")){
1297 my $userenv = C4::Context->userenv;
1298 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1299 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1303 if ( $data->{'serial'}) {
1304 $ssth->execute($data->{'itemnumber'}) ;
1305 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1308 if ( $datedue eq '' ) {
1309 my ( $restype, $reserves ) =
1310 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1311 # Previous conditional check with if ($restype) is not needed because a true
1312 # result for one item will result in subsequent items defaulting to this true
1314 $count_reserves = $restype;
1316 #get branch information.....
1317 my $bsth = $dbh->prepare(
1318 "SELECT * FROM branches WHERE branchcode = ?
1321 $bsth->execute( $data->{'holdingbranch'} );
1322 if ( my $bdata = $bsth->fetchrow_hashref ) {
1323 $data->{'branchname'} = $bdata->{'branchname'};
1325 $data->{'datedue'} = $datedue;
1326 $data->{'count_reserves'} = $count_reserves;
1328 # get notforloan complete status if applicable
1329 my $sthnflstatus = $dbh->prepare(
1330 'SELECT authorised_value
1331 FROM marc_subfield_structure
1332 WHERE kohafield="items.notforloan"
1336 $sthnflstatus->execute;
1337 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1338 if ($authorised_valuecode) {
1339 $sthnflstatus = $dbh->prepare(
1340 "SELECT lib FROM authorised_values
1342 AND authorised_value=?"
1344 $sthnflstatus->execute( $authorised_valuecode,
1345 $data->{itemnotforloan} );
1346 my ($lib) = $sthnflstatus->fetchrow;
1347 $data->{notforloanvalue} = $lib;
1349 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1351 # my stack procedures
1352 my $stackstatus = $dbh->prepare(
1353 'SELECT authorised_value
1354 FROM marc_subfield_structure
1355 WHERE kohafield="items.stack"
1358 $stackstatus->execute;
1360 ($authorised_valuecode) = $stackstatus->fetchrow;
1361 if ($authorised_valuecode) {
1362 $stackstatus = $dbh->prepare(
1364 FROM authorised_values
1366 AND authorised_value=?
1369 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1370 my ($lib) = $stackstatus->fetchrow;
1371 $data->{stack} = $lib;
1373 # Find the last 3 people who borrowed this item.
1374 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1375 WHERE itemnumber = ?
1376 AND old_issues.borrowernumber = borrowers.borrowernumber
1377 ORDER BY returndate DESC
1379 $sth2->execute($data->{'itemnumber'});
1381 while (my $data2 = $sth2->fetchrow_hashref()) {
1382 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1383 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1384 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1388 $results[$i] = $data;
1392 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1398 =head2 GetLastAcquisitions
1402 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 'itemtypes' => ('BK','BD')}, 10);
1408 sub GetLastAcquisitions {
1409 my ($data,$max) = @_;
1411 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1413 my $number_of_branches = @{$data->{branches}};
1414 my $number_of_itemtypes = @{$data->{itemtypes}};
1417 my @where = ('WHERE 1 ');
1418 $number_of_branches and push @where
1419 , 'AND holdingbranch IN ('
1420 , join(',', ('?') x $number_of_branches )
1424 $number_of_itemtypes and push @where
1425 , "AND $itemtype IN ("
1426 , join(',', ('?') x $number_of_itemtypes )
1430 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1431 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1432 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1434 GROUP BY biblio.biblionumber
1435 ORDER BY dateaccessioned DESC LIMIT $max";
1437 my $dbh = C4::Context->dbh;
1438 my $sth = $dbh->prepare($query);
1440 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1443 while( my $row = $sth->fetchrow_hashref){
1444 push @results, {date => $row->{dateaccessioned}
1445 , biblionumber => $row->{biblionumber}
1446 , title => $row->{title}};
1452 =head2 get_itemnumbers_of
1456 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1460 Given a list of biblionumbers, return the list of corresponding itemnumbers
1461 for each biblionumber.
1463 Return a reference on a hash where keys are biblionumbers and values are
1464 references on array of itemnumbers.
1468 sub get_itemnumbers_of {
1469 my @biblionumbers = @_;
1471 my $dbh = C4::Context->dbh;
1477 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1479 my $sth = $dbh->prepare($query);
1480 $sth->execute(@biblionumbers);
1484 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1485 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1488 return \%itemnumbers_of;
1491 =head2 GetItemnumberFromBarcode
1495 $result = GetItemnumberFromBarcode($barcode);
1501 sub GetItemnumberFromBarcode {
1503 my $dbh = C4::Context->dbh;
1506 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1507 $rq->execute($barcode);
1508 my ($result) = $rq->fetchrow;
1512 =head3 get_item_authorised_values
1514 find the types and values for all authorised values assigned to this item.
1519 returns: a hashref malling the authorised value to the value set for this itemnumber
1521 $authorised_values = {
1527 'RESTRICTED' => undef,
1530 'branches' => 'CPL',
1531 'cn_source' => undef,
1532 'itemtypes' => 'SER',
1535 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1539 sub get_item_authorised_values {
1540 my $itemnumber = shift;
1542 # assume that these entries in the authorised_value table are item level.
1543 my $query = q(SELECT distinct authorised_value, kohafield
1544 FROM marc_subfield_structure
1545 WHERE kohafield like 'item%'
1546 AND authorised_value != '' );
1548 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1549 my $iteminfo = GetItem( $itemnumber );
1550 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1552 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1553 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1554 $field =~ s/^items\.//;
1555 if ( exists $iteminfo->{ $field } ) {
1556 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1559 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1563 =head3 get_authorised_value_images
1565 find a list of icons that are appropriate for display based on the
1566 authorised values for a biblio.
1568 parameters: listref of authorised values, such as comes from
1569 get_item_authorised_values or
1570 from C4::Biblio::get_biblio_authorised_values
1572 returns: listref of hashrefs for each image. Each hashref looks like
1575 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1580 Notes: Currently, I put on the full path to the images on the staff
1581 side. This should either be configurable or not done at all. Since I
1582 have to deal with 'intranet' or 'opac' in
1583 get_biblio_authorised_values, perhaps I should be passing it in.
1587 sub get_authorised_value_images {
1588 my $authorised_values = shift;
1592 my $authorised_value_list = GetAuthorisedValues();
1593 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1594 foreach my $this_authorised_value ( @$authorised_value_list ) {
1595 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1596 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1597 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1598 if ( defined $this_authorised_value->{'imageurl'} ) {
1599 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1600 label => $this_authorised_value->{'lib'},
1601 category => $this_authorised_value->{'category'},
1602 value => $this_authorised_value->{'authorised_value'}, };
1607 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1612 =head1 LIMITED USE FUNCTIONS
1614 The following functions, while part of the public API,
1615 are not exported. This is generally because they are
1616 meant to be used by only one script for a specific
1617 purpose, and should not be used in any other context
1618 without careful thought.
1626 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1630 Returns MARC::Record of the item passed in parameter.
1631 This function is meant for use only in C<cataloguing/additem.pl>,
1632 where it is needed to support that script's MARC-like
1638 my ( $biblionumber, $itemnumber ) = @_;
1640 # GetMarcItem has been revised so that it does the following:
1641 # 1. Gets the item information from the items table.
1642 # 2. Converts it to a MARC field for storage in the bib record.
1644 # The previous behavior was:
1645 # 1. Get the bib record.
1646 # 2. Return the MARC tag corresponding to the item record.
1648 # The difference is that one treats the items row as authoritative,
1649 # while the other treats the MARC representation as authoritative
1650 # under certain circumstances.
1652 my $itemrecord = GetItem($itemnumber);
1654 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1655 # Also, don't emit a subfield if the underlying field is blank.
1658 return Item2Marc($itemrecord,$biblionumber);
1662 my ($itemrecord,$biblionumber)=@_;
1665 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1666 } keys %{ $itemrecord }
1668 my $itemmarc = TransformKohaToMarc($mungeditem);
1669 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1671 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1672 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1673 foreach my $field ($itemmarc->field($itemtag)){
1674 $field->add_subfields(@$unlinked_item_subfields);
1680 =head1 PRIVATE FUNCTIONS AND VARIABLES
1682 The following functions are not meant to be called
1683 directly, but are documented in order to explain
1684 the inner workings of C<C4::Items>.
1688 =head2 %derived_columns
1690 This hash keeps track of item columns that
1691 are strictly derived from other columns in
1692 the item record and are not meant to be set
1695 Each key in the hash should be the name of a
1696 column (as named by TransformMarcToKoha). Each
1697 value should be hashref whose keys are the
1698 columns on which the derived column depends. The
1699 hashref should also contain a 'BUILDER' key
1700 that is a reference to a sub that calculates
1705 my %derived_columns = (
1706 'items.cn_sort' => {
1707 'itemcallnumber' => 1,
1708 'items.cn_source' => 1,
1709 'BUILDER' => \&_calc_items_cn_sort,
1713 =head2 _set_derived_columns_for_add
1717 _set_derived_column_for_add($item);
1721 Given an item hash representing a new item to be added,
1722 calculate any derived columns. Currently the only
1723 such column is C<items.cn_sort>.
1727 sub _set_derived_columns_for_add {
1730 foreach my $column (keys %derived_columns) {
1731 my $builder = $derived_columns{$column}->{'BUILDER'};
1732 my $source_values = {};
1733 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1734 next if $source_column eq 'BUILDER';
1735 $source_values->{$source_column} = $item->{$source_column};
1737 $builder->($item, $source_values);
1741 =head2 _set_derived_columns_for_mod
1745 _set_derived_column_for_mod($item);
1749 Given an item hash representing a new item to be modified.
1750 calculate any derived columns. Currently the only
1751 such column is C<items.cn_sort>.
1753 This routine differs from C<_set_derived_columns_for_add>
1754 in that it needs to handle partial item records. In other
1755 words, the caller of C<ModItem> may have supplied only one
1756 or two columns to be changed, so this function needs to
1757 determine whether any of the columns to be changed affect
1758 any of the derived columns. Also, if a derived column
1759 depends on more than one column, but the caller is not
1760 changing all of then, this routine retrieves the unchanged
1761 values from the database in order to ensure a correct
1766 sub _set_derived_columns_for_mod {
1769 foreach my $column (keys %derived_columns) {
1770 my $builder = $derived_columns{$column}->{'BUILDER'};
1771 my $source_values = {};
1772 my %missing_sources = ();
1773 my $must_recalc = 0;
1774 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1775 next if $source_column eq 'BUILDER';
1776 if (exists $item->{$source_column}) {
1778 $source_values->{$source_column} = $item->{$source_column};
1780 $missing_sources{$source_column} = 1;
1784 foreach my $source_column (keys %missing_sources) {
1785 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1787 $builder->($item, $source_values);
1792 =head2 _do_column_fixes_for_mod
1796 _do_column_fixes_for_mod($item);
1800 Given an item hashref containing one or more
1801 columns to modify, fix up certain values.
1802 Specifically, set to 0 any passed value
1803 of C<notforloan>, C<damaged>, C<itemlost>, or
1804 C<wthdrawn> that is either undefined or
1805 contains the empty string.
1809 sub _do_column_fixes_for_mod {
1812 if (exists $item->{'notforloan'} and
1813 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1814 $item->{'notforloan'} = 0;
1816 if (exists $item->{'damaged'} and
1817 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1818 $item->{'damaged'} = 0;
1820 if (exists $item->{'itemlost'} and
1821 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1822 $item->{'itemlost'} = 0;
1824 if (exists $item->{'wthdrawn'} and
1825 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1826 $item->{'wthdrawn'} = 0;
1828 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1829 $item->{'permanent_location'} = $item->{'location'};
1833 =head2 _get_single_item_column
1837 _get_single_item_column($column, $itemnumber);
1841 Retrieves the value of a single column from an C<items>
1842 row specified by C<$itemnumber>.
1846 sub _get_single_item_column {
1848 my $itemnumber = shift;
1850 my $dbh = C4::Context->dbh;
1851 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1852 $sth->execute($itemnumber);
1853 my ($value) = $sth->fetchrow();
1857 =head2 _calc_items_cn_sort
1861 _calc_items_cn_sort($item, $source_values);
1865 Helper routine to calculate C<items.cn_sort>.
1869 sub _calc_items_cn_sort {
1871 my $source_values = shift;
1873 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1876 =head2 _set_defaults_for_add
1880 _set_defaults_for_add($item_hash);
1884 Given an item hash representing an item to be added, set
1885 correct default values for columns whose default value
1886 is not handled by the DBMS. This includes the following
1893 C<items.dateaccessioned>
1915 sub _set_defaults_for_add {
1917 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1918 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1921 =head2 _koha_new_item
1925 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1929 Perform the actual insert into the C<items> table.
1933 sub _koha_new_item
{
1934 my ( $item, $barcode ) = @_;
1935 my $dbh=C4
::Context
->dbh;
1938 "INSERT INTO items SET
1940 biblioitemnumber = ?,
1942 dateaccessioned = ?,
1946 replacementprice = ?,
1947 replacementpricedate = NOW(),
1948 datelastborrowed = ?,
1949 datelastseen = NOW(),
1972 more_subfields_xml = ?,
1975 my $sth = $dbh->prepare($query);
1977 $item->{'biblionumber'},
1978 $item->{'biblioitemnumber'},
1980 $item->{'dateaccessioned'},
1981 $item->{'booksellerid'},
1982 $item->{'homebranch'},
1984 $item->{'replacementprice'},
1985 $item->{datelastborrowed
},
1987 $item->{'notforloan'},
1989 $item->{'itemlost'},
1990 $item->{'wthdrawn'},
1991 $item->{'itemcallnumber'},
1992 $item->{'restricted'},
1993 $item->{'itemnotes'},
1994 $item->{'holdingbranch'},
1996 $item->{'location'},
1999 $item->{'renewals'},
2000 $item->{'reserves'},
2001 $item->{'items.cn_source'},
2002 $item->{'items.cn_sort'},
2005 $item->{'materials'},
2007 $item->{'enumchron'},
2008 $item->{'more_subfields_xml'},
2009 $item->{'copynumber'},
2011 my $itemnumber = $dbh->{'mysql_insertid'};
2012 if ( defined $sth->errstr ) {
2013 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2015 return ( $itemnumber, $error );
2018 =head2 MoveItemFromBiblio
2022 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2026 Moves an item from a biblio to another
2028 Returns undef if the move failed or the biblionumber of the destination record otherwise
2030 sub MoveItemFromBiblio
{
2031 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2032 my $dbh = C4
::Context
->dbh;
2033 my $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2034 my $return = $sth->execute($tobiblio, $tobiblio, $itemnumber, $frombiblio);
2038 my $frameworkcode = GetFrameworkCode
($frombiblio);
2040 # Getting marc field for itemnumber
2041 my ($itemtag, $itemsubfield) = GetMarcFromKohaField
('items.itemnumber', $frameworkcode);
2043 # Getting the record we want to move the item from
2044 my $record = GetMarcBiblio
($frombiblio);
2046 # The item we want to move
2050 foreach my $fielditem ($record->field($itemtag)){
2051 # If it is the item we want to move
2052 if ($fielditem->subfield($itemsubfield) == $itemnumber) {
2055 # Then delete it from the record
2056 $record->delete_field($fielditem)
2060 # If we found an item (should always true, except in case of database-marcxml inconsistency)
2063 # Saving the modification
2064 ModBiblioMarc
($record, $frombiblio, $frameworkcode);
2066 # Getting the record we want to move the item to
2067 $record = GetMarcBiblio
($tobiblio);
2069 # Inserting the previously saved item
2070 $record->insert_fields_ordered($item);
2072 # Saving the modification
2073 ModBiblioMarc
($record, $tobiblio, $frameworkcode);
2087 DelItemCheck($dbh, $biblionumber, $itemnumber);
2091 Exported function (core API) for deleting an item record in Koha if there no current issue.
2096 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2099 # check that there is no issue on this item before deletion.
2100 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2101 $sth->execute($itemnumber);
2103 my $onloan=$sth->fetchrow;
2106 $error = "book_on_loan"
2108 # check it doesnt have a waiting reserve
2109 $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
2110 $sth->execute($itemnumber);
2111 my $reserve=$sth->fetchrow;
2113 $error = "book_reserved";
2115 DelItem
($dbh, $biblionumber, $itemnumber);
2122 =head2 _koha_modify_item
2126 my ($itemnumber,$error) =_koha_modify_item( $item );
2130 Perform the actual update of the C<items> row. Note that this
2131 routine accepts a hashref specifying the columns to update.
2135 sub _koha_modify_item
{
2137 my $dbh=C4
::Context
->dbh;
2140 my $query = "UPDATE items SET ";
2142 for my $key ( keys %$item ) {
2144 push @bind, $item->{$key};
2147 $query .= " WHERE itemnumber=?";
2148 push @bind, $item->{'itemnumber'};
2149 my $sth = C4
::Context
->dbh->prepare($query);
2150 $sth->execute(@bind);
2151 if ( C4
::Context
->dbh->errstr ) {
2152 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2155 return ($item->{'itemnumber'},$error);
2158 =head2 _koha_delete_item
2162 _koha_delete_item( $dbh, $itemnum );
2166 Internal function to delete an item record from the koha tables
2170 sub _koha_delete_item
{
2171 my ( $dbh, $itemnum ) = @_;
2173 # save the deleted item to deleteditems table
2174 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2175 $sth->execute($itemnum);
2176 my $data = $sth->fetchrow_hashref();
2177 my $query = "INSERT INTO deleteditems SET ";
2179 foreach my $key ( keys %$data ) {
2180 $query .= "$key = ?,";
2181 push( @bind, $data->{$key} );
2184 $sth = $dbh->prepare($query);
2185 $sth->execute(@bind);
2187 # delete from items table
2188 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2189 $sth->execute($itemnum);
2193 =head2 _marc_from_item_hash
2197 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2201 Given an item hash representing a complete item record,
2202 create a C<MARC::Record> object containing an embedded
2203 tag representing that item.
2205 The third, optional parameter C<$unlinked_item_subfields> is
2206 an arrayref of subfields (not mapped to C<items> fields per the
2207 framework) to be added to the MARC representation
2212 sub _marc_from_item_hash
{
2214 my $frameworkcode = shift;
2215 my $unlinked_item_subfields;
2217 $unlinked_item_subfields = shift;
2220 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2221 # Also, don't emit a subfield if the underlying field is blank.
2222 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2223 (/^items\./ ?
($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2224 : () } keys %{ $item } };
2226 my $item_marc = MARC
::Record
->new();
2227 foreach my $item_field (keys %{ $mungeditem }) {
2228 my ($tag, $subfield) = GetMarcFromKohaField
($item_field, $frameworkcode);
2229 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2230 if (my $field = $item_marc->field($tag)) {
2231 $field->add_subfields($subfield => $mungeditem->{$item_field});
2233 my $add_subfields = [];
2234 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2235 $add_subfields = $unlinked_item_subfields;
2237 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @
$add_subfields);
2244 =head2 _add_item_field_to_biblio
2248 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2252 Adds the fields from a MARC record containing the
2253 representation of a Koha item record to the MARC
2254 biblio record. The input C<$item_marc> record
2255 is expect to contain just one field, the embedded
2256 item information field.
2260 sub _add_item_field_to_biblio
{
2261 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2263 my $biblio_marc = GetMarcBiblio
($biblionumber);
2264 foreach my $field ($item_marc->fields()) {
2265 $biblio_marc->append_fields($field);
2268 ModBiblioMarc
($biblio_marc, $biblionumber, $frameworkcode);
2271 =head2 _replace_item_field_in_biblio
2275 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2279 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2280 representation of the item, examine the biblio MARC
2281 for the corresponding tag for that item and
2282 replace it with the tag from C<$item_marc>.
2286 sub _replace_item_field_in_biblio
{
2287 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2288 my $dbh = C4
::Context
->dbh;
2290 # get complete MARC record & replace the item field by the new one
2291 my $completeRecord = GetMarcBiblio
($biblionumber);
2292 my ($itemtag,$itemsubfield) = GetMarcFromKohaField
("items.itemnumber",$frameworkcode);
2293 my $itemField = $ItemRecord->field($itemtag);
2294 my @items = $completeRecord->field($itemtag);
2297 if ($_->subfield($itemsubfield) eq $itemnumber) {
2298 $_->replace_with($itemField);
2304 # If we haven't found the matching field,
2305 # just add it. However, this means that
2306 # there is likely a bug.
2307 $completeRecord->append_fields($itemField);
2311 ModBiblioMarc
($completeRecord, $biblionumber, $frameworkcode);
2314 =head2 _repack_item_errors
2316 Add an error message hash generated by C<CheckItemPreSave>
2317 to a list of errors.
2321 sub _repack_item_errors
{
2322 my $item_sequence_num = shift;
2323 my $item_ref = shift;
2324 my $error_ref = shift;
2326 my @repacked_errors = ();
2328 foreach my $error_code (sort keys %{ $error_ref }) {
2329 my $repacked_error = {};
2330 $repacked_error->{'item_sequence'} = $item_sequence_num;
2331 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ?
$item_ref->{'barcode'} : '';
2332 $repacked_error->{'error_code'} = $error_code;
2333 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2334 push @repacked_errors, $repacked_error;
2337 return @repacked_errors;
2340 =head2 _get_unlinked_item_subfields
2344 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2350 sub _get_unlinked_item_subfields
{
2351 my $original_item_marc = shift;
2352 my $frameworkcode = shift;
2354 my $marcstructure = GetMarcStructure
(1, $frameworkcode);
2356 # assume that this record has only one field, and that that
2357 # field contains only the item information
2359 my @fields = $original_item_marc->fields();
2360 if ($#fields > -1) {
2361 my $field = $fields[0];
2362 my $tag = $field->tag();
2363 foreach my $subfield ($field->subfields()) {
2364 if (defined $subfield->[1] and
2365 $subfield->[1] ne '' and
2366 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2367 push @
$subfields, $subfield->[0] => $subfield->[1];
2374 =head2 _get_unlinked_subfields_xml
2378 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2384 sub _get_unlinked_subfields_xml
{
2385 my $unlinked_item_subfields = shift;
2388 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2389 my $marc = MARC
::Record
->new();
2390 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2391 # used in the framework
2392 $marc->append_fields(MARC
::Field
->new('999', ' ', ' ', @
$unlinked_item_subfields));
2393 $marc->encoding("UTF-8");
2394 $xml = $marc->as_xml("USMARC");
2400 =head2 _parse_unlinked_item_subfields_from_xml
2404 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2410 sub _parse_unlinked_item_subfields_from_xml
{
2413 return unless defined $xml and $xml ne "";
2414 my $marc = MARC
::Record
->new_from_xml(StripNonXmlChars
($xml),'UTF-8');
2415 my $unlinked_subfields = [];
2416 my @fields = $marc->fields();
2417 if ($#fields > -1) {
2418 foreach my $subfield ($fields[0]->subfields()) {
2419 push @
$unlinked_subfields, $subfield->[0] => $subfield->[1];
2422 return $unlinked_subfields;