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 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
228 $item->{'itemnumber'} = $itemnumber;
230 # create MARC tag representing item and add to bib
231 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
232 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
234 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
236 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
239 =head2 AddItemBatchFromMarc
243 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
247 Efficiently create item records from a MARC biblio record with
248 embedded item fields. This routine is suitable for batch jobs.
250 This API assumes that the bib record has already been
251 saved to the C<biblio> and C<biblioitems> tables. It does
252 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
253 are populated, but it will do so via a call to ModBibiloMarc.
255 The goal of this API is to have a similar effect to using AddBiblio
256 and AddItems in succession, but without inefficient repeated
257 parsing of the MARC XML bib record.
259 This function returns an arrayref of new itemsnumbers and an arrayref of item
260 errors encountered during the processing. Each entry in the errors
261 list is a hashref containing the following keys:
267 Sequence number of original item tag in the MARC record.
271 Item barcode, provide to assist in the construction of
272 useful error messages.
274 =item error_condition
276 Code representing the error condition. Can be 'duplicate_barcode',
277 'invalid_homebranch', or 'invalid_holdingbranch'.
279 =item error_information
281 Additional information appropriate to the error condition.
287 sub AddItemBatchFromMarc {
288 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
290 my @itemnumbers = ();
292 my $dbh = C4::Context->dbh;
294 # loop through the item tags and start creating items
295 my @bad_item_fields = ();
296 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
297 my $item_sequence_num = 0;
298 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
299 $item_sequence_num++;
300 # we take the item field and stick it into a new
301 # MARC record -- this is required so far because (FIXME)
302 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
303 # and there is no TransformMarcFieldToKoha
304 my $temp_item_marc = MARC::Record->new();
305 $temp_item_marc->append_fields($item_field);
307 # add biblionumber and biblioitemnumber
308 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
309 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
310 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
311 $item->{'biblionumber'} = $biblionumber;
312 $item->{'biblioitemnumber'} = $biblioitemnumber;
314 # check for duplicate barcode
315 my %item_errors = CheckItemPreSave($item);
317 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
318 push @bad_item_fields, $item_field;
322 _set_defaults_for_add($item);
323 _set_derived_columns_for_add($item);
324 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
325 warn $error if $error;
326 push @itemnumbers, $itemnumber; # FIXME not checking error
327 $item->{'itemnumber'} = $itemnumber;
329 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
331 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
332 $item_field->replace_with($new_item_marc->field($itemtag));
335 # remove any MARC item fields for rejected items
336 foreach my $item_field (@bad_item_fields) {
337 $record->delete_field($item_field);
340 # update the MARC biblio
341 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
343 return (\@itemnumbers, \@errors);
346 =head2 ModItemFromMarc
350 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
354 This function updates an item record based on a supplied
355 C<MARC::Record> object containing an embedded item field.
356 This API is meant for the use of C<additem.pl>; for
357 other purposes, C<ModItem> should be used.
361 sub ModItemFromMarc {
362 my $item_marc = shift;
363 my $biblionumber = shift;
364 my $itemnumber = shift;
366 my $dbh = C4::Context->dbh;
367 my $frameworkcode = GetFrameworkCode( $biblionumber );
368 my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode );
369 my $unlinked_item_subfields = _get_unlinked_item_subfields($item_marc, $frameworkcode);
371 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
378 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
382 Change one or more columns in an item record and update
383 the MARC representation of the item.
385 The first argument is a hashref mapping from item column
386 names to the new values. The second and third arguments
387 are the biblionumber and itemnumber, respectively.
389 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
390 an arrayref containing subfields present in the original MARC
391 representation of the item (e.g., from the item editor) that are
392 not mapped to C<items> columns directly but should instead
393 be stored in C<items.more_subfields_xml> and included in
394 the biblio items tag for display and indexing.
396 If one of the changed columns is used to calculate
397 the derived value of a column such as C<items.cn_sort>,
398 this routine will perform the necessary calculation
405 my $biblionumber = shift;
406 my $itemnumber = shift;
408 # if $biblionumber is undefined, get it from the current item
409 unless (defined $biblionumber) {
410 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
413 my $dbh = @_ ? shift : C4::Context->dbh;
414 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
416 my $unlinked_item_subfields;
418 $unlinked_item_subfields = shift;
419 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
422 $item->{'itemnumber'} = $itemnumber or return undef;
423 _set_derived_columns_for_mod($item);
424 _do_column_fixes_for_mod($item);
427 # attempt to change itemnumber
428 # attempt to change biblionumber (if we want
429 # an API to relink an item to a different bib,
430 # it should be a separate function)
433 _koha_modify_item($item);
435 # update biblio MARC XML
436 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
438 unless (defined $unlinked_item_subfields) {
439 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
441 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
442 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
444 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
445 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
446 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
449 =head2 ModItemTransfer
453 ModItemTransfer($itenumber, $frombranch, $tobranch);
457 Marks an item as being transferred from one branch
462 sub ModItemTransfer {
463 my ( $itemnumber, $frombranch, $tobranch ) = @_;
465 my $dbh = C4::Context->dbh;
467 #new entry in branchtransfers....
468 my $sth = $dbh->prepare(
469 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
470 VALUES (?, ?, NOW(), ?)");
471 $sth->execute($itemnumber, $frombranch, $tobranch);
473 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
474 ModDateLastSeen($itemnumber);
478 =head2 ModDateLastSeen
482 ModDateLastSeen($itemnum);
486 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
487 C<$itemnum> is the item number
491 sub ModDateLastSeen {
492 my ($itemnumber) = @_;
494 my $today = C4::Dates->new();
495 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
502 DelItem($biblionumber, $itemnumber);
506 Exported function (core API) for deleting an item record in Koha.
511 my ( $dbh, $biblionumber, $itemnumber ) = @_;
513 # FIXME check the item has no current issues
515 _koha_delete_item( $dbh, $itemnumber );
517 # get the MARC record
518 my $record = GetMarcBiblio($biblionumber);
519 my $frameworkcode = GetFrameworkCode($biblionumber);
522 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
523 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
525 #search item field code
526 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
527 my @fields = $record->field($itemtag);
529 # delete the item specified
530 foreach my $field (@fields) {
531 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
532 $record->delete_field($field);
535 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
536 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
539 =head2 CheckItemPreSave
543 my $item_ref = TransformMarcToKoha($marc, 'items');
545 my %errors = CheckItemPreSave($item_ref);
546 if (exists $errors{'duplicate_barcode'}) {
547 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
548 } elsif (exists $errors{'invalid_homebranch'}) {
549 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
550 } elsif (exists $errors{'invalid_holdingbranch'}) {
551 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
558 Given a hashref containing item fields, determine if it can be
559 inserted or updated in the database. Specifically, checks for
560 database integrity issues, and returns a hash containing any
561 of the following keys, if applicable.
565 =item duplicate_barcode
567 Barcode, if it duplicates one already found in the database.
569 =item invalid_homebranch
571 Home branch, if not defined in branches table.
573 =item invalid_holdingbranch
575 Holding branch, if not defined in branches table.
579 This function does NOT implement any policy-related checks,
580 e.g., whether current operator is allowed to save an
581 item that has a given branch code.
585 sub CheckItemPreSave {
586 my $item_ref = shift;
590 # check for duplicate barcode
591 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
592 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
593 if ($existing_itemnumber) {
594 if (!exists $item_ref->{'itemnumber'} # new item
595 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
596 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
601 # check for valid home branch
602 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
603 my $branch_name = GetBranchName($item_ref->{'homebranch'});
604 unless (defined $branch_name) {
605 # relies on fact that branches.branchname is a non-NULL column,
606 # so GetBranchName returns undef only if branch does not exist
607 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
611 # check for valid holding branch
612 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
613 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
614 unless (defined $branch_name) {
615 # relies on fact that branches.branchname is a non-NULL column,
616 # so GetBranchName returns undef only if branch does not exist
617 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
625 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
627 The following functions provide various ways of
628 getting an item record, a set of item records, or
629 lists of authorized values for certain item fields.
631 Some of the functions in this group are candidates
632 for refactoring -- for example, some of the code
633 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
634 has copy-and-paste work.
642 $itemstatushash = GetItemStatus($fwkcode);
646 Returns a list of valid values for the
647 C<items.notforloan> field.
649 NOTE: does B<not> return an individual item's
652 Can be MARC dependant.
654 But basically could be can be loan or not
655 Create a status selector with the following code
657 =head3 in PERL SCRIPT
661 my $itemstatushash = getitemstatus;
663 foreach my $thisstatus (keys %$itemstatushash) {
664 my %row =(value => $thisstatus,
665 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
667 push @itemstatusloop, \%row;
669 $template->param(statusloop=>\@itemstatusloop);
677 <select name="statusloop">
678 <option value="">Default</option>
679 <!-- TMPL_LOOP name="statusloop" -->
680 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
690 # returns a reference to a hash of references to status...
693 my $dbh = C4::Context->dbh;
695 $fwk = '' unless ($fwk);
696 my ( $tag, $subfield ) =
697 GetMarcFromKohaField( "items.notforloan", $fwk );
698 if ( $tag and $subfield ) {
701 "SELECT authorised_value
702 FROM marc_subfield_structure
708 $sth->execute( $tag, $subfield, $fwk );
709 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
712 "SELECT authorised_value,lib
713 FROM authorised_values
718 $authvalsth->execute($authorisedvaluecat);
719 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
720 $itemstatus{$authorisedvalue} = $lib;
736 $itemstatus{"1"} = "Not For Loan";
740 =head2 GetItemLocation
744 $itemlochash = GetItemLocation($fwk);
748 Returns a list of valid values for the
749 C<items.location> field.
751 NOTE: does B<not> return an individual item's
754 where fwk stands for an optional framework code.
755 Create a location selector with the following code
757 =head3 in PERL SCRIPT
761 my $itemlochash = getitemlocation;
763 foreach my $thisloc (keys %$itemlochash) {
764 my $selected = 1 if $thisbranch eq $branch;
765 my %row =(locval => $thisloc,
766 selected => $selected,
767 locname => $itemlochash->{$thisloc},
769 push @itemlocloop, \%row;
771 $template->param(itemlocationloop => \@itemlocloop);
779 <select name="location">
780 <option value="">Default</option>
781 <!-- TMPL_LOOP name="itemlocationloop" -->
782 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
790 sub GetItemLocation {
792 # returns a reference to a hash of references to location...
795 my $dbh = C4::Context->dbh;
797 $fwk = '' unless ($fwk);
798 my ( $tag, $subfield ) =
799 GetMarcFromKohaField( "items.location", $fwk );
800 if ( $tag and $subfield ) {
803 "SELECT authorised_value
804 FROM marc_subfield_structure
809 $sth->execute( $tag, $subfield, $fwk );
810 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
813 "SELECT authorised_value,lib
814 FROM authorised_values
818 $authvalsth->execute($authorisedvaluecat);
819 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
820 $itemlocation{$authorisedvalue} = $lib;
823 return \%itemlocation;
836 $itemlocation{"1"} = "Not For Loan";
837 return \%itemlocation;
844 $items = GetLostItems( $where, $orderby );
848 This function gets a list of lost items.
854 C<$where> is a hashref. it containts a field of the items table as key
855 and the value to match as value. For example:
857 { barcode => 'abc123',
858 homebranch => 'CPL', }
860 C<$orderby> is a field of the items table by which the resultset
865 C<$items> is a reference to an array full of hashrefs with columns
866 from the "items" table as keys.
868 =item usage in the perl script:
870 my $where = { barcode => '0001548' };
871 my $items = GetLostItems( $where, "homebranch" );
872 $template->param( itemsloop => $items );
879 # Getting input args.
882 my $dbh = C4::Context->dbh;
886 FROM items, biblio, authorised_values
888 items.biblionumber = biblio.biblionumber
889 AND items.itemlost = authorised_values.authorised_value
890 AND authorised_values.category = 'LOST'
891 AND itemlost IS NOT NULL
895 my @query_parameters;
896 foreach my $key (keys %$where) {
897 $query .= " AND $key LIKE ?";
898 push @query_parameters, "%$where->{$key}%";
900 if ( defined $orderby ) {
901 $query .= ' ORDER BY ?';
902 push @query_parameters, $orderby;
905 my $sth = $dbh->prepare($query);
906 $sth->execute( @query_parameters );
908 while ( my $row = $sth->fetchrow_hashref ){
914 =head2 GetItemsForInventory
918 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
922 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
924 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
925 It is ordered by callnumber,title.
927 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
928 the datelastseen can be used to specify that you want to see items not seen since a past date only.
929 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
933 sub GetItemsForInventory {
934 my ( $minlocation, $maxlocation,$location, $itemtype, $datelastseen, $branch, $offset, $size ) = @_;
935 my $dbh = C4::Context->dbh;
938 $datelastseen=format_date_in_iso($datelastseen);
940 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
942 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
943 LEFT JOIN biblioitems on items.biblionumber=biblioitems.biblionumber
944 WHERE itemcallnumber>= ?
945 AND itemcallnumber <=?
946 AND (datelastseen< ? OR datelastseen IS NULL)";
947 $query.= " AND items.location=".$dbh->quote($location) if $location;
948 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
949 $query.= " AND biblioitems.itemtype=".$dbh->quote($itemtype) if $itemtype;
950 $query .= " ORDER BY itemcallnumber,title";
951 $sth = $dbh->prepare($query);
952 $sth->execute( $minlocation, $maxlocation, $datelastseen );
956 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
958 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
959 LEFT JOIN biblioitems on items.biblionumber=biblioitems.biblionumber
960 WHERE itemcallnumber>= ?
961 AND itemcallnumber <=?";
962 $query.= " AND items.location=".$dbh->quote($location) if $location;
963 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
964 $query.= " AND biblioitems.itemtype=".$dbh->quote($itemtype) if $itemtype;
965 $query .= " ORDER BY itemcallnumber,title";
966 $sth = $dbh->prepare($query);
967 $sth->execute( $minlocation, $maxlocation );
971 while ( my $row = $sth->fetchrow_hashref ) {
972 $offset-- if ($offset);
973 $row->{datelastseen}=format_date($row->{datelastseen});
974 if ( ( !$offset ) && $size ) {
985 $count = &GetItemsCount( $biblionumber);
989 This function return count of item with $biblionumber
994 my ( $biblionumber ) = @_;
995 my $dbh = C4::Context->dbh;
996 my $query = "SELECT count(*)
998 WHERE biblionumber=?";
999 my $sth = $dbh->prepare($query);
1000 $sth->execute($biblionumber);
1001 my $count = $sth->fetchrow;
1006 =head2 GetItemInfosOf
1010 GetItemInfosOf(@itemnumbers);
1016 sub GetItemInfosOf {
1017 my @itemnumbers = @_;
1022 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1024 return get_infos_of( $query, 'itemnumber' );
1027 =head2 GetItemsByBiblioitemnumber
1031 GetItemsByBiblioitemnumber($biblioitemnumber);
1035 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1036 Called by C<C4::XISBN>
1040 sub GetItemsByBiblioitemnumber {
1041 my ( $bibitem ) = @_;
1042 my $dbh = C4::Context->dbh;
1043 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1044 # Get all items attached to a biblioitem
1047 $sth->execute($bibitem) || die $sth->errstr;
1048 while ( my $data = $sth->fetchrow_hashref ) {
1049 # Foreach item, get circulation information
1050 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1051 WHERE itemnumber = ?
1052 AND issues.borrowernumber = borrowers.borrowernumber"
1054 $sth2->execute( $data->{'itemnumber'} );
1055 if ( my $data2 = $sth2->fetchrow_hashref ) {
1056 # if item is out, set the due date and who it is out too
1057 $data->{'date_due'} = $data2->{'date_due'};
1058 $data->{'cardnumber'} = $data2->{'cardnumber'};
1059 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1062 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1063 $data->{'date_due'} = '';
1066 # Find the last 3 people who borrowed this item.
1067 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1068 AND old_issues.borrowernumber = borrowers.borrowernumber
1069 ORDER BY returndate desc,timestamp desc LIMIT 3";
1070 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1071 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1073 while ( my $data2 = $sth2->fetchrow_hashref ) {
1074 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1075 $data->{"card$i2"} = $data2->{'cardnumber'};
1076 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1080 push(@results,$data);
1090 @results = GetItemsInfo($biblionumber, $type);
1094 Returns information about books with the given biblionumber.
1096 C<$type> may be either C<intra> or anything else. If it is not set to
1097 C<intra>, then the search will exclude lost, very overdue, and
1100 C<GetItemsInfo> returns a list of references-to-hash. Each element
1101 contains a number of keys. Most of them are table items from the
1102 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1103 Koha database. Other keys include:
1107 =item C<$data-E<gt>{branchname}>
1109 The name (not the code) of the branch to which the book belongs.
1111 =item C<$data-E<gt>{datelastseen}>
1113 This is simply C<items.datelastseen>, except that while the date is
1114 stored in YYYY-MM-DD format in the database, here it is converted to
1115 DD/MM/YYYY format. A NULL date is returned as C<//>.
1117 =item C<$data-E<gt>{datedue}>
1119 =item C<$data-E<gt>{class}>
1121 This is the concatenation of C<biblioitems.classification>, the book's
1122 Dewey code, and C<biblioitems.subclass>.
1124 =item C<$data-E<gt>{ocount}>
1126 I think this is the number of copies of the book available.
1128 =item C<$data-E<gt>{order}>
1130 If this is set, it is set to C<One Order>.
1137 my ( $biblionumber, $type ) = @_;
1138 my $dbh = C4::Context->dbh;
1139 my $query = "SELECT *,items.notforloan as itemnotforloan
1141 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1142 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1143 $query .= (C4::Context->preference('item-level_itypes')) ?
1144 " LEFT JOIN itemtypes on items.itype = itemtypes.itemtype "
1145 : " LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype ";
1146 $query .= "WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1147 my $sth = $dbh->prepare($query);
1148 $sth->execute($biblionumber);
1151 my ( $date_due, $count_reserves, $serial );
1153 my $isth = $dbh->prepare(
1154 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1155 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1156 WHERE itemnumber = ?"
1158 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1159 while ( my $data = $sth->fetchrow_hashref ) {
1161 $isth->execute( $data->{'itemnumber'} );
1162 if ( my $idata = $isth->fetchrow_hashref ) {
1163 $data->{borrowernumber} = $idata->{borrowernumber};
1164 $data->{cardnumber} = $idata->{cardnumber};
1165 $data->{surname} = $idata->{surname};
1166 $data->{firstname} = $idata->{firstname};
1167 $datedue = $idata->{'date_due'};
1168 if (C4::Context->preference("IndependantBranches")){
1169 my $userenv = C4::Context->userenv;
1170 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1171 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1175 if ( $data->{'serial'}) {
1176 $ssth->execute($data->{'itemnumber'}) ;
1177 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1180 if ( $datedue eq '' ) {
1181 my ( $restype, $reserves ) =
1182 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1184 $count_reserves = $restype;
1189 #get branch information.....
1190 my $bsth = $dbh->prepare(
1191 "SELECT * FROM branches WHERE branchcode = ?
1194 $bsth->execute( $data->{'holdingbranch'} );
1195 if ( my $bdata = $bsth->fetchrow_hashref ) {
1196 $data->{'branchname'} = $bdata->{'branchname'};
1198 $data->{'datedue'} = $datedue;
1199 $data->{'count_reserves'} = $count_reserves;
1201 # get notforloan complete status if applicable
1202 my $sthnflstatus = $dbh->prepare(
1203 'SELECT authorised_value
1204 FROM marc_subfield_structure
1205 WHERE kohafield="items.notforloan"
1209 $sthnflstatus->execute;
1210 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1211 if ($authorised_valuecode) {
1212 $sthnflstatus = $dbh->prepare(
1213 "SELECT lib FROM authorised_values
1215 AND authorised_value=?"
1217 $sthnflstatus->execute( $authorised_valuecode,
1218 $data->{itemnotforloan} );
1219 my ($lib) = $sthnflstatus->fetchrow;
1220 $data->{notforloanvalue} = $lib;
1222 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1224 # my stack procedures
1225 my $stackstatus = $dbh->prepare(
1226 'SELECT authorised_value
1227 FROM marc_subfield_structure
1228 WHERE kohafield="items.stack"
1231 $stackstatus->execute;
1233 ($authorised_valuecode) = $stackstatus->fetchrow;
1234 if ($authorised_valuecode) {
1235 $stackstatus = $dbh->prepare(
1237 FROM authorised_values
1239 AND authorised_value=?
1242 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1243 my ($lib) = $stackstatus->fetchrow;
1244 $data->{stack} = $lib;
1246 # Find the last 3 people who borrowed this item.
1247 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1248 WHERE itemnumber = ?
1249 AND old_issues.borrowernumber = borrowers.borrowernumber
1251 $sth2->execute($data->{'itemnumber'});
1253 while (my $data2 = $sth2->fetchrow_hashref()) {
1254 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1255 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1256 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1260 $results[$i] = $data;
1265 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1271 =head2 get_itemnumbers_of
1275 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1279 Given a list of biblionumbers, return the list of corresponding itemnumbers
1280 for each biblionumber.
1282 Return a reference on a hash where keys are biblionumbers and values are
1283 references on array of itemnumbers.
1287 sub get_itemnumbers_of {
1288 my @biblionumbers = @_;
1290 my $dbh = C4::Context->dbh;
1296 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1298 my $sth = $dbh->prepare($query);
1299 $sth->execute(@biblionumbers);
1303 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1304 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1307 return \%itemnumbers_of;
1310 =head2 GetItemnumberFromBarcode
1314 $result = GetItemnumberFromBarcode($barcode);
1320 sub GetItemnumberFromBarcode {
1322 my $dbh = C4::Context->dbh;
1325 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1326 $rq->execute($barcode);
1327 my ($result) = $rq->fetchrow;
1331 =head3 get_item_authorised_values
1333 find the types and values for all authorised values assigned to this item.
1338 returns: a hashref malling the authorised value to the value set for this itemnumber
1340 $authorised_values = {
1346 'RESTRICTED' => undef,
1349 'branches' => 'CPL',
1350 'cn_source' => undef,
1351 'itemtypes' => 'SER',
1354 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1358 sub get_item_authorised_values {
1359 my $itemnumber = shift;
1361 # assume that these entries in the authorised_value table are item level.
1362 my $query = q(SELECT distinct authorised_value, kohafield
1363 FROM marc_subfield_structure
1364 WHERE kohafield like 'item%'
1365 AND authorised_value != '' );
1367 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1368 my $iteminfo = GetItem( $itemnumber );
1369 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1371 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1372 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1373 $field =~ s/^items\.//;
1374 if ( exists $iteminfo->{ $field } ) {
1375 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1378 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1382 =head3 get_authorised_value_images
1384 find a list of icons that are appropriate for display based on the
1385 authorised values for a biblio.
1387 parameters: listref of authorised values, such as comes from
1388 get_item_ahtorised_values or
1389 from C4::Biblio::get_biblio_authorised_values
1391 returns: listref of hashrefs for each image. Each hashref looks like
1394 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1399 Notes: Currently, I put on the full path to the images on the staff
1400 side. This should either be configurable or not done at all. Since I
1401 have to deal with 'intranet' or 'opac' in
1402 get_biblio_authorised_values, perhaps I should be passing it in.
1406 sub get_authorised_value_images {
1407 my $authorised_values = shift;
1411 my $authorised_value_list = GetAuthorisedValues();
1412 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1413 foreach my $this_authorised_value ( @$authorised_value_list ) {
1414 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1415 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1416 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1417 if ( defined $this_authorised_value->{'imageurl'} ) {
1418 push @imagelist, { imageurl => C4::Koha::getitemtypeimagesrc( 'intranet' ) . '/' . $this_authorised_value->{'imageurl'},
1419 label => $this_authorised_value->{'lib'},
1420 category => $this_authorised_value->{'category'},
1421 value => $this_authorised_value->{'authorised_value'}, };
1426 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1431 =head1 LIMITED USE FUNCTIONS
1433 The following functions, while part of the public API,
1434 are not exported. This is generally because they are
1435 meant to be used by only one script for a specific
1436 purpose, and should not be used in any other context
1437 without careful thought.
1445 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1449 Returns MARC::Record of the item passed in parameter.
1450 This function is meant for use only in C<cataloguing/additem.pl>,
1451 where it is needed to support that script's MARC-like
1457 my ( $biblionumber, $itemnumber ) = @_;
1459 # GetMarcItem has been revised so that it does the following:
1460 # 1. Gets the item information from the items table.
1461 # 2. Converts it to a MARC field for storage in the bib record.
1463 # The previous behavior was:
1464 # 1. Get the bib record.
1465 # 2. Return the MARC tag corresponding to the item record.
1467 # The difference is that one treats the items row as authoritative,
1468 # while the other treats the MARC representation as authoritative
1469 # under certain circumstances.
1471 my $itemrecord = GetItem($itemnumber);
1473 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1474 # Also, don't emit a subfield if the underlying field is blank.
1475 my $mungeditem = { map { $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : () } keys %{ $itemrecord } };
1476 my $itemmarc = TransformKohaToMarc($mungeditem);
1478 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1479 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1480 my @fields = $itemmarc->fields();
1481 if ($#fields > -1) {
1482 $fields[0]->add_subfields(@$unlinked_item_subfields);
1490 =head1 PRIVATE FUNCTIONS AND VARIABLES
1492 The following functions are not meant to be called
1493 directly, but are documented in order to explain
1494 the inner workings of C<C4::Items>.
1498 =head2 %derived_columns
1500 This hash keeps track of item columns that
1501 are strictly derived from other columns in
1502 the item record and are not meant to be set
1505 Each key in the hash should be the name of a
1506 column (as named by TransformMarcToKoha). Each
1507 value should be hashref whose keys are the
1508 columns on which the derived column depends. The
1509 hashref should also contain a 'BUILDER' key
1510 that is a reference to a sub that calculates
1515 my %derived_columns = (
1516 'items.cn_sort' => {
1517 'itemcallnumber' => 1,
1518 'items.cn_source' => 1,
1519 'BUILDER' => \&_calc_items_cn_sort,
1523 =head2 _set_derived_columns_for_add
1527 _set_derived_column_for_add($item);
1531 Given an item hash representing a new item to be added,
1532 calculate any derived columns. Currently the only
1533 such column is C<items.cn_sort>.
1537 sub _set_derived_columns_for_add {
1540 foreach my $column (keys %derived_columns) {
1541 my $builder = $derived_columns{$column}->{'BUILDER'};
1542 my $source_values = {};
1543 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1544 next if $source_column eq 'BUILDER';
1545 $source_values->{$source_column} = $item->{$source_column};
1547 $builder->($item, $source_values);
1551 =head2 _set_derived_columns_for_mod
1555 _set_derived_column_for_mod($item);
1559 Given an item hash representing a new item to be modified.
1560 calculate any derived columns. Currently the only
1561 such column is C<items.cn_sort>.
1563 This routine differs from C<_set_derived_columns_for_add>
1564 in that it needs to handle partial item records. In other
1565 words, the caller of C<ModItem> may have supplied only one
1566 or two columns to be changed, so this function needs to
1567 determine whether any of the columns to be changed affect
1568 any of the derived columns. Also, if a derived column
1569 depends on more than one column, but the caller is not
1570 changing all of then, this routine retrieves the unchanged
1571 values from the database in order to ensure a correct
1576 sub _set_derived_columns_for_mod {
1579 foreach my $column (keys %derived_columns) {
1580 my $builder = $derived_columns{$column}->{'BUILDER'};
1581 my $source_values = {};
1582 my %missing_sources = ();
1583 my $must_recalc = 0;
1584 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1585 next if $source_column eq 'BUILDER';
1586 if (exists $item->{$source_column}) {
1588 $source_values->{$source_column} = $item->{$source_column};
1590 $missing_sources{$source_column} = 1;
1594 foreach my $source_column (keys %missing_sources) {
1595 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1597 $builder->($item, $source_values);
1602 =head2 _do_column_fixes_for_mod
1606 _do_column_fixes_for_mod($item);
1610 Given an item hashref containing one or more
1611 columns to modify, fix up certain values.
1612 Specifically, set to 0 any passed value
1613 of C<notforloan>, C<damaged>, C<itemlost>, or
1614 C<wthdrawn> that is either undefined or
1615 contains the empty string.
1619 sub _do_column_fixes_for_mod {
1622 if (exists $item->{'notforloan'} and
1623 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1624 $item->{'notforloan'} = 0;
1626 if (exists $item->{'damaged'} and
1627 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1628 $item->{'damaged'} = 0;
1630 if (exists $item->{'itemlost'} and
1631 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1632 $item->{'itemlost'} = 0;
1634 if (exists $item->{'wthdrawn'} and
1635 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1636 $item->{'wthdrawn'} = 0;
1640 =head2 _get_single_item_column
1644 _get_single_item_column($column, $itemnumber);
1648 Retrieves the value of a single column from an C<items>
1649 row specified by C<$itemnumber>.
1653 sub _get_single_item_column {
1655 my $itemnumber = shift;
1657 my $dbh = C4::Context->dbh;
1658 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1659 $sth->execute($itemnumber);
1660 my ($value) = $sth->fetchrow();
1664 =head2 _calc_items_cn_sort
1668 _calc_items_cn_sort($item, $source_values);
1672 Helper routine to calculate C<items.cn_sort>.
1676 sub _calc_items_cn_sort {
1678 my $source_values = shift;
1680 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1683 =head2 _set_defaults_for_add
1687 _set_defaults_for_add($item_hash);
1691 Given an item hash representing an item to be added, set
1692 correct default values for columns whose default value
1693 is not handled by the DBMS. This includes the following
1700 C<items.dateaccessioned>
1722 sub _set_defaults_for_add {
1725 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
1726 if (!(exists $item->{'dateaccessioned'}) ||
1727 ($item->{'dateaccessioned'} eq '')) {
1728 # FIXME add check for invalid date
1729 my $today = C4::Dates->new();
1730 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
1733 # various item status fields cannot be null
1734 $item->{'notforloan'} = 0 unless exists $item->{'notforloan'} and defined $item->{'notforloan'} and $item->{'notforloan'} ne '';
1735 $item->{'damaged'} = 0 unless exists $item->{'damaged'} and defined $item->{'damaged'} and $item->{'damaged'} ne '';
1736 $item->{'itemlost'} = 0 unless exists $item->{'itemlost'} and defined $item->{'itemlost'} and $item->{'itemlost'} ne '';
1737 $item->{'wthdrawn'} = 0 unless exists $item->{'wthdrawn'} and defined $item->{'wthdrawn'} and $item->{'wthdrawn'} ne '';
1740 =head2 _koha_new_item
1744 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1748 Perform the actual insert into the C<items> table.
1752 sub _koha_new_item {
1753 my ( $item, $barcode ) = @_;
1754 my $dbh=C4::Context->dbh;
1757 "INSERT INTO items SET
1759 biblioitemnumber = ?,
1761 dateaccessioned = ?,
1765 replacementprice = ?,
1766 replacementpricedate = NOW(),
1767 datelastborrowed = ?,
1768 datelastseen = NOW(),
1791 more_subfields_xml = ?
1793 my $sth = $dbh->prepare($query);
1795 $item->{'biblionumber'},
1796 $item->{'biblioitemnumber'},
1798 $item->{'dateaccessioned'},
1799 $item->{'booksellerid'},
1800 $item->{'homebranch'},
1802 $item->{'replacementprice'},
1803 $item->{datelastborrowed},
1805 $item->{'notforloan'},
1807 $item->{'itemlost'},
1808 $item->{'wthdrawn'},
1809 $item->{'itemcallnumber'},
1810 $item->{'restricted'},
1811 $item->{'itemnotes'},
1812 $item->{'holdingbranch'},
1814 $item->{'location'},
1817 $item->{'renewals'},
1818 $item->{'reserves'},
1819 $item->{'items.cn_source'},
1820 $item->{'items.cn_sort'},
1823 $item->{'materials'},
1825 $item->{'enumchron'},
1826 $item->{'more_subfields_xml'},
1828 my $itemnumber = $dbh->{'mysql_insertid'};
1829 if ( defined $sth->errstr ) {
1830 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1833 return ( $itemnumber, $error );
1836 =head2 _koha_modify_item
1840 my ($itemnumber,$error) =_koha_modify_item( $item );
1844 Perform the actual update of the C<items> row. Note that this
1845 routine accepts a hashref specifying the columns to update.
1849 sub _koha_modify_item {
1851 my $dbh=C4::Context->dbh;
1854 my $query = "UPDATE items SET ";
1856 for my $key ( keys %$item ) {
1858 push @bind, $item->{$key};
1861 $query .= " WHERE itemnumber=?";
1862 push @bind, $item->{'itemnumber'};
1863 my $sth = C4::Context->dbh->prepare($query);
1864 $sth->execute(@bind);
1865 if ( C4::Context->dbh->errstr ) {
1866 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1870 return ($item->{'itemnumber'},$error);
1873 =head2 _koha_delete_item
1877 _koha_delete_item( $dbh, $itemnum );
1881 Internal function to delete an item record from the koha tables
1885 sub _koha_delete_item {
1886 my ( $dbh, $itemnum ) = @_;
1888 # save the deleted item to deleteditems table
1889 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1890 $sth->execute($itemnum);
1891 my $data = $sth->fetchrow_hashref();
1893 my $query = "INSERT INTO deleteditems SET ";
1895 foreach my $key ( keys %$data ) {
1896 $query .= "$key = ?,";
1897 push( @bind, $data->{$key} );
1900 $sth = $dbh->prepare($query);
1901 $sth->execute(@bind);
1904 # delete from items table
1905 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1906 $sth->execute($itemnum);
1911 =head2 _marc_from_item_hash
1915 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1919 Given an item hash representing a complete item record,
1920 create a C<MARC::Record> object containing an embedded
1921 tag representing that item.
1923 The third, optional parameter C<$unlinked_item_subfields> is
1924 an arrayref of subfields (not mapped to C<items> fields per the
1925 framework) to be added to the MARC representation
1930 sub _marc_from_item_hash {
1932 my $frameworkcode = shift;
1933 my $unlinked_item_subfields;
1935 $unlinked_item_subfields = shift;
1938 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1939 # Also, don't emit a subfield if the underlying field is blank.
1940 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1941 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1942 : () } keys %{ $item } };
1944 my $item_marc = MARC::Record->new();
1945 foreach my $item_field (keys %{ $mungeditem }) {
1946 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
1947 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1948 if (my $field = $item_marc->field($tag)) {
1949 $field->add_subfields($subfield => $mungeditem->{$item_field});
1951 my $add_subfields = [];
1952 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1953 $add_subfields = $unlinked_item_subfields;
1955 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
1962 =head2 _add_item_field_to_biblio
1966 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
1970 Adds the fields from a MARC record containing the
1971 representation of a Koha item record to the MARC
1972 biblio record. The input C<$item_marc> record
1973 is expect to contain just one field, the embedded
1974 item information field.
1978 sub _add_item_field_to_biblio {
1979 my ($item_marc, $biblionumber, $frameworkcode) = @_;
1981 my $biblio_marc = GetMarcBiblio($biblionumber);
1982 foreach my $field ($item_marc->fields()) {
1983 $biblio_marc->append_fields($field);
1986 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
1989 =head2 _replace_item_field_in_biblio
1993 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
1997 Given a MARC::Record C<$item_marc> containing one tag with the MARC
1998 representation of the item, examine the biblio MARC
1999 for the corresponding tag for that item and
2000 replace it with the tag from C<$item_marc>.
2004 sub _replace_item_field_in_biblio {
2005 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2006 my $dbh = C4::Context->dbh;
2008 # get complete MARC record & replace the item field by the new one
2009 my $completeRecord = GetMarcBiblio($biblionumber);
2010 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2011 my $itemField = $ItemRecord->field($itemtag);
2012 my @items = $completeRecord->field($itemtag);
2015 if ($_->subfield($itemsubfield) eq $itemnumber) {
2016 $_->replace_with($itemField);
2022 # If we haven't found the matching field,
2023 # just add it. However, this means that
2024 # there is likely a bug.
2025 $completeRecord->append_fields($itemField);
2029 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2032 =head2 _repack_item_errors
2034 Add an error message hash generated by C<CheckItemPreSave>
2035 to a list of errors.
2039 sub _repack_item_errors {
2040 my $item_sequence_num = shift;
2041 my $item_ref = shift;
2042 my $error_ref = shift;
2044 my @repacked_errors = ();
2046 foreach my $error_code (sort keys %{ $error_ref }) {
2047 my $repacked_error = {};
2048 $repacked_error->{'item_sequence'} = $item_sequence_num;
2049 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2050 $repacked_error->{'error_code'} = $error_code;
2051 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2052 push @repacked_errors, $repacked_error;
2055 return @repacked_errors;
2058 =head2 _get_unlinked_item_subfields
2062 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2068 sub _get_unlinked_item_subfields {
2069 my $original_item_marc = shift;
2070 my $frameworkcode = shift;
2072 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2074 # assume that this record has only one field, and that that
2075 # field contains only the item information
2077 my @fields = $original_item_marc->fields();
2078 if ($#fields > -1) {
2079 my $field = $fields[0];
2080 my $tag = $field->tag();
2081 foreach my $subfield ($field->subfields()) {
2082 if (defined $subfield->[1] and
2083 $subfield->[1] ne '' and
2084 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2085 push @$subfields, $subfield->[0] => $subfield->[1];
2092 =head2 _get_unlinked_subfields_xml
2096 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2102 sub _get_unlinked_subfields_xml {
2103 my $unlinked_item_subfields = shift;
2106 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2107 my $marc = MARC::Record->new();
2108 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2109 # used in the framework
2110 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2111 $marc->encoding("UTF-8");
2112 $xml = $marc->as_xml("USMARC");
2118 =head2 _parse_unlinked_item_subfields_from_xml
2122 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2128 sub _parse_unlinked_item_subfields_from_xml {
2131 return unless defined $xml and $xml ne "";
2132 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2133 my $unlinked_subfields = [];
2134 my @fields = $marc->fields();
2135 if ($#fields > -1) {
2136 foreach my $subfield ($fields[0]->subfields()) {
2137 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2140 return $unlinked_subfields;