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 );
61 GetItemsByBiblioitemnumber
64 GetItemnumberFromBarcode
70 C4::Items - item management functions
74 This module contains an API for manipulating item
75 records in Koha, and is used by cataloguing, circulation,
76 acquisitions, and serials management.
78 A Koha item record is stored in two places: the
79 items table and embedded in a MARC tag in the XML
80 version of the associated bib record in C<biblioitems.marcxml>.
81 This is done to allow the item information to be readily
82 indexed (e.g., by Zebra), but means that each item
83 modification transaction must keep the items table
84 and the MARC XML in sync at all times.
86 Consequently, all code that creates, modifies, or deletes
87 item records B<must> use an appropriate function from
88 C<C4::Items>. If no existing function is suitable, it is
89 better to add one to C<C4::Items> than to use add
90 one-off SQL statements to add or modify items.
92 The items table will be considered authoritative. In other
93 words, if there is ever a discrepancy between the items
94 table and the MARC XML, the items table should be considered
97 =head1 HISTORICAL NOTE
99 Most of the functions in C<C4::Items> were originally in
100 the C<C4::Biblio> module.
102 =head1 CORE EXPORTED FUNCTIONS
104 The following functions are meant for use by users
113 $item = GetItem($itemnumber,$barcode,$serial);
117 Return item information, for a given itemnumber or barcode.
118 The return value is a hashref mapping item column
119 names to values. If C<$serial> is true, include serial publication data.
124 my ($itemnumber,$barcode, $serial) = @_;
125 my $dbh = C4::Context->dbh;
128 my $sth = $dbh->prepare("
130 WHERE itemnumber = ?");
131 $sth->execute($itemnumber);
132 $data = $sth->fetchrow_hashref;
134 my $sth = $dbh->prepare("
138 $sth->execute($barcode);
139 $data = $sth->fetchrow_hashref;
142 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
143 $ssth->execute($data->{'itemnumber'}) ;
144 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
145 warn $data->{'serialseq'} , $data->{'publisheddate'};
147 #if we don't have an items.itype, use biblioitems.itemtype.
148 if( ! $data->{'itype'} ) {
149 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
150 $sth->execute($data->{'biblionumber'});
151 ($data->{'itype'}) = $sth->fetchrow_array;
156 =head2 AddItemFromMarc
160 my ($biblionumber, $biblioitemnumber, $itemnumber)
161 = AddItemFromMarc($source_item_marc, $biblionumber);
165 Given a MARC::Record object containing an embedded item
166 record and a biblionumber, create a new item record.
170 sub AddItemFromMarc {
171 my ( $source_item_marc, $biblionumber ) = @_;
172 my $dbh = C4::Context->dbh;
174 # parse item hash from MARC
175 my $frameworkcode = GetFrameworkCode( $biblionumber );
176 my $item = &TransformMarcToKoha( $dbh, $source_item_marc, $frameworkcode );
177 my $unlinked_item_subfields = _get_unlinked_item_subfields($source_item_marc, $frameworkcode);
178 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
185 my ($biblionumber, $biblioitemnumber, $itemnumber)
186 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
190 Given a hash containing item column names as keys,
191 create a new Koha item record.
193 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
194 do not need to be supplied for general use; they exist
195 simply to allow them to be picked up from AddItemFromMarc.
197 The final optional parameter, C<$unlinked_item_subfields>, contains
198 an arrayref containing subfields present in the original MARC
199 representation of the item (e.g., from the item editor) that are
200 not mapped to C<items> columns directly but should instead
201 be stored in C<items.more_subfields_xml> and included in
202 the biblio items tag for display and indexing.
208 my $biblionumber = shift;
210 my $dbh = @_ ? shift : C4::Context->dbh;
211 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
212 my $unlinked_item_subfields;
214 $unlinked_item_subfields = shift
217 # needs old biblionumber and biblioitemnumber
218 $item->{'biblionumber'} = $biblionumber;
219 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
220 $sth->execute( $item->{'biblionumber'} );
221 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
223 _set_defaults_for_add($item);
224 _set_derived_columns_for_add($item);
225 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
226 # FIXME - checks here
227 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
228 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
229 $itype_sth->execute( $item->{'biblionumber'} );
230 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
233 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
234 $item->{'itemnumber'} = $itemnumber;
236 # create MARC tag representing item and add to bib
237 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
238 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
240 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
242 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
245 =head2 AddItemBatchFromMarc
249 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
253 Efficiently create item records from a MARC biblio record with
254 embedded item fields. This routine is suitable for batch jobs.
256 This API assumes that the bib record has already been
257 saved to the C<biblio> and C<biblioitems> tables. It does
258 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
259 are populated, but it will do so via a call to ModBibiloMarc.
261 The goal of this API is to have a similar effect to using AddBiblio
262 and AddItems in succession, but without inefficient repeated
263 parsing of the MARC XML bib record.
265 This function returns an arrayref of new itemsnumbers and an arrayref of item
266 errors encountered during the processing. Each entry in the errors
267 list is a hashref containing the following keys:
273 Sequence number of original item tag in the MARC record.
277 Item barcode, provide to assist in the construction of
278 useful error messages.
280 =item error_condition
282 Code representing the error condition. Can be 'duplicate_barcode',
283 'invalid_homebranch', or 'invalid_holdingbranch'.
285 =item error_information
287 Additional information appropriate to the error condition.
293 sub AddItemBatchFromMarc {
294 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
296 my @itemnumbers = ();
298 my $dbh = C4::Context->dbh;
300 # loop through the item tags and start creating items
301 my @bad_item_fields = ();
302 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
303 my $item_sequence_num = 0;
304 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
305 $item_sequence_num++;
306 # we take the item field and stick it into a new
307 # MARC record -- this is required so far because (FIXME)
308 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
309 # and there is no TransformMarcFieldToKoha
310 my $temp_item_marc = MARC::Record->new();
311 $temp_item_marc->append_fields($item_field);
313 # add biblionumber and biblioitemnumber
314 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
315 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
316 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
317 $item->{'biblionumber'} = $biblionumber;
318 $item->{'biblioitemnumber'} = $biblioitemnumber;
320 # check for duplicate barcode
321 my %item_errors = CheckItemPreSave($item);
323 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
324 push @bad_item_fields, $item_field;
328 _set_defaults_for_add($item);
329 _set_derived_columns_for_add($item);
330 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
331 warn $error if $error;
332 push @itemnumbers, $itemnumber; # FIXME not checking error
333 $item->{'itemnumber'} = $itemnumber;
335 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
337 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
338 $item_field->replace_with($new_item_marc->field($itemtag));
341 # remove any MARC item fields for rejected items
342 foreach my $item_field (@bad_item_fields) {
343 $record->delete_field($item_field);
346 # update the MARC biblio
347 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
349 return (\@itemnumbers, \@errors);
352 =head2 ModItemFromMarc
356 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
360 This function updates an item record based on a supplied
361 C<MARC::Record> object containing an embedded item field.
362 This API is meant for the use of C<additem.pl>; for
363 other purposes, C<ModItem> should be used.
365 This function uses the hash %default_values_for_mod_from_marc,
366 which contains default values for item fields to
367 apply when modifying an item. This is needed beccause
368 if an item field's value is cleared, TransformMarcToKoha
369 does not include the column in the
370 hash that's passed to ModItem, which without
371 use of this hash makes it impossible to clear
372 an item field's value. See bug 2466.
374 Note that only columns that can be directly
375 changed from the cataloging and serials
376 item editors are included in this hash.
380 my %default_values_for_mod_from_marc = (
382 booksellerid => undef,
384 'items.cn_source' => undef,
387 dateaccessioned => undef,
389 holdingbranch => undef,
391 itemcallnumber => undef,
400 replacementprice => undef,
401 replacementpricedate => undef,
408 sub ModItemFromMarc {
409 my $item_marc = shift;
410 my $biblionumber = shift;
411 my $itemnumber = shift;
413 my $dbh = C4::Context->dbh;
414 my $frameworkcode = GetFrameworkCode( $biblionumber );
415 my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode );
416 foreach my $item_field (keys %default_values_for_mod_from_marc) {
417 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
419 my $unlinked_item_subfields = _get_unlinked_item_subfields($item_marc, $frameworkcode);
421 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
428 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
432 Change one or more columns in an item record and update
433 the MARC representation of the item.
435 The first argument is a hashref mapping from item column
436 names to the new values. The second and third arguments
437 are the biblionumber and itemnumber, respectively.
439 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
440 an arrayref containing subfields present in the original MARC
441 representation of the item (e.g., from the item editor) that are
442 not mapped to C<items> columns directly but should instead
443 be stored in C<items.more_subfields_xml> and included in
444 the biblio items tag for display and indexing.
446 If one of the changed columns is used to calculate
447 the derived value of a column such as C<items.cn_sort>,
448 this routine will perform the necessary calculation
455 my $biblionumber = shift;
456 my $itemnumber = shift;
458 # if $biblionumber is undefined, get it from the current item
459 unless (defined $biblionumber) {
460 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
463 my $dbh = @_ ? shift : C4::Context->dbh;
464 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
466 my $unlinked_item_subfields;
468 $unlinked_item_subfields = shift;
469 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
472 $item->{'itemnumber'} = $itemnumber or return undef;
473 _set_derived_columns_for_mod($item);
474 _do_column_fixes_for_mod($item);
477 # attempt to change itemnumber
478 # attempt to change biblionumber (if we want
479 # an API to relink an item to a different bib,
480 # it should be a separate function)
483 _koha_modify_item($item);
485 # update biblio MARC XML
486 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
488 unless (defined $unlinked_item_subfields) {
489 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
491 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
492 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
494 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
495 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
496 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
499 =head2 ModItemTransfer
503 ModItemTransfer($itenumber, $frombranch, $tobranch);
507 Marks an item as being transferred from one branch
512 sub ModItemTransfer {
513 my ( $itemnumber, $frombranch, $tobranch ) = @_;
515 my $dbh = C4::Context->dbh;
517 #new entry in branchtransfers....
518 my $sth = $dbh->prepare(
519 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
520 VALUES (?, ?, NOW(), ?)");
521 $sth->execute($itemnumber, $frombranch, $tobranch);
523 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
524 ModDateLastSeen($itemnumber);
528 =head2 ModDateLastSeen
532 ModDateLastSeen($itemnum);
536 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
537 C<$itemnum> is the item number
541 sub ModDateLastSeen {
542 my ($itemnumber) = @_;
544 my $today = C4::Dates->new();
545 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
552 DelItem($biblionumber, $itemnumber);
556 Exported function (core API) for deleting an item record in Koha.
561 my ( $dbh, $biblionumber, $itemnumber ) = @_;
563 # FIXME check the item has no current issues
565 _koha_delete_item( $dbh, $itemnumber );
567 # get the MARC record
568 my $record = GetMarcBiblio($biblionumber);
569 my $frameworkcode = GetFrameworkCode($biblionumber);
572 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
573 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
575 #search item field code
576 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
577 my @fields = $record->field($itemtag);
579 # delete the item specified
580 foreach my $field (@fields) {
581 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
582 $record->delete_field($field);
585 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
586 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
589 =head2 CheckItemPreSave
593 my $item_ref = TransformMarcToKoha($marc, 'items');
595 my %errors = CheckItemPreSave($item_ref);
596 if (exists $errors{'duplicate_barcode'}) {
597 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
598 } elsif (exists $errors{'invalid_homebranch'}) {
599 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
600 } elsif (exists $errors{'invalid_holdingbranch'}) {
601 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
608 Given a hashref containing item fields, determine if it can be
609 inserted or updated in the database. Specifically, checks for
610 database integrity issues, and returns a hash containing any
611 of the following keys, if applicable.
615 =item duplicate_barcode
617 Barcode, if it duplicates one already found in the database.
619 =item invalid_homebranch
621 Home branch, if not defined in branches table.
623 =item invalid_holdingbranch
625 Holding branch, if not defined in branches table.
629 This function does NOT implement any policy-related checks,
630 e.g., whether current operator is allowed to save an
631 item that has a given branch code.
635 sub CheckItemPreSave {
636 my $item_ref = shift;
640 # check for duplicate barcode
641 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
642 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
643 if ($existing_itemnumber) {
644 if (!exists $item_ref->{'itemnumber'} # new item
645 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
646 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
651 # check for valid home branch
652 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
653 my $branch_name = GetBranchName($item_ref->{'homebranch'});
654 unless (defined $branch_name) {
655 # relies on fact that branches.branchname is a non-NULL column,
656 # so GetBranchName returns undef only if branch does not exist
657 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
661 # check for valid holding branch
662 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
663 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
664 unless (defined $branch_name) {
665 # relies on fact that branches.branchname is a non-NULL column,
666 # so GetBranchName returns undef only if branch does not exist
667 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
675 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
677 The following functions provide various ways of
678 getting an item record, a set of item records, or
679 lists of authorized values for certain item fields.
681 Some of the functions in this group are candidates
682 for refactoring -- for example, some of the code
683 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
684 has copy-and-paste work.
692 $itemstatushash = GetItemStatus($fwkcode);
696 Returns a list of valid values for the
697 C<items.notforloan> field.
699 NOTE: does B<not> return an individual item's
702 Can be MARC dependant.
704 But basically could be can be loan or not
705 Create a status selector with the following code
707 =head3 in PERL SCRIPT
711 my $itemstatushash = getitemstatus;
713 foreach my $thisstatus (keys %$itemstatushash) {
714 my %row =(value => $thisstatus,
715 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
717 push @itemstatusloop, \%row;
719 $template->param(statusloop=>\@itemstatusloop);
727 <select name="statusloop">
728 <option value="">Default</option>
729 <!-- TMPL_LOOP name="statusloop" -->
730 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
740 # returns a reference to a hash of references to status...
743 my $dbh = C4::Context->dbh;
745 $fwk = '' unless ($fwk);
746 my ( $tag, $subfield ) =
747 GetMarcFromKohaField( "items.notforloan", $fwk );
748 if ( $tag and $subfield ) {
751 "SELECT authorised_value
752 FROM marc_subfield_structure
758 $sth->execute( $tag, $subfield, $fwk );
759 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
762 "SELECT authorised_value,lib
763 FROM authorised_values
768 $authvalsth->execute($authorisedvaluecat);
769 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
770 $itemstatus{$authorisedvalue} = $lib;
786 $itemstatus{"1"} = "Not For Loan";
790 =head2 GetItemLocation
794 $itemlochash = GetItemLocation($fwk);
798 Returns a list of valid values for the
799 C<items.location> field.
801 NOTE: does B<not> return an individual item's
804 where fwk stands for an optional framework code.
805 Create a location selector with the following code
807 =head3 in PERL SCRIPT
811 my $itemlochash = getitemlocation;
813 foreach my $thisloc (keys %$itemlochash) {
814 my $selected = 1 if $thisbranch eq $branch;
815 my %row =(locval => $thisloc,
816 selected => $selected,
817 locname => $itemlochash->{$thisloc},
819 push @itemlocloop, \%row;
821 $template->param(itemlocationloop => \@itemlocloop);
829 <select name="location">
830 <option value="">Default</option>
831 <!-- TMPL_LOOP name="itemlocationloop" -->
832 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
840 sub GetItemLocation {
842 # returns a reference to a hash of references to location...
845 my $dbh = C4::Context->dbh;
847 $fwk = '' unless ($fwk);
848 my ( $tag, $subfield ) =
849 GetMarcFromKohaField( "items.location", $fwk );
850 if ( $tag and $subfield ) {
853 "SELECT authorised_value
854 FROM marc_subfield_structure
859 $sth->execute( $tag, $subfield, $fwk );
860 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
863 "SELECT authorised_value,lib
864 FROM authorised_values
868 $authvalsth->execute($authorisedvaluecat);
869 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
870 $itemlocation{$authorisedvalue} = $lib;
873 return \%itemlocation;
886 $itemlocation{"1"} = "Not For Loan";
887 return \%itemlocation;
894 $items = GetLostItems( $where, $orderby );
898 This function gets a list of lost items.
904 C<$where> is a hashref. it containts a field of the items table as key
905 and the value to match as value. For example:
907 { barcode => 'abc123',
908 homebranch => 'CPL', }
910 C<$orderby> is a field of the items table by which the resultset
915 C<$items> is a reference to an array full of hashrefs with columns
916 from the "items" table as keys.
918 =item usage in the perl script:
920 my $where = { barcode => '0001548' };
921 my $items = GetLostItems( $where, "homebranch" );
922 $template->param( itemsloop => $items );
929 # Getting input args.
932 my $dbh = C4::Context->dbh;
937 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
938 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
939 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
941 authorised_values.category = 'LOST'
942 AND itemlost IS NOT NULL
945 my @query_parameters;
946 foreach my $key (keys %$where) {
947 $query .= " AND $key LIKE ?";
948 push @query_parameters, "%$where->{$key}%";
950 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
952 if ( defined $orderby && grep($orderby, @ordervalues)) {
953 $query .= ' ORDER BY '.$orderby;
956 my $sth = $dbh->prepare($query);
957 $sth->execute( @query_parameters );
959 while ( my $row = $sth->fetchrow_hashref ){
965 =head2 GetItemsForInventory
969 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size);
973 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
975 The sub returns a reference to a list of hashes, each containing
976 itemnumber, author, title, barcode, item callnumber, and date last
977 seen. It is ordered by callnumber then title.
979 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
980 the datelastseen can be used to specify that you want to see items not seen since a past date only.
981 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
985 sub GetItemsForInventory {
986 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branch, $offset, $size ) = @_;
987 my $dbh = C4::Context->dbh;
988 my ( @bind_params, @where_strings );
990 my $query = <<'END_SQL';
991 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
993 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
994 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
998 push @where_strings, 'itemcallnumber >= ?';
999 push @bind_params, $minlocation;
1003 push @where_strings, 'itemcallnumber <= ?';
1004 push @bind_params, $maxlocation;
1007 if ($datelastseen) {
1008 $datelastseen = format_date_in_iso($datelastseen);
1009 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
1010 push @bind_params, $datelastseen;
1014 push @where_strings, 'items.location = ?';
1015 push @bind_params, $location;
1019 push @where_strings, 'items.homebranch = ?';
1020 push @bind_params, $branch;
1024 push @where_strings, 'biblioitems.itemtype = ?';
1025 push @bind_params, $itemtype;
1028 if ( $ignoreissued) {
1029 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1030 push @where_strings, 'issues.date_due IS NULL';
1033 if ( @where_strings ) {
1035 $query .= join ' AND ', @where_strings;
1037 $query .= ' ORDER BY itemcallnumber, title';
1038 my $sth = $dbh->prepare($query);
1039 $sth->execute( @bind_params );
1043 while ( my $row = $sth->fetchrow_hashref ) {
1044 $offset-- if ($offset);
1045 $row->{datelastseen}=format_date($row->{datelastseen});
1046 if ( ( !$offset ) && $size ) {
1047 push @results, $row;
1054 =head2 GetItemsCount
1057 $count = &GetItemsCount( $biblionumber);
1061 This function return count of item with $biblionumber
1066 my ( $biblionumber ) = @_;
1067 my $dbh = C4::Context->dbh;
1068 my $query = "SELECT count(*)
1070 WHERE biblionumber=?";
1071 my $sth = $dbh->prepare($query);
1072 $sth->execute($biblionumber);
1073 my $count = $sth->fetchrow;
1078 =head2 GetItemInfosOf
1082 GetItemInfosOf(@itemnumbers);
1088 sub GetItemInfosOf {
1089 my @itemnumbers = @_;
1094 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1096 return get_infos_of( $query, 'itemnumber' );
1099 =head2 GetItemsByBiblioitemnumber
1103 GetItemsByBiblioitemnumber($biblioitemnumber);
1107 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1108 Called by C<C4::XISBN>
1112 sub GetItemsByBiblioitemnumber {
1113 my ( $bibitem ) = @_;
1114 my $dbh = C4::Context->dbh;
1115 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1116 # Get all items attached to a biblioitem
1119 $sth->execute($bibitem) || die $sth->errstr;
1120 while ( my $data = $sth->fetchrow_hashref ) {
1121 # Foreach item, get circulation information
1122 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1123 WHERE itemnumber = ?
1124 AND issues.borrowernumber = borrowers.borrowernumber"
1126 $sth2->execute( $data->{'itemnumber'} );
1127 if ( my $data2 = $sth2->fetchrow_hashref ) {
1128 # if item is out, set the due date and who it is out too
1129 $data->{'date_due'} = $data2->{'date_due'};
1130 $data->{'cardnumber'} = $data2->{'cardnumber'};
1131 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1134 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1135 $data->{'date_due'} = '';
1138 # Find the last 3 people who borrowed this item.
1139 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1140 AND old_issues.borrowernumber = borrowers.borrowernumber
1141 ORDER BY returndate desc,timestamp desc LIMIT 3";
1142 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1143 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1145 while ( my $data2 = $sth2->fetchrow_hashref ) {
1146 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1147 $data->{"card$i2"} = $data2->{'cardnumber'};
1148 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1152 push(@results,$data);
1162 @results = GetItemsInfo($biblionumber, $type);
1166 Returns information about books with the given biblionumber.
1168 C<$type> may be either C<intra> or anything else. If it is not set to
1169 C<intra>, then the search will exclude lost, very overdue, and
1172 C<GetItemsInfo> returns a list of references-to-hash. Each element
1173 contains a number of keys. Most of them are table items from the
1174 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1175 Koha database. Other keys include:
1179 =item C<$data-E<gt>{branchname}>
1181 The name (not the code) of the branch to which the book belongs.
1183 =item C<$data-E<gt>{datelastseen}>
1185 This is simply C<items.datelastseen>, except that while the date is
1186 stored in YYYY-MM-DD format in the database, here it is converted to
1187 DD/MM/YYYY format. A NULL date is returned as C<//>.
1189 =item C<$data-E<gt>{datedue}>
1191 =item C<$data-E<gt>{class}>
1193 This is the concatenation of C<biblioitems.classification>, the book's
1194 Dewey code, and C<biblioitems.subclass>.
1196 =item C<$data-E<gt>{ocount}>
1198 I think this is the number of copies of the book available.
1200 =item C<$data-E<gt>{order}>
1202 If this is set, it is set to C<One Order>.
1209 my ( $biblionumber, $type ) = @_;
1210 my $dbh = C4::Context->dbh;
1211 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1217 biblioitems.itemtype,
1220 biblioitems.publicationyear,
1221 biblioitems.publishercode,
1222 biblioitems.volumedate,
1223 biblioitems.volumedesc,
1226 items.notforloan as itemnotforloan,
1227 itemtypes.description
1229 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1230 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1231 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1232 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1233 $query .= " WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1234 my $sth = $dbh->prepare($query);
1235 $sth->execute($biblionumber);
1238 my ( $date_due, $count_reserves, $serial );
1240 my $isth = $dbh->prepare(
1241 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1242 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1243 WHERE itemnumber = ?"
1245 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1246 while ( my $data = $sth->fetchrow_hashref ) {
1248 $isth->execute( $data->{'itemnumber'} );
1249 if ( my $idata = $isth->fetchrow_hashref ) {
1250 $data->{borrowernumber} = $idata->{borrowernumber};
1251 $data->{cardnumber} = $idata->{cardnumber};
1252 $data->{surname} = $idata->{surname};
1253 $data->{firstname} = $idata->{firstname};
1254 $datedue = $idata->{'date_due'};
1255 if (C4::Context->preference("IndependantBranches")){
1256 my $userenv = C4::Context->userenv;
1257 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1258 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1262 if ( $data->{'serial'}) {
1263 $ssth->execute($data->{'itemnumber'}) ;
1264 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1267 if ( $datedue eq '' ) {
1268 my ( $restype, $reserves ) =
1269 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1271 $count_reserves = $restype;
1276 #get branch information.....
1277 my $bsth = $dbh->prepare(
1278 "SELECT * FROM branches WHERE branchcode = ?
1281 $bsth->execute( $data->{'holdingbranch'} );
1282 if ( my $bdata = $bsth->fetchrow_hashref ) {
1283 $data->{'branchname'} = $bdata->{'branchname'};
1285 $data->{'datedue'} = $datedue;
1286 $data->{'count_reserves'} = $count_reserves;
1288 # get notforloan complete status if applicable
1289 my $sthnflstatus = $dbh->prepare(
1290 'SELECT authorised_value
1291 FROM marc_subfield_structure
1292 WHERE kohafield="items.notforloan"
1296 $sthnflstatus->execute;
1297 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1298 if ($authorised_valuecode) {
1299 $sthnflstatus = $dbh->prepare(
1300 "SELECT lib FROM authorised_values
1302 AND authorised_value=?"
1304 $sthnflstatus->execute( $authorised_valuecode,
1305 $data->{itemnotforloan} );
1306 my ($lib) = $sthnflstatus->fetchrow;
1307 $data->{notforloanvalue} = $lib;
1309 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1311 # my stack procedures
1312 my $stackstatus = $dbh->prepare(
1313 'SELECT authorised_value
1314 FROM marc_subfield_structure
1315 WHERE kohafield="items.stack"
1318 $stackstatus->execute;
1320 ($authorised_valuecode) = $stackstatus->fetchrow;
1321 if ($authorised_valuecode) {
1322 $stackstatus = $dbh->prepare(
1324 FROM authorised_values
1326 AND authorised_value=?
1329 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1330 my ($lib) = $stackstatus->fetchrow;
1331 $data->{stack} = $lib;
1333 # Find the last 3 people who borrowed this item.
1334 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1335 WHERE itemnumber = ?
1336 AND old_issues.borrowernumber = borrowers.borrowernumber
1337 ORDER BY returndate DESC
1339 $sth2->execute($data->{'itemnumber'});
1341 while (my $data2 = $sth2->fetchrow_hashref()) {
1342 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1343 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1344 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1348 $results[$i] = $data;
1352 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1358 =head2 get_itemnumbers_of
1362 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1366 Given a list of biblionumbers, return the list of corresponding itemnumbers
1367 for each biblionumber.
1369 Return a reference on a hash where keys are biblionumbers and values are
1370 references on array of itemnumbers.
1374 sub get_itemnumbers_of {
1375 my @biblionumbers = @_;
1377 my $dbh = C4::Context->dbh;
1383 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1385 my $sth = $dbh->prepare($query);
1386 $sth->execute(@biblionumbers);
1390 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1391 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1394 return \%itemnumbers_of;
1397 =head2 GetItemnumberFromBarcode
1401 $result = GetItemnumberFromBarcode($barcode);
1407 sub GetItemnumberFromBarcode {
1409 my $dbh = C4::Context->dbh;
1412 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1413 $rq->execute($barcode);
1414 my ($result) = $rq->fetchrow;
1418 =head3 get_item_authorised_values
1420 find the types and values for all authorised values assigned to this item.
1425 returns: a hashref malling the authorised value to the value set for this itemnumber
1427 $authorised_values = {
1433 'RESTRICTED' => undef,
1436 'branches' => 'CPL',
1437 'cn_source' => undef,
1438 'itemtypes' => 'SER',
1441 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1445 sub get_item_authorised_values {
1446 my $itemnumber = shift;
1448 # assume that these entries in the authorised_value table are item level.
1449 my $query = q(SELECT distinct authorised_value, kohafield
1450 FROM marc_subfield_structure
1451 WHERE kohafield like 'item%'
1452 AND authorised_value != '' );
1454 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1455 my $iteminfo = GetItem( $itemnumber );
1456 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1458 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1459 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1460 $field =~ s/^items\.//;
1461 if ( exists $iteminfo->{ $field } ) {
1462 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1465 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1469 =head3 get_authorised_value_images
1471 find a list of icons that are appropriate for display based on the
1472 authorised values for a biblio.
1474 parameters: listref of authorised values, such as comes from
1475 get_item_ahtorised_values or
1476 from C4::Biblio::get_biblio_authorised_values
1478 returns: listref of hashrefs for each image. Each hashref looks like
1481 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1486 Notes: Currently, I put on the full path to the images on the staff
1487 side. This should either be configurable or not done at all. Since I
1488 have to deal with 'intranet' or 'opac' in
1489 get_biblio_authorised_values, perhaps I should be passing it in.
1493 sub get_authorised_value_images {
1494 my $authorised_values = shift;
1498 my $authorised_value_list = GetAuthorisedValues();
1499 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1500 foreach my $this_authorised_value ( @$authorised_value_list ) {
1501 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1502 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1503 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1504 if ( defined $this_authorised_value->{'imageurl'} ) {
1505 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1506 label => $this_authorised_value->{'lib'},
1507 category => $this_authorised_value->{'category'},
1508 value => $this_authorised_value->{'authorised_value'}, };
1513 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1518 =head1 LIMITED USE FUNCTIONS
1520 The following functions, while part of the public API,
1521 are not exported. This is generally because they are
1522 meant to be used by only one script for a specific
1523 purpose, and should not be used in any other context
1524 without careful thought.
1532 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1536 Returns MARC::Record of the item passed in parameter.
1537 This function is meant for use only in C<cataloguing/additem.pl>,
1538 where it is needed to support that script's MARC-like
1544 my ( $biblionumber, $itemnumber ) = @_;
1546 # GetMarcItem has been revised so that it does the following:
1547 # 1. Gets the item information from the items table.
1548 # 2. Converts it to a MARC field for storage in the bib record.
1550 # The previous behavior was:
1551 # 1. Get the bib record.
1552 # 2. Return the MARC tag corresponding to the item record.
1554 # The difference is that one treats the items row as authoritative,
1555 # while the other treats the MARC representation as authoritative
1556 # under certain circumstances.
1558 my $itemrecord = GetItem($itemnumber);
1560 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1561 # Also, don't emit a subfield if the underlying field is blank.
1564 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1565 } keys %{ $itemrecord }
1567 my $itemmarc = TransformKohaToMarc($mungeditem);
1569 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1570 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1571 my @fields = $itemmarc->fields();
1572 if ($#fields > -1) {
1573 $fields[0]->add_subfields(@$unlinked_item_subfields);
1581 =head1 PRIVATE FUNCTIONS AND VARIABLES
1583 The following functions are not meant to be called
1584 directly, but are documented in order to explain
1585 the inner workings of C<C4::Items>.
1589 =head2 %derived_columns
1591 This hash keeps track of item columns that
1592 are strictly derived from other columns in
1593 the item record and are not meant to be set
1596 Each key in the hash should be the name of a
1597 column (as named by TransformMarcToKoha). Each
1598 value should be hashref whose keys are the
1599 columns on which the derived column depends. The
1600 hashref should also contain a 'BUILDER' key
1601 that is a reference to a sub that calculates
1606 my %derived_columns = (
1607 'items.cn_sort' => {
1608 'itemcallnumber' => 1,
1609 'items.cn_source' => 1,
1610 'BUILDER' => \&_calc_items_cn_sort,
1614 =head2 _set_derived_columns_for_add
1618 _set_derived_column_for_add($item);
1622 Given an item hash representing a new item to be added,
1623 calculate any derived columns. Currently the only
1624 such column is C<items.cn_sort>.
1628 sub _set_derived_columns_for_add {
1631 foreach my $column (keys %derived_columns) {
1632 my $builder = $derived_columns{$column}->{'BUILDER'};
1633 my $source_values = {};
1634 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1635 next if $source_column eq 'BUILDER';
1636 $source_values->{$source_column} = $item->{$source_column};
1638 $builder->($item, $source_values);
1642 =head2 _set_derived_columns_for_mod
1646 _set_derived_column_for_mod($item);
1650 Given an item hash representing a new item to be modified.
1651 calculate any derived columns. Currently the only
1652 such column is C<items.cn_sort>.
1654 This routine differs from C<_set_derived_columns_for_add>
1655 in that it needs to handle partial item records. In other
1656 words, the caller of C<ModItem> may have supplied only one
1657 or two columns to be changed, so this function needs to
1658 determine whether any of the columns to be changed affect
1659 any of the derived columns. Also, if a derived column
1660 depends on more than one column, but the caller is not
1661 changing all of then, this routine retrieves the unchanged
1662 values from the database in order to ensure a correct
1667 sub _set_derived_columns_for_mod {
1670 foreach my $column (keys %derived_columns) {
1671 my $builder = $derived_columns{$column}->{'BUILDER'};
1672 my $source_values = {};
1673 my %missing_sources = ();
1674 my $must_recalc = 0;
1675 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1676 next if $source_column eq 'BUILDER';
1677 if (exists $item->{$source_column}) {
1679 $source_values->{$source_column} = $item->{$source_column};
1681 $missing_sources{$source_column} = 1;
1685 foreach my $source_column (keys %missing_sources) {
1686 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1688 $builder->($item, $source_values);
1693 =head2 _do_column_fixes_for_mod
1697 _do_column_fixes_for_mod($item);
1701 Given an item hashref containing one or more
1702 columns to modify, fix up certain values.
1703 Specifically, set to 0 any passed value
1704 of C<notforloan>, C<damaged>, C<itemlost>, or
1705 C<wthdrawn> that is either undefined or
1706 contains the empty string.
1710 sub _do_column_fixes_for_mod {
1713 if (exists $item->{'notforloan'} and
1714 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1715 $item->{'notforloan'} = 0;
1717 if (exists $item->{'damaged'} and
1718 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1719 $item->{'damaged'} = 0;
1721 if (exists $item->{'itemlost'} and
1722 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1723 $item->{'itemlost'} = 0;
1725 if (exists $item->{'wthdrawn'} and
1726 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1727 $item->{'wthdrawn'} = 0;
1731 =head2 _get_single_item_column
1735 _get_single_item_column($column, $itemnumber);
1739 Retrieves the value of a single column from an C<items>
1740 row specified by C<$itemnumber>.
1744 sub _get_single_item_column {
1746 my $itemnumber = shift;
1748 my $dbh = C4::Context->dbh;
1749 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1750 $sth->execute($itemnumber);
1751 my ($value) = $sth->fetchrow();
1755 =head2 _calc_items_cn_sort
1759 _calc_items_cn_sort($item, $source_values);
1763 Helper routine to calculate C<items.cn_sort>.
1767 sub _calc_items_cn_sort {
1769 my $source_values = shift;
1771 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1774 =head2 _set_defaults_for_add
1778 _set_defaults_for_add($item_hash);
1782 Given an item hash representing an item to be added, set
1783 correct default values for columns whose default value
1784 is not handled by the DBMS. This includes the following
1791 C<items.dateaccessioned>
1813 sub _set_defaults_for_add {
1815 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
1816 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
1819 =head2 _koha_new_item
1823 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1827 Perform the actual insert into the C<items> table.
1831 sub _koha_new_item {
1832 my ( $item, $barcode ) = @_;
1833 my $dbh=C4::Context->dbh;
1836 "INSERT INTO items SET
1838 biblioitemnumber = ?,
1840 dateaccessioned = ?,
1844 replacementprice = ?,
1845 replacementpricedate = NOW(),
1846 datelastborrowed = ?,
1847 datelastseen = NOW(),
1870 more_subfields_xml = ?,
1873 my $sth = $dbh->prepare($query);
1875 $item->{'biblionumber'},
1876 $item->{'biblioitemnumber'},
1878 $item->{'dateaccessioned'},
1879 $item->{'booksellerid'},
1880 $item->{'homebranch'},
1882 $item->{'replacementprice'},
1883 $item->{datelastborrowed},
1885 $item->{'notforloan'},
1887 $item->{'itemlost'},
1888 $item->{'wthdrawn'},
1889 $item->{'itemcallnumber'},
1890 $item->{'restricted'},
1891 $item->{'itemnotes'},
1892 $item->{'holdingbranch'},
1894 $item->{'location'},
1897 $item->{'renewals'},
1898 $item->{'reserves'},
1899 $item->{'items.cn_source'},
1900 $item->{'items.cn_sort'},
1903 $item->{'materials'},
1905 $item->{'enumchron'},
1906 $item->{'more_subfields_xml'},
1907 $item->{'copynumber'},
1909 my $itemnumber = $dbh->{'mysql_insertid'};
1910 if ( defined $sth->errstr ) {
1911 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1914 return ( $itemnumber, $error );
1917 =head2 _koha_modify_item
1921 my ($itemnumber,$error) =_koha_modify_item( $item );
1925 Perform the actual update of the C<items> row. Note that this
1926 routine accepts a hashref specifying the columns to update.
1930 sub _koha_modify_item {
1932 my $dbh=C4::Context->dbh;
1935 my $query = "UPDATE items SET ";
1937 for my $key ( keys %$item ) {
1939 push @bind, $item->{$key};
1942 $query .= " WHERE itemnumber=?";
1943 push @bind, $item->{'itemnumber'};
1944 my $sth = C4::Context->dbh->prepare($query);
1945 $sth->execute(@bind);
1946 if ( C4::Context->dbh->errstr ) {
1947 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1951 return ($item->{'itemnumber'},$error);
1954 =head2 _koha_delete_item
1958 _koha_delete_item( $dbh, $itemnum );
1962 Internal function to delete an item record from the koha tables
1966 sub _koha_delete_item {
1967 my ( $dbh, $itemnum ) = @_;
1969 # save the deleted item to deleteditems table
1970 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1971 $sth->execute($itemnum);
1972 my $data = $sth->fetchrow_hashref();
1974 my $query = "INSERT INTO deleteditems SET ";
1976 foreach my $key ( keys %$data ) {
1977 $query .= "$key = ?,";
1978 push( @bind, $data->{$key} );
1981 $sth = $dbh->prepare($query);
1982 $sth->execute(@bind);
1985 # delete from items table
1986 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1987 $sth->execute($itemnum);
1992 =head2 _marc_from_item_hash
1996 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2000 Given an item hash representing a complete item record,
2001 create a C<MARC::Record> object containing an embedded
2002 tag representing that item.
2004 The third, optional parameter C<$unlinked_item_subfields> is
2005 an arrayref of subfields (not mapped to C<items> fields per the
2006 framework) to be added to the MARC representation
2011 sub _marc_from_item_hash {
2013 my $frameworkcode = shift;
2014 my $unlinked_item_subfields;
2016 $unlinked_item_subfields = shift;
2019 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2020 # Also, don't emit a subfield if the underlying field is blank.
2021 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2022 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2023 : () } keys %{ $item } };
2025 my $item_marc = MARC::Record->new();
2026 foreach my $item_field (keys %{ $mungeditem }) {
2027 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
2028 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2029 if (my $field = $item_marc->field($tag)) {
2030 $field->add_subfields($subfield => $mungeditem->{$item_field});
2032 my $add_subfields = [];
2033 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2034 $add_subfields = $unlinked_item_subfields;
2036 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
2043 =head2 _add_item_field_to_biblio
2047 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2051 Adds the fields from a MARC record containing the
2052 representation of a Koha item record to the MARC
2053 biblio record. The input C<$item_marc> record
2054 is expect to contain just one field, the embedded
2055 item information field.
2059 sub _add_item_field_to_biblio {
2060 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2062 my $biblio_marc = GetMarcBiblio($biblionumber);
2063 foreach my $field ($item_marc->fields()) {
2064 $biblio_marc->append_fields($field);
2067 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2070 =head2 _replace_item_field_in_biblio
2074 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2078 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2079 representation of the item, examine the biblio MARC
2080 for the corresponding tag for that item and
2081 replace it with the tag from C<$item_marc>.
2085 sub _replace_item_field_in_biblio {
2086 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2087 my $dbh = C4::Context->dbh;
2089 # get complete MARC record & replace the item field by the new one
2090 my $completeRecord = GetMarcBiblio($biblionumber);
2091 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2092 my $itemField = $ItemRecord->field($itemtag);
2093 my @items = $completeRecord->field($itemtag);
2096 if ($_->subfield($itemsubfield) eq $itemnumber) {
2097 $_->replace_with($itemField);
2103 # If we haven't found the matching field,
2104 # just add it. However, this means that
2105 # there is likely a bug.
2106 $completeRecord->append_fields($itemField);
2110 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2113 =head2 _repack_item_errors
2115 Add an error message hash generated by C<CheckItemPreSave>
2116 to a list of errors.
2120 sub _repack_item_errors {
2121 my $item_sequence_num = shift;
2122 my $item_ref = shift;
2123 my $error_ref = shift;
2125 my @repacked_errors = ();
2127 foreach my $error_code (sort keys %{ $error_ref }) {
2128 my $repacked_error = {};
2129 $repacked_error->{'item_sequence'} = $item_sequence_num;
2130 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2131 $repacked_error->{'error_code'} = $error_code;
2132 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2133 push @repacked_errors, $repacked_error;
2136 return @repacked_errors;
2139 =head2 _get_unlinked_item_subfields
2143 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2149 sub _get_unlinked_item_subfields {
2150 my $original_item_marc = shift;
2151 my $frameworkcode = shift;
2153 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2155 # assume that this record has only one field, and that that
2156 # field contains only the item information
2158 my @fields = $original_item_marc->fields();
2159 if ($#fields > -1) {
2160 my $field = $fields[0];
2161 my $tag = $field->tag();
2162 foreach my $subfield ($field->subfields()) {
2163 if (defined $subfield->[1] and
2164 $subfield->[1] ne '' and
2165 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2166 push @$subfields, $subfield->[0] => $subfield->[1];
2173 =head2 _get_unlinked_subfields_xml
2177 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2183 sub _get_unlinked_subfields_xml {
2184 my $unlinked_item_subfields = shift;
2187 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2188 my $marc = MARC::Record->new();
2189 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2190 # used in the framework
2191 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2192 $marc->encoding("UTF-8");
2193 $xml = $marc->as_xml("USMARC");
2199 =head2 _parse_unlinked_item_subfields_from_xml
2203 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2209 sub _parse_unlinked_item_subfields_from_xml {
2212 return unless defined $xml and $xml ne "";
2213 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2214 my $unlinked_subfields = [];
2215 my @fields = $marc->fields();
2216 if ($#fields > -1) {
2217 foreach my $subfield ($fields[0]->subfields()) {
2218 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2221 return $unlinked_subfields;