3 # Copyright 2007 LibLime, Inc.
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
25 use C4::Dates qw/format_date format_date_in_iso/;
33 use vars qw($VERSION @ISA @EXPORT);
39 @ISA = qw( Exporter );
62 GetItemsByBiblioitemnumber
65 GetItemnumberFromBarcode
71 C4::Items - item management functions
75 This module contains an API for manipulating item
76 records in Koha, and is used by cataloguing, circulation,
77 acquisitions, and serials management.
79 A Koha item record is stored in two places: the
80 items table and embedded in a MARC tag in the XML
81 version of the associated bib record in C<biblioitems.marcxml>.
82 This is done to allow the item information to be readily
83 indexed (e.g., by Zebra), but means that each item
84 modification transaction must keep the items table
85 and the MARC XML in sync at all times.
87 Consequently, all code that creates, modifies, or deletes
88 item records B<must> use an appropriate function from
89 C<C4::Items>. If no existing function is suitable, it is
90 better to add one to C<C4::Items> than to use add
91 one-off SQL statements to add or modify items.
93 The items table will be considered authoritative. In other
94 words, if there is ever a discrepancy between the items
95 table and the MARC XML, the items table should be considered
98 =head1 HISTORICAL NOTE
100 Most of the functions in C<C4::Items> were originally in
101 the C<C4::Biblio> module.
103 =head1 CORE EXPORTED FUNCTIONS
105 The following functions are meant for use by users
114 $item = GetItem($itemnumber,$barcode,$serial);
118 Return item information, for a given itemnumber or barcode.
119 The return value is a hashref mapping item column
120 names to values. If C<$serial> is true, include serial publication data.
125 my ($itemnumber,$barcode, $serial) = @_;
126 my $dbh = C4::Context->dbh;
129 my $sth = $dbh->prepare("
131 WHERE itemnumber = ?");
132 $sth->execute($itemnumber);
133 $data = $sth->fetchrow_hashref;
135 my $sth = $dbh->prepare("
139 $sth->execute($barcode);
140 $data = $sth->fetchrow_hashref;
143 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
144 $ssth->execute($data->{'itemnumber'}) ;
145 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
146 warn $data->{'serialseq'} , $data->{'publisheddate'};
148 #if we don't have an items.itype, use biblioitems.itemtype.
149 if( ! $data->{'itype'} ) {
150 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
151 $sth->execute($data->{'biblionumber'});
152 ($data->{'itype'}) = $sth->fetchrow_array;
157 =head2 AddItemFromMarc
161 my ($biblionumber, $biblioitemnumber, $itemnumber)
162 = AddItemFromMarc($source_item_marc, $biblionumber);
166 Given a MARC::Record object containing an embedded item
167 record and a biblionumber, create a new item record.
171 sub AddItemFromMarc {
172 my ( $source_item_marc, $biblionumber ) = @_;
173 my $dbh = C4::Context->dbh;
175 # parse item hash from MARC
176 my $frameworkcode = GetFrameworkCode( $biblionumber );
177 my $item = &TransformMarcToKoha( $dbh, $source_item_marc, $frameworkcode );
178 my $unlinked_item_subfields = _get_unlinked_item_subfields($source_item_marc, $frameworkcode);
179 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
186 my ($biblionumber, $biblioitemnumber, $itemnumber)
187 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
191 Given a hash containing item column names as keys,
192 create a new Koha item record.
194 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
195 do not need to be supplied for general use; they exist
196 simply to allow them to be picked up from AddItemFromMarc.
198 The final optional parameter, C<$unlinked_item_subfields>, contains
199 an arrayref containing subfields present in the original MARC
200 representation of the item (e.g., from the item editor) that are
201 not mapped to C<items> columns directly but should instead
202 be stored in C<items.more_subfields_xml> and included in
203 the biblio items tag for display and indexing.
209 my $biblionumber = shift;
211 my $dbh = @_ ? shift : C4::Context->dbh;
212 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
213 my $unlinked_item_subfields;
215 $unlinked_item_subfields = shift
218 # needs old biblionumber and biblioitemnumber
219 $item->{'biblionumber'} = $biblionumber;
220 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
221 $sth->execute( $item->{'biblionumber'} );
222 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
224 _set_defaults_for_add($item);
225 _set_derived_columns_for_add($item);
226 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
227 # FIXME - checks here
228 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
229 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
230 $itype_sth->execute( $item->{'biblionumber'} );
231 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
234 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
235 $item->{'itemnumber'} = $itemnumber;
237 # create MARC tag representing item and add to bib
238 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
239 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
241 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
243 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
246 =head2 AddItemBatchFromMarc
250 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
254 Efficiently create item records from a MARC biblio record with
255 embedded item fields. This routine is suitable for batch jobs.
257 This API assumes that the bib record has already been
258 saved to the C<biblio> and C<biblioitems> tables. It does
259 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
260 are populated, but it will do so via a call to ModBibiloMarc.
262 The goal of this API is to have a similar effect to using AddBiblio
263 and AddItems in succession, but without inefficient repeated
264 parsing of the MARC XML bib record.
266 This function returns an arrayref of new itemsnumbers and an arrayref of item
267 errors encountered during the processing. Each entry in the errors
268 list is a hashref containing the following keys:
274 Sequence number of original item tag in the MARC record.
278 Item barcode, provide to assist in the construction of
279 useful error messages.
281 =item error_condition
283 Code representing the error condition. Can be 'duplicate_barcode',
284 'invalid_homebranch', or 'invalid_holdingbranch'.
286 =item error_information
288 Additional information appropriate to the error condition.
294 sub AddItemBatchFromMarc {
295 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
297 my @itemnumbers = ();
299 my $dbh = C4::Context->dbh;
301 # loop through the item tags and start creating items
302 my @bad_item_fields = ();
303 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
304 my $item_sequence_num = 0;
305 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
306 $item_sequence_num++;
307 # we take the item field and stick it into a new
308 # MARC record -- this is required so far because (FIXME)
309 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
310 # and there is no TransformMarcFieldToKoha
311 my $temp_item_marc = MARC::Record->new();
312 $temp_item_marc->append_fields($item_field);
314 # add biblionumber and biblioitemnumber
315 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
316 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
317 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
318 $item->{'biblionumber'} = $biblionumber;
319 $item->{'biblioitemnumber'} = $biblioitemnumber;
321 # check for duplicate barcode
322 my %item_errors = CheckItemPreSave($item);
324 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
325 push @bad_item_fields, $item_field;
329 _set_defaults_for_add($item);
330 _set_derived_columns_for_add($item);
331 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
332 warn $error if $error;
333 push @itemnumbers, $itemnumber; # FIXME not checking error
334 $item->{'itemnumber'} = $itemnumber;
336 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
338 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
339 $item_field->replace_with($new_item_marc->field($itemtag));
342 # remove any MARC item fields for rejected items
343 foreach my $item_field (@bad_item_fields) {
344 $record->delete_field($item_field);
347 # update the MARC biblio
348 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
350 return (\@itemnumbers, \@errors);
353 =head2 ModItemFromMarc
357 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
361 This function updates an item record based on a supplied
362 C<MARC::Record> object containing an embedded item field.
363 This API is meant for the use of C<additem.pl>; for
364 other purposes, C<ModItem> should be used.
366 This function uses the hash %default_values_for_mod_from_marc,
367 which contains default values for item fields to
368 apply when modifying an item. This is needed beccause
369 if an item field's value is cleared, TransformMarcToKoha
370 does not include the column in the
371 hash that's passed to ModItem, which without
372 use of this hash makes it impossible to clear
373 an item field's value. See bug 2466.
375 Note that only columns that can be directly
376 changed from the cataloging and serials
377 item editors are included in this hash.
381 my %default_values_for_mod_from_marc = (
383 booksellerid => undef,
385 'items.cn_source' => undef,
388 dateaccessioned => undef,
390 holdingbranch => undef,
392 itemcallnumber => undef,
401 replacementprice => undef,
402 replacementpricedate => undef,
409 sub ModItemFromMarc {
410 my $item_marc = shift;
411 my $biblionumber = shift;
412 my $itemnumber = shift;
414 my $dbh = C4::Context->dbh;
415 my $frameworkcode = GetFrameworkCode( $biblionumber );
416 my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode );
417 foreach my $item_field (keys %default_values_for_mod_from_marc) {
418 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
420 my $unlinked_item_subfields = _get_unlinked_item_subfields($item_marc, $frameworkcode);
422 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
429 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
433 Change one or more columns in an item record and update
434 the MARC representation of the item.
436 The first argument is a hashref mapping from item column
437 names to the new values. The second and third arguments
438 are the biblionumber and itemnumber, respectively.
440 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
441 an arrayref containing subfields present in the original MARC
442 representation of the item (e.g., from the item editor) that are
443 not mapped to C<items> columns directly but should instead
444 be stored in C<items.more_subfields_xml> and included in
445 the biblio items tag for display and indexing.
447 If one of the changed columns is used to calculate
448 the derived value of a column such as C<items.cn_sort>,
449 this routine will perform the necessary calculation
456 my $biblionumber = shift;
457 my $itemnumber = shift;
459 # if $biblionumber is undefined, get it from the current item
460 unless (defined $biblionumber) {
461 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
464 my $dbh = @_ ? shift : C4::Context->dbh;
465 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
467 my $unlinked_item_subfields;
469 $unlinked_item_subfields = shift;
470 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
473 $item->{'itemnumber'} = $itemnumber or return undef;
474 _set_derived_columns_for_mod($item);
475 _do_column_fixes_for_mod($item);
478 # attempt to change itemnumber
479 # attempt to change biblionumber (if we want
480 # an API to relink an item to a different bib,
481 # it should be a separate function)
484 _koha_modify_item($item);
486 # update biblio MARC XML
487 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
489 unless (defined $unlinked_item_subfields) {
490 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
492 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
493 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
495 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
496 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
497 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
500 =head2 ModItemTransfer
504 ModItemTransfer($itenumber, $frombranch, $tobranch);
508 Marks an item as being transferred from one branch
513 sub ModItemTransfer {
514 my ( $itemnumber, $frombranch, $tobranch ) = @_;
516 my $dbh = C4::Context->dbh;
518 #new entry in branchtransfers....
519 my $sth = $dbh->prepare(
520 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
521 VALUES (?, ?, NOW(), ?)");
522 $sth->execute($itemnumber, $frombranch, $tobranch);
524 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
525 ModDateLastSeen($itemnumber);
529 =head2 ModDateLastSeen
533 ModDateLastSeen($itemnum);
537 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
538 C<$itemnum> is the item number
542 sub ModDateLastSeen {
543 my ($itemnumber) = @_;
545 my $today = C4::Dates->new();
546 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
553 DelItem($biblionumber, $itemnumber);
557 Exported function (core API) for deleting an item record in Koha.
562 my ( $dbh, $biblionumber, $itemnumber ) = @_;
564 # FIXME check the item has no current issues
566 _koha_delete_item( $dbh, $itemnumber );
568 # get the MARC record
569 my $record = GetMarcBiblio($biblionumber);
570 my $frameworkcode = GetFrameworkCode($biblionumber);
573 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
574 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
576 #search item field code
577 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
578 my @fields = $record->field($itemtag);
580 # delete the item specified
581 foreach my $field (@fields) {
582 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
583 $record->delete_field($field);
586 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
587 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
594 DelItemCheck($dbh, $biblionumber, $itemnumber);
598 Exported function (core API) for deleting an item record in Koha if there no current issue.
603 my ( $dbh, $biblionumber, $itemnumber ) = @_;
606 # check that there is no issue on this item before deletion.
607 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
608 $sth->execute($itemnumber);
610 my $onloan=$sth->fetchrow;
614 $error = "book_on_loan"
616 # check it doesnt have a waiting reserve
617 $sth=$dbh->prepare("SELECT * FROM reserves WHERE found = 'W' AND itemnumber = ?");
618 $sth->execute($itemnumber);
619 my $reserve=$sth->fetchrow;
622 $error = "book_reserved";
624 DelItem($dbh, $biblionumber, $itemnumber);
631 =head2 CheckItemPreSave
635 my $item_ref = TransformMarcToKoha($marc, 'items');
637 my %errors = CheckItemPreSave($item_ref);
638 if (exists $errors{'duplicate_barcode'}) {
639 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
640 } elsif (exists $errors{'invalid_homebranch'}) {
641 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
642 } elsif (exists $errors{'invalid_holdingbranch'}) {
643 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
650 Given a hashref containing item fields, determine if it can be
651 inserted or updated in the database. Specifically, checks for
652 database integrity issues, and returns a hash containing any
653 of the following keys, if applicable.
657 =item duplicate_barcode
659 Barcode, if it duplicates one already found in the database.
661 =item invalid_homebranch
663 Home branch, if not defined in branches table.
665 =item invalid_holdingbranch
667 Holding branch, if not defined in branches table.
671 This function does NOT implement any policy-related checks,
672 e.g., whether current operator is allowed to save an
673 item that has a given branch code.
677 sub CheckItemPreSave {
678 my $item_ref = shift;
682 # check for duplicate barcode
683 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
684 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
685 if ($existing_itemnumber) {
686 if (!exists $item_ref->{'itemnumber'} # new item
687 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
688 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
693 # check for valid home branch
694 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
695 my $branch_name = GetBranchName($item_ref->{'homebranch'});
696 unless (defined $branch_name) {
697 # relies on fact that branches.branchname is a non-NULL column,
698 # so GetBranchName returns undef only if branch does not exist
699 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
703 # check for valid holding branch
704 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
705 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
706 unless (defined $branch_name) {
707 # relies on fact that branches.branchname is a non-NULL column,
708 # so GetBranchName returns undef only if branch does not exist
709 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
717 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
719 The following functions provide various ways of
720 getting an item record, a set of item records, or
721 lists of authorized values for certain item fields.
723 Some of the functions in this group are candidates
724 for refactoring -- for example, some of the code
725 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
726 has copy-and-paste work.
734 $itemstatushash = GetItemStatus($fwkcode);
738 Returns a list of valid values for the
739 C<items.notforloan> field.
741 NOTE: does B<not> return an individual item's
744 Can be MARC dependant.
746 But basically could be can be loan or not
747 Create a status selector with the following code
749 =head3 in PERL SCRIPT
753 my $itemstatushash = getitemstatus;
755 foreach my $thisstatus (keys %$itemstatushash) {
756 my %row =(value => $thisstatus,
757 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
759 push @itemstatusloop, \%row;
761 $template->param(statusloop=>\@itemstatusloop);
769 <select name="statusloop">
770 <option value="">Default</option>
771 <!-- TMPL_LOOP name="statusloop" -->
772 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
782 # returns a reference to a hash of references to status...
785 my $dbh = C4::Context->dbh;
787 $fwk = '' unless ($fwk);
788 my ( $tag, $subfield ) =
789 GetMarcFromKohaField( "items.notforloan", $fwk );
790 if ( $tag and $subfield ) {
793 "SELECT authorised_value
794 FROM marc_subfield_structure
800 $sth->execute( $tag, $subfield, $fwk );
801 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
804 "SELECT authorised_value,lib
805 FROM authorised_values
810 $authvalsth->execute($authorisedvaluecat);
811 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
812 $itemstatus{$authorisedvalue} = $lib;
828 $itemstatus{"1"} = "Not For Loan";
832 =head2 GetItemLocation
836 $itemlochash = GetItemLocation($fwk);
840 Returns a list of valid values for the
841 C<items.location> field.
843 NOTE: does B<not> return an individual item's
846 where fwk stands for an optional framework code.
847 Create a location selector with the following code
849 =head3 in PERL SCRIPT
853 my $itemlochash = getitemlocation;
855 foreach my $thisloc (keys %$itemlochash) {
856 my $selected = 1 if $thisbranch eq $branch;
857 my %row =(locval => $thisloc,
858 selected => $selected,
859 locname => $itemlochash->{$thisloc},
861 push @itemlocloop, \%row;
863 $template->param(itemlocationloop => \@itemlocloop);
871 <select name="location">
872 <option value="">Default</option>
873 <!-- TMPL_LOOP name="itemlocationloop" -->
874 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
882 sub GetItemLocation {
884 # returns a reference to a hash of references to location...
887 my $dbh = C4::Context->dbh;
889 $fwk = '' unless ($fwk);
890 my ( $tag, $subfield ) =
891 GetMarcFromKohaField( "items.location", $fwk );
892 if ( $tag and $subfield ) {
895 "SELECT authorised_value
896 FROM marc_subfield_structure
901 $sth->execute( $tag, $subfield, $fwk );
902 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
905 "SELECT authorised_value,lib
906 FROM authorised_values
910 $authvalsth->execute($authorisedvaluecat);
911 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
912 $itemlocation{$authorisedvalue} = $lib;
915 return \%itemlocation;
928 $itemlocation{"1"} = "Not For Loan";
929 return \%itemlocation;
936 $items = GetLostItems( $where, $orderby );
940 This function gets a list of lost items.
946 C<$where> is a hashref. it containts a field of the items table as key
947 and the value to match as value. For example:
949 { barcode => 'abc123',
950 homebranch => 'CPL', }
952 C<$orderby> is a field of the items table by which the resultset
957 C<$items> is a reference to an array full of hashrefs with columns
958 from the "items" table as keys.
960 =item usage in the perl script:
962 my $where = { barcode => '0001548' };
963 my $items = GetLostItems( $where, "homebranch" );
964 $template->param( itemsloop => $items );
971 # Getting input args.
974 my $dbh = C4::Context->dbh;
978 FROM items, biblio, authorised_values
980 items.biblionumber = biblio.biblionumber
981 AND items.itemlost = authorised_values.authorised_value
982 AND authorised_values.category = 'LOST'
983 AND itemlost IS NOT NULL
987 my @query_parameters;
988 foreach my $key (keys %$where) {
989 $query .= " AND $key LIKE ?";
990 push @query_parameters, "%$where->{$key}%";
992 if ( defined $orderby ) {
993 $query .= ' ORDER BY ?';
994 push @query_parameters, $orderby;
997 my $sth = $dbh->prepare($query);
998 $sth->execute( @query_parameters );
1000 while ( my $row = $sth->fetchrow_hashref ){
1006 =head2 GetItemsForInventory
1010 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size);
1014 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
1016 The sub returns a reference to a list of hashes, each containing
1017 itemnumber, author, title, barcode, item callnumber, and date last
1018 seen. It is ordered by callnumber then title.
1020 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
1021 the datelastseen can be used to specify that you want to see items not seen since a past date only.
1022 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
1026 sub GetItemsForInventory {
1027 my ( $minlocation, $maxlocation,$location, $itemtype, $datelastseen, $branch, $offset, $size ) = @_;
1028 my $dbh = C4::Context->dbh;
1030 my $query = <<'END_SQL';
1031 SELECT itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
1033 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1034 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
1035 WHERE itemcallnumber >= ?
1036 AND itemcallnumber <= ?
1038 my @bind_params = ( $minlocation, $maxlocation );
1040 if ($datelastseen) {
1041 $datelastseen = format_date_in_iso($datelastseen);
1042 $query .= ' AND (datelastseen < ? OR datelastseen IS NULL) ';
1043 push @bind_params, $datelastseen;
1047 $query.= ' AND items.location = ? ';
1048 push @bind_params, $location;
1052 $query.= ' AND items.homebranch = ? ';
1053 push @bind_params, $branch;
1057 $query.= ' AND biblioitems.itemtype = ? ';
1058 push @bind_params, $itemtype;
1061 $query .= ' ORDER BY itemcallnumber, title';
1062 my $sth = $dbh->prepare($query);
1063 $sth->execute( @bind_params );
1067 while ( my $row = $sth->fetchrow_hashref ) {
1068 $offset-- if ($offset);
1069 $row->{datelastseen}=format_date($row->{datelastseen});
1070 if ( ( !$offset ) && $size ) {
1071 push @results, $row;
1078 =head2 GetItemsCount
1081 $count = &GetItemsCount( $biblionumber);
1085 This function return count of item with $biblionumber
1090 my ( $biblionumber ) = @_;
1091 my $dbh = C4::Context->dbh;
1092 my $query = "SELECT count(*)
1094 WHERE biblionumber=?";
1095 my $sth = $dbh->prepare($query);
1096 $sth->execute($biblionumber);
1097 my $count = $sth->fetchrow;
1102 =head2 GetItemInfosOf
1106 GetItemInfosOf(@itemnumbers);
1112 sub GetItemInfosOf {
1113 my @itemnumbers = @_;
1118 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1120 return get_infos_of( $query, 'itemnumber' );
1123 =head2 GetItemsByBiblioitemnumber
1127 GetItemsByBiblioitemnumber($biblioitemnumber);
1131 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1132 Called by C<C4::XISBN>
1136 sub GetItemsByBiblioitemnumber {
1137 my ( $bibitem ) = @_;
1138 my $dbh = C4::Context->dbh;
1139 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1140 # Get all items attached to a biblioitem
1143 $sth->execute($bibitem) || die $sth->errstr;
1144 while ( my $data = $sth->fetchrow_hashref ) {
1145 # Foreach item, get circulation information
1146 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1147 WHERE itemnumber = ?
1148 AND issues.borrowernumber = borrowers.borrowernumber"
1150 $sth2->execute( $data->{'itemnumber'} );
1151 if ( my $data2 = $sth2->fetchrow_hashref ) {
1152 # if item is out, set the due date and who it is out too
1153 $data->{'date_due'} = $data2->{'date_due'};
1154 $data->{'cardnumber'} = $data2->{'cardnumber'};
1155 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1158 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1159 $data->{'date_due'} = '';
1162 # Find the last 3 people who borrowed this item.
1163 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1164 AND old_issues.borrowernumber = borrowers.borrowernumber
1165 ORDER BY returndate desc,timestamp desc LIMIT 3";
1166 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1167 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1169 while ( my $data2 = $sth2->fetchrow_hashref ) {
1170 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1171 $data->{"card$i2"} = $data2->{'cardnumber'};
1172 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1176 push(@results,$data);
1186 @results = GetItemsInfo($biblionumber, $type);
1190 Returns information about books with the given biblionumber.
1192 C<$type> may be either C<intra> or anything else. If it is not set to
1193 C<intra>, then the search will exclude lost, very overdue, and
1196 C<GetItemsInfo> returns a list of references-to-hash. Each element
1197 contains a number of keys. Most of them are table items from the
1198 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1199 Koha database. Other keys include:
1203 =item C<$data-E<gt>{branchname}>
1205 The name (not the code) of the branch to which the book belongs.
1207 =item C<$data-E<gt>{datelastseen}>
1209 This is simply C<items.datelastseen>, except that while the date is
1210 stored in YYYY-MM-DD format in the database, here it is converted to
1211 DD/MM/YYYY format. A NULL date is returned as C<//>.
1213 =item C<$data-E<gt>{datedue}>
1215 =item C<$data-E<gt>{class}>
1217 This is the concatenation of C<biblioitems.classification>, the book's
1218 Dewey code, and C<biblioitems.subclass>.
1220 =item C<$data-E<gt>{ocount}>
1222 I think this is the number of copies of the book available.
1224 =item C<$data-E<gt>{order}>
1226 If this is set, it is set to C<One Order>.
1233 my ( $biblionumber, $type ) = @_;
1234 my $dbh = C4::Context->dbh;
1235 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1241 biblioitems.itemtype,
1244 biblioitems.publicationyear,
1245 biblioitems.publishercode,
1246 biblioitems.volumedate,
1247 biblioitems.volumedesc,
1250 items.notforloan as itemnotforloan,
1251 itemtypes.description
1253 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1254 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1255 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1256 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1257 $query .= " WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1258 my $sth = $dbh->prepare($query);
1259 $sth->execute($biblionumber);
1262 my ( $date_due, $count_reserves, $serial );
1264 my $isth = $dbh->prepare(
1265 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1266 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1267 WHERE itemnumber = ?"
1269 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1270 while ( my $data = $sth->fetchrow_hashref ) {
1272 $isth->execute( $data->{'itemnumber'} );
1273 if ( my $idata = $isth->fetchrow_hashref ) {
1274 $data->{borrowernumber} = $idata->{borrowernumber};
1275 $data->{cardnumber} = $idata->{cardnumber};
1276 $data->{surname} = $idata->{surname};
1277 $data->{firstname} = $idata->{firstname};
1278 $datedue = $idata->{'date_due'};
1279 if (C4::Context->preference("IndependantBranches")){
1280 my $userenv = C4::Context->userenv;
1281 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1282 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1286 if ( $data->{'serial'}) {
1287 $ssth->execute($data->{'itemnumber'}) ;
1288 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1291 if ( $datedue eq '' ) {
1292 my ( $restype, $reserves ) =
1293 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1295 $count_reserves = $restype;
1300 #get branch information.....
1301 my $bsth = $dbh->prepare(
1302 "SELECT * FROM branches WHERE branchcode = ?
1305 $bsth->execute( $data->{'holdingbranch'} );
1306 if ( my $bdata = $bsth->fetchrow_hashref ) {
1307 $data->{'branchname'} = $bdata->{'branchname'};
1309 $data->{'datedue'} = $datedue;
1310 $data->{'count_reserves'} = $count_reserves;
1312 # get notforloan complete status if applicable
1313 my $sthnflstatus = $dbh->prepare(
1314 'SELECT authorised_value
1315 FROM marc_subfield_structure
1316 WHERE kohafield="items.notforloan"
1320 $sthnflstatus->execute;
1321 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1322 if ($authorised_valuecode) {
1323 $sthnflstatus = $dbh->prepare(
1324 "SELECT lib FROM authorised_values
1326 AND authorised_value=?"
1328 $sthnflstatus->execute( $authorised_valuecode,
1329 $data->{itemnotforloan} );
1330 my ($lib) = $sthnflstatus->fetchrow;
1331 $data->{notforloanvalue} = $lib;
1333 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1335 # my stack procedures
1336 my $stackstatus = $dbh->prepare(
1337 'SELECT authorised_value
1338 FROM marc_subfield_structure
1339 WHERE kohafield="items.stack"
1342 $stackstatus->execute;
1344 ($authorised_valuecode) = $stackstatus->fetchrow;
1345 if ($authorised_valuecode) {
1346 $stackstatus = $dbh->prepare(
1348 FROM authorised_values
1350 AND authorised_value=?
1353 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1354 my ($lib) = $stackstatus->fetchrow;
1355 $data->{stack} = $lib;
1357 # Find the last 3 people who borrowed this item.
1358 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1359 WHERE itemnumber = ?
1360 AND old_issues.borrowernumber = borrowers.borrowernumber
1361 ORDER BY returndate DESC
1363 $sth2->execute($data->{'itemnumber'});
1365 while (my $data2 = $sth2->fetchrow_hashref()) {
1366 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1367 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1368 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1372 $results[$i] = $data;
1376 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1382 =head2 get_itemnumbers_of
1386 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1390 Given a list of biblionumbers, return the list of corresponding itemnumbers
1391 for each biblionumber.
1393 Return a reference on a hash where keys are biblionumbers and values are
1394 references on array of itemnumbers.
1398 sub get_itemnumbers_of {
1399 my @biblionumbers = @_;
1401 my $dbh = C4::Context->dbh;
1407 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1409 my $sth = $dbh->prepare($query);
1410 $sth->execute(@biblionumbers);
1414 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1415 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1418 return \%itemnumbers_of;
1421 =head2 GetItemnumberFromBarcode
1425 $result = GetItemnumberFromBarcode($barcode);
1431 sub GetItemnumberFromBarcode {
1433 my $dbh = C4::Context->dbh;
1436 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1437 $rq->execute($barcode);
1438 my ($result) = $rq->fetchrow;
1442 =head3 get_item_authorised_values
1444 find the types and values for all authorised values assigned to this item.
1449 returns: a hashref malling the authorised value to the value set for this itemnumber
1451 $authorised_values = {
1457 'RESTRICTED' => undef,
1460 'branches' => 'CPL',
1461 'cn_source' => undef,
1462 'itemtypes' => 'SER',
1465 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1469 sub get_item_authorised_values {
1470 my $itemnumber = shift;
1472 # assume that these entries in the authorised_value table are item level.
1473 my $query = q(SELECT distinct authorised_value, kohafield
1474 FROM marc_subfield_structure
1475 WHERE kohafield like 'item%'
1476 AND authorised_value != '' );
1478 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1479 my $iteminfo = GetItem( $itemnumber );
1480 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1482 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1483 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1484 $field =~ s/^items\.//;
1485 if ( exists $iteminfo->{ $field } ) {
1486 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1489 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1493 =head3 get_authorised_value_images
1495 find a list of icons that are appropriate for display based on the
1496 authorised values for a biblio.
1498 parameters: listref of authorised values, such as comes from
1499 get_item_ahtorised_values or
1500 from C4::Biblio::get_biblio_authorised_values
1502 returns: listref of hashrefs for each image. Each hashref looks like
1505 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1510 Notes: Currently, I put on the full path to the images on the staff
1511 side. This should either be configurable or not done at all. Since I
1512 have to deal with 'intranet' or 'opac' in
1513 get_biblio_authorised_values, perhaps I should be passing it in.
1517 sub get_authorised_value_images {
1518 my $authorised_values = shift;
1522 my $authorised_value_list = GetAuthorisedValues();
1523 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1524 foreach my $this_authorised_value ( @$authorised_value_list ) {
1525 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1526 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1527 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1528 if ( defined $this_authorised_value->{'imageurl'} ) {
1529 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1530 label => $this_authorised_value->{'lib'},
1531 category => $this_authorised_value->{'category'},
1532 value => $this_authorised_value->{'authorised_value'}, };
1537 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1542 =head1 LIMITED USE FUNCTIONS
1544 The following functions, while part of the public API,
1545 are not exported. This is generally because they are
1546 meant to be used by only one script for a specific
1547 purpose, and should not be used in any other context
1548 without careful thought.
1556 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1560 Returns MARC::Record of the item passed in parameter.
1561 This function is meant for use only in C<cataloguing/additem.pl>,
1562 where it is needed to support that script's MARC-like
1568 my ( $biblionumber, $itemnumber ) = @_;
1570 # GetMarcItem has been revised so that it does the following:
1571 # 1. Gets the item information from the items table.
1572 # 2. Converts it to a MARC field for storage in the bib record.
1574 # The previous behavior was:
1575 # 1. Get the bib record.
1576 # 2. Return the MARC tag corresponding to the item record.
1578 # The difference is that one treats the items row as authoritative,
1579 # while the other treats the MARC representation as authoritative
1580 # under certain circumstances.
1582 my $itemrecord = GetItem($itemnumber);
1584 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1585 # Also, don't emit a subfield if the underlying field is blank.
1588 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1589 } keys %{ $itemrecord }
1591 my $itemmarc = TransformKohaToMarc($mungeditem);
1593 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1594 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1595 my @fields = $itemmarc->fields();
1596 if ($#fields > -1) {
1597 $fields[0]->add_subfields(@$unlinked_item_subfields);
1605 =head1 PRIVATE FUNCTIONS AND VARIABLES
1607 The following functions are not meant to be called
1608 directly, but are documented in order to explain
1609 the inner workings of C<C4::Items>.
1613 =head2 %derived_columns
1615 This hash keeps track of item columns that
1616 are strictly derived from other columns in
1617 the item record and are not meant to be set
1620 Each key in the hash should be the name of a
1621 column (as named by TransformMarcToKoha). Each
1622 value should be hashref whose keys are the
1623 columns on which the derived column depends. The
1624 hashref should also contain a 'BUILDER' key
1625 that is a reference to a sub that calculates
1630 my %derived_columns = (
1631 'items.cn_sort' => {
1632 'itemcallnumber' => 1,
1633 'items.cn_source' => 1,
1634 'BUILDER' => \&_calc_items_cn_sort,
1638 =head2 _set_derived_columns_for_add
1642 _set_derived_column_for_add($item);
1646 Given an item hash representing a new item to be added,
1647 calculate any derived columns. Currently the only
1648 such column is C<items.cn_sort>.
1652 sub _set_derived_columns_for_add {
1655 foreach my $column (keys %derived_columns) {
1656 my $builder = $derived_columns{$column}->{'BUILDER'};
1657 my $source_values = {};
1658 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1659 next if $source_column eq 'BUILDER';
1660 $source_values->{$source_column} = $item->{$source_column};
1662 $builder->($item, $source_values);
1666 =head2 _set_derived_columns_for_mod
1670 _set_derived_column_for_mod($item);
1674 Given an item hash representing a new item to be modified.
1675 calculate any derived columns. Currently the only
1676 such column is C<items.cn_sort>.
1678 This routine differs from C<_set_derived_columns_for_add>
1679 in that it needs to handle partial item records. In other
1680 words, the caller of C<ModItem> may have supplied only one
1681 or two columns to be changed, so this function needs to
1682 determine whether any of the columns to be changed affect
1683 any of the derived columns. Also, if a derived column
1684 depends on more than one column, but the caller is not
1685 changing all of then, this routine retrieves the unchanged
1686 values from the database in order to ensure a correct
1691 sub _set_derived_columns_for_mod {
1694 foreach my $column (keys %derived_columns) {
1695 my $builder = $derived_columns{$column}->{'BUILDER'};
1696 my $source_values = {};
1697 my %missing_sources = ();
1698 my $must_recalc = 0;
1699 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1700 next if $source_column eq 'BUILDER';
1701 if (exists $item->{$source_column}) {
1703 $source_values->{$source_column} = $item->{$source_column};
1705 $missing_sources{$source_column} = 1;
1709 foreach my $source_column (keys %missing_sources) {
1710 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1712 $builder->($item, $source_values);
1717 =head2 _do_column_fixes_for_mod
1721 _do_column_fixes_for_mod($item);
1725 Given an item hashref containing one or more
1726 columns to modify, fix up certain values.
1727 Specifically, set to 0 any passed value
1728 of C<notforloan>, C<damaged>, C<itemlost>, or
1729 C<wthdrawn> that is either undefined or
1730 contains the empty string.
1734 sub _do_column_fixes_for_mod {
1737 if (exists $item->{'notforloan'} and
1738 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1739 $item->{'notforloan'} = 0;
1741 if (exists $item->{'damaged'} and
1742 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1743 $item->{'damaged'} = 0;
1745 if (exists $item->{'itemlost'} and
1746 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1747 $item->{'itemlost'} = 0;
1749 if (exists $item->{'wthdrawn'} and
1750 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1751 $item->{'wthdrawn'} = 0;
1755 =head2 _get_single_item_column
1759 _get_single_item_column($column, $itemnumber);
1763 Retrieves the value of a single column from an C<items>
1764 row specified by C<$itemnumber>.
1768 sub _get_single_item_column {
1770 my $itemnumber = shift;
1772 my $dbh = C4::Context->dbh;
1773 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1774 $sth->execute($itemnumber);
1775 my ($value) = $sth->fetchrow();
1779 =head2 _calc_items_cn_sort
1783 _calc_items_cn_sort($item, $source_values);
1787 Helper routine to calculate C<items.cn_sort>.
1791 sub _calc_items_cn_sort {
1793 my $source_values = shift;
1795 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1798 =head2 _set_defaults_for_add
1802 _set_defaults_for_add($item_hash);
1806 Given an item hash representing an item to be added, set
1807 correct default values for columns whose default value
1808 is not handled by the DBMS. This includes the following
1815 C<items.dateaccessioned>
1837 sub _set_defaults_for_add {
1839 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1840 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1843 =head2 _koha_new_item
1847 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1851 Perform the actual insert into the C<items> table.
1855 sub _koha_new_item {
1856 my ( $item, $barcode ) = @_;
1857 my $dbh=C4::Context->dbh;
1860 "INSERT INTO items SET
1862 biblioitemnumber = ?,
1864 dateaccessioned = ?,
1868 replacementprice = ?,
1869 replacementpricedate = NOW(),
1870 datelastborrowed = ?,
1871 datelastseen = NOW(),
1894 more_subfields_xml = ?,
1897 my $sth = $dbh->prepare($query);
1899 $item->{'biblionumber'},
1900 $item->{'biblioitemnumber'},
1902 $item->{'dateaccessioned'},
1903 $item->{'booksellerid'},
1904 $item->{'homebranch'},
1906 $item->{'replacementprice'},
1907 $item->{datelastborrowed},
1909 $item->{'notforloan'},
1911 $item->{'itemlost'},
1912 $item->{'wthdrawn'},
1913 $item->{'itemcallnumber'},
1914 $item->{'restricted'},
1915 $item->{'itemnotes'},
1916 $item->{'holdingbranch'},
1918 $item->{'location'},
1921 $item->{'renewals'},
1922 $item->{'reserves'},
1923 $item->{'items.cn_source'},
1924 $item->{'items.cn_sort'},
1927 $item->{'materials'},
1929 $item->{'enumchron'},
1930 $item->{'more_subfields_xml'},
1931 $item->{'copynumber'},
1933 my $itemnumber = $dbh->{'mysql_insertid'};
1934 if ( defined $sth->errstr ) {
1935 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1938 return ( $itemnumber, $error );
1941 =head2 _koha_modify_item
1945 my ($itemnumber,$error) =_koha_modify_item( $item );
1949 Perform the actual update of the C<items> row. Note that this
1950 routine accepts a hashref specifying the columns to update.
1954 sub _koha_modify_item {
1956 my $dbh=C4::Context->dbh;
1959 my $query = "UPDATE items SET ";
1961 for my $key ( keys %$item ) {
1963 push @bind, $item->{$key};
1966 $query .= " WHERE itemnumber=?";
1967 push @bind, $item->{'itemnumber'};
1968 my $sth = C4::Context->dbh->prepare($query);
1969 $sth->execute(@bind);
1970 if ( C4::Context->dbh->errstr ) {
1971 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1975 return ($item->{'itemnumber'},$error);
1978 =head2 _koha_delete_item
1982 _koha_delete_item( $dbh, $itemnum );
1986 Internal function to delete an item record from the koha tables
1990 sub _koha_delete_item {
1991 my ( $dbh, $itemnum ) = @_;
1993 # save the deleted item to deleteditems table
1994 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1995 $sth->execute($itemnum);
1996 my $data = $sth->fetchrow_hashref();
1998 my $query = "INSERT INTO deleteditems SET ";
2000 foreach my $key ( keys %$data ) {
2001 $query .= "$key = ?,";
2002 push( @bind, $data->{$key} );
2005 $sth = $dbh->prepare($query);
2006 $sth->execute(@bind);
2009 # delete from items table
2010 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2011 $sth->execute($itemnum);
2016 =head2 _marc_from_item_hash
2020 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2024 Given an item hash representing a complete item record,
2025 create a C<MARC::Record> object containing an embedded
2026 tag representing that item.
2028 The third, optional parameter C<$unlinked_item_subfields> is
2029 an arrayref of subfields (not mapped to C<items> fields per the
2030 framework) to be added to the MARC representation
2035 sub _marc_from_item_hash {
2037 my $frameworkcode = shift;
2038 my $unlinked_item_subfields;
2040 $unlinked_item_subfields = shift;
2043 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2044 # Also, don't emit a subfield if the underlying field is blank.
2045 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2046 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2047 : () } keys %{ $item } };
2049 my $item_marc = MARC::Record->new();
2050 foreach my $item_field (keys %{ $mungeditem }) {
2051 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
2052 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2053 if (my $field = $item_marc->field($tag)) {
2054 $field->add_subfields($subfield => $mungeditem->{$item_field});
2056 my $add_subfields = [];
2057 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2058 $add_subfields = $unlinked_item_subfields;
2060 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
2067 =head2 _add_item_field_to_biblio
2071 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2075 Adds the fields from a MARC record containing the
2076 representation of a Koha item record to the MARC
2077 biblio record. The input C<$item_marc> record
2078 is expect to contain just one field, the embedded
2079 item information field.
2083 sub _add_item_field_to_biblio {
2084 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2086 my $biblio_marc = GetMarcBiblio($biblionumber);
2087 foreach my $field ($item_marc->fields()) {
2088 $biblio_marc->append_fields($field);
2091 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2094 =head2 _replace_item_field_in_biblio
2098 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2102 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2103 representation of the item, examine the biblio MARC
2104 for the corresponding tag for that item and
2105 replace it with the tag from C<$item_marc>.
2109 sub _replace_item_field_in_biblio {
2110 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2111 my $dbh = C4::Context->dbh;
2113 # get complete MARC record & replace the item field by the new one
2114 my $completeRecord = GetMarcBiblio($biblionumber);
2115 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2116 my $itemField = $ItemRecord->field($itemtag);
2117 my @items = $completeRecord->field($itemtag);
2120 if ($_->subfield($itemsubfield) eq $itemnumber) {
2121 $_->replace_with($itemField);
2127 # If we haven't found the matching field,
2128 # just add it. However, this means that
2129 # there is likely a bug.
2130 $completeRecord->append_fields($itemField);
2134 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2137 =head2 _repack_item_errors
2139 Add an error message hash generated by C<CheckItemPreSave>
2140 to a list of errors.
2144 sub _repack_item_errors {
2145 my $item_sequence_num = shift;
2146 my $item_ref = shift;
2147 my $error_ref = shift;
2149 my @repacked_errors = ();
2151 foreach my $error_code (sort keys %{ $error_ref }) {
2152 my $repacked_error = {};
2153 $repacked_error->{'item_sequence'} = $item_sequence_num;
2154 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2155 $repacked_error->{'error_code'} = $error_code;
2156 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2157 push @repacked_errors, $repacked_error;
2160 return @repacked_errors;
2163 =head2 _get_unlinked_item_subfields
2167 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2173 sub _get_unlinked_item_subfields {
2174 my $original_item_marc = shift;
2175 my $frameworkcode = shift;
2177 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2179 # assume that this record has only one field, and that that
2180 # field contains only the item information
2182 my @fields = $original_item_marc->fields();
2183 if ($#fields > -1) {
2184 my $field = $fields[0];
2185 my $tag = $field->tag();
2186 foreach my $subfield ($field->subfields()) {
2187 if (defined $subfield->[1] and
2188 $subfield->[1] ne '' and
2189 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2190 push @$subfields, $subfield->[0] => $subfield->[1];
2197 =head2 _get_unlinked_subfields_xml
2201 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2207 sub _get_unlinked_subfields_xml {
2208 my $unlinked_item_subfields = shift;
2211 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2212 my $marc = MARC::Record->new();
2213 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2214 # used in the framework
2215 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2216 $marc->encoding("UTF-8");
2217 $xml = $marc->as_xml("USMARC");
2223 =head2 _parse_unlinked_item_subfields_from_xml
2227 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2233 sub _parse_unlinked_item_subfields_from_xml {
2236 return unless defined $xml and $xml ne "";
2237 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2238 my $unlinked_subfields = [];
2239 my @fields = $marc->fields();
2240 if ($#fields > -1) {
2241 foreach my $subfield ($fields[0]->subfields()) {
2242 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2245 return $unlinked_subfields;