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/;
32 use vars qw($VERSION @ISA @EXPORT);
38 @ISA = qw( Exporter );
60 GetItemsByBiblioitemnumber
63 GetItemnumberFromBarcode
69 C4::Items - item management functions
73 This module contains an API for manipulating item
74 records in Koha, and is used by cataloguing, circulation,
75 acquisitions, and serials management.
77 A Koha item record is stored in two places: the
78 items table and embedded in a MARC tag in the XML
79 version of the associated bib record in C<biblioitems.marcxml>.
80 This is done to allow the item information to be readily
81 indexed (e.g., by Zebra), but means that each item
82 modification transaction must keep the items table
83 and the MARC XML in sync at all times.
85 Consequently, all code that creates, modifies, or deletes
86 item records B<must> use an appropriate function from
87 C<C4::Items>. If no existing function is suitable, it is
88 better to add one to C<C4::Items> than to use add
89 one-off SQL statements to add or modify items.
91 The items table will be considered authoritative. In other
92 words, if there is ever a discrepancy between the items
93 table and the MARC XML, the items table should be considered
96 =head1 HISTORICAL NOTE
98 Most of the functions in C<C4::Items> were originally in
99 the C<C4::Biblio> module.
101 =head1 CORE EXPORTED FUNCTIONS
103 The following functions are meant for use by users
112 $item = GetItem($itemnumber,$barcode,$serial);
116 Return item information, for a given itemnumber or barcode.
117 The return value is a hashref mapping item column
118 names to values. If C<$serial> is true, include serial publication data.
123 my ($itemnumber,$barcode, $serial) = @_;
124 my $dbh = C4::Context->dbh;
127 my $sth = $dbh->prepare("
129 WHERE itemnumber = ?");
130 $sth->execute($itemnumber);
131 $data = $sth->fetchrow_hashref;
133 my $sth = $dbh->prepare("
137 $sth->execute($barcode);
138 $data = $sth->fetchrow_hashref;
141 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
142 $ssth->execute($data->{'itemnumber'}) ;
143 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
144 warn $data->{'serialseq'} , $data->{'publisheddate'};
149 =head2 AddItemFromMarc
153 my ($biblionumber, $biblioitemnumber, $itemnumber)
154 = AddItemFromMarc($source_item_marc, $biblionumber);
158 Given a MARC::Record object containing an embedded item
159 record and a biblionumber, create a new item record.
163 sub AddItemFromMarc {
164 my ( $source_item_marc, $biblionumber ) = @_;
165 my $dbh = C4::Context->dbh;
167 # parse item hash from MARC
168 my $frameworkcode = GetFrameworkCode( $biblionumber );
169 my $item = &TransformMarcToKoha( $dbh, $source_item_marc, $frameworkcode );
170 my $unlinked_item_subfields = _get_unlinked_item_subfields($source_item_marc, $frameworkcode);
171 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
178 my ($biblionumber, $biblioitemnumber, $itemnumber)
179 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
183 Given a hash containing item column names as keys,
184 create a new Koha item record.
186 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
187 do not need to be supplied for general use; they exist
188 simply to allow them to be picked up from AddItemFromMarc.
190 The final optional parameter, C<$unlinked_item_subfields>, contains
191 an arrayref containing subfields present in the original MARC
192 representation of the item (e.g., from the item editor) that are
193 not mapped to C<items> columns directly but should instead
194 be stored in C<items.more_subfields_xml> and included in
195 the biblio items tag for display and indexing.
201 my $biblionumber = shift;
203 my $dbh = @_ ? shift : C4::Context->dbh;
204 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
205 my $unlinked_item_subfields;
207 $unlinked_item_subfields = shift
210 # needs old biblionumber and biblioitemnumber
211 $item->{'biblionumber'} = $biblionumber;
212 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
213 $sth->execute( $item->{'biblionumber'} );
214 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
216 _set_defaults_for_add($item);
217 _set_derived_columns_for_add($item);
218 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
219 # FIXME - checks here
220 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
221 $item->{'itemnumber'} = $itemnumber;
223 # create MARC tag representing item and add to bib
224 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
225 _add_item_field_to_biblio($new_item_marc, $item->{'biblionumber'}, $frameworkcode );
227 logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
228 if C4::Context->preference("CataloguingLog");
230 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
233 =head2 AddItemBatchFromMarc
237 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, $biblionumber, $biblioitemnumber, $frameworkcode);
241 Efficiently create item records from a MARC biblio record with
242 embedded item fields. This routine is suitable for batch jobs.
244 This API assumes that the bib record has already been
245 saved to the C<biblio> and C<biblioitems> tables. It does
246 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
247 are populated, but it will do so via a call to ModBibiloMarc.
249 The goal of this API is to have a similar effect to using AddBiblio
250 and AddItems in succession, but without inefficient repeated
251 parsing of the MARC XML bib record.
253 This function returns an arrayref of new itemsnumbers and an arrayref of item
254 errors encountered during the processing. Each entry in the errors
255 list is a hashref containing the following keys:
261 Sequence number of original item tag in the MARC record.
265 Item barcode, provide to assist in the construction of
266 useful error messages.
268 =item error_condition
270 Code representing the error condition. Can be 'duplicate_barcode',
271 'invalid_homebranch', or 'invalid_holdingbranch'.
273 =item error_information
275 Additional information appropriate to the error condition.
281 sub AddItemBatchFromMarc {
282 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
284 my @itemnumbers = ();
286 my $dbh = C4::Context->dbh;
288 # loop through the item tags and start creating items
289 my @bad_item_fields = ();
290 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
291 my $item_sequence_num = 0;
292 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
293 $item_sequence_num++;
294 # we take the item field and stick it into a new
295 # MARC record -- this is required so far because (FIXME)
296 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
297 # and there is no TransformMarcFieldToKoha
298 my $temp_item_marc = MARC::Record->new();
299 $temp_item_marc->append_fields($item_field);
301 # add biblionumber and biblioitemnumber
302 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
303 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
304 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
305 $item->{'biblionumber'} = $biblionumber;
306 $item->{'biblioitemnumber'} = $biblioitemnumber;
308 # check for duplicate barcode
309 my %item_errors = CheckItemPreSave($item);
311 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
312 push @bad_item_fields, $item_field;
316 _set_defaults_for_add($item);
317 _set_derived_columns_for_add($item);
318 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
319 warn $error if $error;
320 push @itemnumbers, $itemnumber; # FIXME not checking error
321 $item->{'itemnumber'} = $itemnumber;
323 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","ADD",$itemnumber,"item")
324 if C4::Context->preference("CataloguingLog");
326 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
327 $item_field->replace_with($new_item_marc->field($itemtag));
330 # remove any MARC item fields for rejected items
331 foreach my $item_field (@bad_item_fields) {
332 $record->delete_field($item_field);
335 # update the MARC biblio
336 $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
338 return (\@itemnumbers, \@errors);
341 =head2 ModItemFromMarc
345 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
349 This function updates an item record based on a supplied
350 C<MARC::Record> object containing an embedded item field.
351 This API is meant for the use of C<additem.pl>; for
352 other purposes, C<ModItem> should be used.
356 sub ModItemFromMarc {
357 my $item_marc = shift;
358 my $biblionumber = shift;
359 my $itemnumber = shift;
361 my $dbh = C4::Context->dbh;
362 my $frameworkcode = GetFrameworkCode( $biblionumber );
363 my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode );
364 my $unlinked_item_subfields = _get_unlinked_item_subfields($item_marc, $frameworkcode);
366 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
373 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
377 Change one or more columns in an item record and update
378 the MARC representation of the item.
380 The first argument is a hashref mapping from item column
381 names to the new values. The second and third arguments
382 are the biblionumber and itemnumber, respectively.
384 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
385 an arrayref containing subfields present in the original MARC
386 representation of the item (e.g., from the item editor) that are
387 not mapped to C<items> columns directly but should instead
388 be stored in C<items.more_subfields_xml> and included in
389 the biblio items tag for display and indexing.
391 If one of the changed columns is used to calculate
392 the derived value of a column such as C<items.cn_sort>,
393 this routine will perform the necessary calculation
400 my $biblionumber = shift;
401 my $itemnumber = shift;
403 # if $biblionumber is undefined, get it from the current item
404 unless (defined $biblionumber) {
405 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
408 my $dbh = @_ ? shift : C4::Context->dbh;
409 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
411 my $unlinked_item_subfields;
413 $unlinked_item_subfields = shift;
414 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
417 $item->{'itemnumber'} = $itemnumber or return undef;
418 _set_derived_columns_for_mod($item);
419 _do_column_fixes_for_mod($item);
422 # attempt to change itemnumber
423 # attempt to change biblionumber (if we want
424 # an API to relink an item to a different bib,
425 # it should be a separate function)
428 _koha_modify_item($item);
430 # update biblio MARC XML
431 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
433 unless (defined $unlinked_item_subfields) {
434 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
436 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
437 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
439 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
440 (C4::Context->userenv eq '0') and die "userenv is '0', not hashref"; # logaction line would crash anyway
441 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
442 logaction(C4::Context->userenv->{'number'},"CATALOGUING","MODIFY",$itemnumber,$new_item_marc->as_formatted)
443 if C4::Context->preference("CataloguingLog");
446 =head2 ModItemTransfer
450 ModItemTransfer($itenumber, $frombranch, $tobranch);
454 Marks an item as being transferred from one branch
459 sub ModItemTransfer {
460 my ( $itemnumber, $frombranch, $tobranch ) = @_;
462 my $dbh = C4::Context->dbh;
464 #new entry in branchtransfers....
465 my $sth = $dbh->prepare(
466 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
467 VALUES (?, ?, NOW(), ?)");
468 $sth->execute($itemnumber, $frombranch, $tobranch);
470 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
471 ModDateLastSeen($itemnumber);
475 =head2 ModDateLastSeen
479 ModDateLastSeen($itemnum);
483 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
484 C<$itemnum> is the item number
488 sub ModDateLastSeen {
489 my ($itemnumber) = @_;
491 my $today = C4::Dates->new();
492 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
499 DelItem($biblionumber, $itemnumber);
503 Exported function (core API) for deleting an item record in Koha.
508 my ( $dbh, $biblionumber, $itemnumber ) = @_;
510 # FIXME check the item has no current issues
512 _koha_delete_item( $dbh, $itemnumber );
514 # get the MARC record
515 my $record = GetMarcBiblio($biblionumber);
516 my $frameworkcode = GetFrameworkCode($biblionumber);
519 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
520 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
522 #search item field code
523 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
524 my @fields = $record->field($itemtag);
526 # delete the item specified
527 foreach my $field (@fields) {
528 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
529 $record->delete_field($field);
532 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
533 &logaction(C4::Context->userenv->{'number'},"CATALOGUING","DELETE",$itemnumber,"item")
534 if C4::Context->preference("CataloguingLog");
537 =head2 CheckItemPreSave
541 my $item_ref = TransformMarcToKoha($marc, 'items');
543 my %errors = CheckItemPreSave($item_ref);
544 if (exists $errors{'duplicate_barcode'}) {
545 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
546 } elsif (exists $errors{'invalid_homebranch'}) {
547 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
548 } elsif (exists $errors{'invalid_holdingbranch'}) {
549 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
556 Given a hashref containing item fields, determine if it can be
557 inserted or updated in the database. Specifically, checks for
558 database integrity issues, and returns a hash containing any
559 of the following keys, if applicable.
563 =item duplicate_barcode
565 Barcode, if it duplicates one already found in the database.
567 =item invalid_homebranch
569 Home branch, if not defined in branches table.
571 =item invalid_holdingbranch
573 Holding branch, if not defined in branches table.
577 This function does NOT implement any policy-related checks,
578 e.g., whether current operator is allowed to save an
579 item that has a given branch code.
583 sub CheckItemPreSave {
584 my $item_ref = shift;
588 # check for duplicate barcode
589 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
590 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
591 if ($existing_itemnumber) {
592 if (!exists $item_ref->{'itemnumber'} # new item
593 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
594 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
599 # check for valid home branch
600 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
601 my $branch_name = GetBranchName($item_ref->{'homebranch'});
602 unless (defined $branch_name) {
603 # relies on fact that branches.branchname is a non-NULL column,
604 # so GetBranchName returns undef only if branch does not exist
605 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
609 # check for valid holding branch
610 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
611 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
612 unless (defined $branch_name) {
613 # relies on fact that branches.branchname is a non-NULL column,
614 # so GetBranchName returns undef only if branch does not exist
615 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
623 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
625 The following functions provide various ways of
626 getting an item record, a set of item records, or
627 lists of authorized values for certain item fields.
629 Some of the functions in this group are candidates
630 for refactoring -- for example, some of the code
631 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
632 has copy-and-paste work.
640 $itemstatushash = GetItemStatus($fwkcode);
644 Returns a list of valid values for the
645 C<items.notforloan> field.
647 NOTE: does B<not> return an individual item's
650 Can be MARC dependant.
652 But basically could be can be loan or not
653 Create a status selector with the following code
655 =head3 in PERL SCRIPT
659 my $itemstatushash = getitemstatus;
661 foreach my $thisstatus (keys %$itemstatushash) {
662 my %row =(value => $thisstatus,
663 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
665 push @itemstatusloop, \%row;
667 $template->param(statusloop=>\@itemstatusloop);
675 <select name="statusloop">
676 <option value="">Default</option>
677 <!-- TMPL_LOOP name="statusloop" -->
678 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
688 # returns a reference to a hash of references to status...
691 my $dbh = C4::Context->dbh;
693 $fwk = '' unless ($fwk);
694 my ( $tag, $subfield ) =
695 GetMarcFromKohaField( "items.notforloan", $fwk );
696 if ( $tag and $subfield ) {
699 "SELECT authorised_value
700 FROM marc_subfield_structure
706 $sth->execute( $tag, $subfield, $fwk );
707 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
710 "SELECT authorised_value,lib
711 FROM authorised_values
716 $authvalsth->execute($authorisedvaluecat);
717 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
718 $itemstatus{$authorisedvalue} = $lib;
734 $itemstatus{"1"} = "Not For Loan";
738 =head2 GetItemLocation
742 $itemlochash = GetItemLocation($fwk);
746 Returns a list of valid values for the
747 C<items.location> field.
749 NOTE: does B<not> return an individual item's
752 where fwk stands for an optional framework code.
753 Create a location selector with the following code
755 =head3 in PERL SCRIPT
759 my $itemlochash = getitemlocation;
761 foreach my $thisloc (keys %$itemlochash) {
762 my $selected = 1 if $thisbranch eq $branch;
763 my %row =(locval => $thisloc,
764 selected => $selected,
765 locname => $itemlochash->{$thisloc},
767 push @itemlocloop, \%row;
769 $template->param(itemlocationloop => \@itemlocloop);
777 <select name="location">
778 <option value="">Default</option>
779 <!-- TMPL_LOOP name="itemlocationloop" -->
780 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
788 sub GetItemLocation {
790 # returns a reference to a hash of references to location...
793 my $dbh = C4::Context->dbh;
795 $fwk = '' unless ($fwk);
796 my ( $tag, $subfield ) =
797 GetMarcFromKohaField( "items.location", $fwk );
798 if ( $tag and $subfield ) {
801 "SELECT authorised_value
802 FROM marc_subfield_structure
807 $sth->execute( $tag, $subfield, $fwk );
808 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
811 "SELECT authorised_value,lib
812 FROM authorised_values
816 $authvalsth->execute($authorisedvaluecat);
817 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
818 $itemlocation{$authorisedvalue} = $lib;
821 return \%itemlocation;
834 $itemlocation{"1"} = "Not For Loan";
835 return \%itemlocation;
842 $items = GetLostItems($where,$orderby);
846 This function get the items lost into C<$items>.
851 C<$where> is a hashref. it containts a field of the items table as key
852 and the value to match as value.
853 C<$orderby> is a field of the items table.
856 C<$items> is a reference to an array full of hasref which keys are items' table column.
858 =item usage in the perl script:
861 $where{barcode} = 0001548;
862 my $items = GetLostItems( \%where, "homebranch" );
863 $template->param(itemsloop => $items);
870 # Getting input args.
873 my $dbh = C4::Context->dbh;
878 WHERE itemlost IS NOT NULL
881 foreach my $key (keys %$where) {
882 $query .= " AND " . $key . " LIKE '%" . $where->{$key} . "%'";
884 $query .= " ORDER BY ".$orderby if defined $orderby;
886 my $sth = $dbh->prepare($query);
889 while ( my $row = $sth->fetchrow_hashref ){
895 =head2 GetItemsForInventory
899 $itemlist = GetItemsForInventory($minlocation,$maxlocation,$datelastseen,$offset,$size)
903 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
905 The sub returns a list of hashes, containing itemnumber, author, title, barcode & item callnumber.
906 It is ordered by callnumber,title.
908 The minlocation & maxlocation parameters are used to specify a range of item callnumbers
909 the datelastseen can be used to specify that you want to see items not seen since a past date only.
910 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
914 sub GetItemsForInventory {
915 my ( $minlocation, $maxlocation,$location, $datelastseen, $branch, $offset, $size ) = @_;
916 my $dbh = C4::Context->dbh;
919 $datelastseen=format_date_in_iso($datelastseen);
921 "SELECT itemnumber,barcode,itemcallnumber,title,author,biblio.biblionumber,datelastseen
923 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
924 WHERE itemcallnumber>= ?
925 AND itemcallnumber <=?
926 AND (datelastseen< ? OR datelastseen IS NULL)";
927 $query.= " AND items.location=".$dbh->quote($location) if $location;
928 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
929 $query .= " ORDER BY itemcallnumber,title";
930 $sth = $dbh->prepare($query);
931 $sth->execute( $minlocation, $maxlocation, $datelastseen );
935 SELECT itemnumber,barcode,itemcallnumber,biblio.biblionumber,title,author,datelastseen
937 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
938 WHERE itemcallnumber>= ?
939 AND itemcallnumber <=?";
940 $query.= " AND items.location=".$dbh->quote($location) if $location;
941 $query.= " AND items.homebranch=".$dbh->quote($branch) if $branch;
942 $query .= " ORDER BY itemcallnumber,title";
943 $sth = $dbh->prepare($query);
944 $sth->execute( $minlocation, $maxlocation );
947 while ( my $row = $sth->fetchrow_hashref ) {
948 $offset-- if ($offset);
949 $row->{datelastseen}=format_date($row->{datelastseen});
950 if ( ( !$offset ) && $size ) {
961 $count = &GetItemsCount( $biblionumber);
965 This function return count of item with $biblionumber
970 my ( $biblionumber ) = @_;
971 my $dbh = C4::Context->dbh;
972 my $query = "SELECT count(*)
974 WHERE biblionumber=?";
975 my $sth = $dbh->prepare($query);
976 $sth->execute($biblionumber);
977 my $count = $sth->fetchrow;
982 =head2 GetItemInfosOf
986 GetItemInfosOf(@itemnumbers);
993 my @itemnumbers = @_;
998 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1000 return get_infos_of( $query, 'itemnumber' );
1003 =head2 GetItemsByBiblioitemnumber
1007 GetItemsByBiblioitemnumber($biblioitemnumber);
1011 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1012 Called by C<C4::XISBN>
1016 sub GetItemsByBiblioitemnumber {
1017 my ( $bibitem ) = @_;
1018 my $dbh = C4::Context->dbh;
1019 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1020 # Get all items attached to a biblioitem
1023 $sth->execute($bibitem) || die $sth->errstr;
1024 while ( my $data = $sth->fetchrow_hashref ) {
1025 # Foreach item, get circulation information
1026 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1027 WHERE itemnumber = ?
1028 AND returndate is NULL
1029 AND issues.borrowernumber = borrowers.borrowernumber"
1031 $sth2->execute( $data->{'itemnumber'} );
1032 if ( my $data2 = $sth2->fetchrow_hashref ) {
1033 # if item is out, set the due date and who it is out too
1034 $data->{'date_due'} = $data2->{'date_due'};
1035 $data->{'cardnumber'} = $data2->{'cardnumber'};
1036 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1039 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1040 $data->{'date_due'} = '';
1043 # Find the last 3 people who borrowed this item.
1044 my $query2 = "SELECT * FROM issues, borrowers WHERE itemnumber = ?
1045 AND issues.borrowernumber = borrowers.borrowernumber
1046 AND returndate is not NULL
1047 ORDER BY returndate desc,timestamp desc LIMIT 3";
1048 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1049 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1051 while ( my $data2 = $sth2->fetchrow_hashref ) {
1052 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1053 $data->{"card$i2"} = $data2->{'cardnumber'};
1054 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1058 push(@results,$data);
1068 @results = GetItemsInfo($biblionumber, $type);
1072 Returns information about books with the given biblionumber.
1074 C<$type> may be either C<intra> or anything else. If it is not set to
1075 C<intra>, then the search will exclude lost, very overdue, and
1078 C<GetItemsInfo> returns a list of references-to-hash. Each element
1079 contains a number of keys. Most of them are table items from the
1080 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1081 Koha database. Other keys include:
1085 =item C<$data-E<gt>{branchname}>
1087 The name (not the code) of the branch to which the book belongs.
1089 =item C<$data-E<gt>{datelastseen}>
1091 This is simply C<items.datelastseen>, except that while the date is
1092 stored in YYYY-MM-DD format in the database, here it is converted to
1093 DD/MM/YYYY format. A NULL date is returned as C<//>.
1095 =item C<$data-E<gt>{datedue}>
1097 =item C<$data-E<gt>{class}>
1099 This is the concatenation of C<biblioitems.classification>, the book's
1100 Dewey code, and C<biblioitems.subclass>.
1102 =item C<$data-E<gt>{ocount}>
1104 I think this is the number of copies of the book available.
1106 =item C<$data-E<gt>{order}>
1108 If this is set, it is set to C<One Order>.
1115 my ( $biblionumber, $type ) = @_;
1116 my $dbh = C4::Context->dbh;
1117 my $query = "SELECT *,items.notforloan as itemnotforloan
1119 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1120 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1121 $query .= (C4::Context->preference('item-level_itypes')) ?
1122 " LEFT JOIN itemtypes on items.itype = itemtypes.itemtype "
1123 : " LEFT JOIN itemtypes on biblioitems.itemtype = itemtypes.itemtype ";
1124 $query .= "WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1125 my $sth = $dbh->prepare($query);
1126 $sth->execute($biblionumber);
1129 my ( $date_due, $count_reserves, $serial );
1131 my $isth = $dbh->prepare(
1132 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1133 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1134 WHERE itemnumber = ?
1135 AND returndate IS NULL"
1137 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1138 while ( my $data = $sth->fetchrow_hashref ) {
1140 $isth->execute( $data->{'itemnumber'} );
1141 if ( my $idata = $isth->fetchrow_hashref ) {
1142 $data->{borrowernumber} = $idata->{borrowernumber};
1143 $data->{cardnumber} = $idata->{cardnumber};
1144 $data->{surname} = $idata->{surname};
1145 $data->{firstname} = $idata->{firstname};
1146 $datedue = $idata->{'date_due'};
1147 if (C4::Context->preference("IndependantBranches")){
1148 my $userenv = C4::Context->userenv;
1149 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1150 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1154 if ( $data->{'serial'}) {
1155 $ssth->execute($data->{'itemnumber'}) ;
1156 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1159 if ( $datedue eq '' ) {
1160 my ( $restype, $reserves ) =
1161 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1163 $count_reserves = $restype;
1168 #get branch information.....
1169 my $bsth = $dbh->prepare(
1170 "SELECT * FROM branches WHERE branchcode = ?
1173 $bsth->execute( $data->{'holdingbranch'} );
1174 if ( my $bdata = $bsth->fetchrow_hashref ) {
1175 $data->{'branchname'} = $bdata->{'branchname'};
1177 $data->{'datedue'} = $datedue;
1178 $data->{'count_reserves'} = $count_reserves;
1180 # get notforloan complete status if applicable
1181 my $sthnflstatus = $dbh->prepare(
1182 'SELECT authorised_value
1183 FROM marc_subfield_structure
1184 WHERE kohafield="items.notforloan"
1188 $sthnflstatus->execute;
1189 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1190 if ($authorised_valuecode) {
1191 $sthnflstatus = $dbh->prepare(
1192 "SELECT lib FROM authorised_values
1194 AND authorised_value=?"
1196 $sthnflstatus->execute( $authorised_valuecode,
1197 $data->{itemnotforloan} );
1198 my ($lib) = $sthnflstatus->fetchrow;
1199 $data->{notforloanvalue} = $lib;
1202 # my stack procedures
1203 my $stackstatus = $dbh->prepare(
1204 'SELECT authorised_value
1205 FROM marc_subfield_structure
1206 WHERE kohafield="items.stack"
1209 $stackstatus->execute;
1211 ($authorised_valuecode) = $stackstatus->fetchrow;
1212 if ($authorised_valuecode) {
1213 $stackstatus = $dbh->prepare(
1215 FROM authorised_values
1217 AND authorised_value=?
1220 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1221 my ($lib) = $stackstatus->fetchrow;
1222 $data->{stack} = $lib;
1224 # Find the last 3 people who borrowed this item.
1225 my $sth2 = $dbh->prepare("SELECT * FROM issues,borrowers
1226 WHERE itemnumber = ?
1227 AND issues.borrowernumber = borrowers.borrowernumber
1228 AND returndate IS NOT NULL LIMIT 3");
1229 $sth2->execute($data->{'itemnumber'});
1231 while (my $data2 = $sth2->fetchrow_hashref()) {
1232 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1233 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1234 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1238 $results[$i] = $data;
1243 return( sort { $b->{'publisheddate'} cmp $a->{'publisheddate'} } @results );
1249 =head2 get_itemnumbers_of
1253 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1257 Given a list of biblionumbers, return the list of corresponding itemnumbers
1258 for each biblionumber.
1260 Return a reference on a hash where keys are biblionumbers and values are
1261 references on array of itemnumbers.
1265 sub get_itemnumbers_of {
1266 my @biblionumbers = @_;
1268 my $dbh = C4::Context->dbh;
1274 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1276 my $sth = $dbh->prepare($query);
1277 $sth->execute(@biblionumbers);
1281 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1282 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1285 return \%itemnumbers_of;
1288 =head2 GetItemnumberFromBarcode
1292 $result = GetItemnumberFromBarcode($barcode);
1298 sub GetItemnumberFromBarcode {
1300 my $dbh = C4::Context->dbh;
1303 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1304 $rq->execute($barcode);
1305 my ($result) = $rq->fetchrow;
1309 =head1 LIMITED USE FUNCTIONS
1311 The following functions, while part of the public API,
1312 are not exported. This is generally because they are
1313 meant to be used by only one script for a specific
1314 purpose, and should not be used in any other context
1315 without careful thought.
1323 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1327 Returns MARC::Record of the item passed in parameter.
1328 This function is meant for use only in C<cataloguing/additem.pl>,
1329 where it is needed to support that script's MARC-like
1335 my ( $biblionumber, $itemnumber ) = @_;
1337 # GetMarcItem has been revised so that it does the following:
1338 # 1. Gets the item information from the items table.
1339 # 2. Converts it to a MARC field for storage in the bib record.
1341 # The previous behavior was:
1342 # 1. Get the bib record.
1343 # 2. Return the MARC tag corresponding to the item record.
1345 # The difference is that one treats the items row as authoritative,
1346 # while the other treats the MARC representation as authoritative
1347 # under certain circumstances.
1349 my $itemrecord = GetItem($itemnumber);
1351 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1352 # Also, don't emit a subfield if the underlying field is blank.
1353 my $mungeditem = { map { $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : () } keys %{ $itemrecord } };
1354 my $itemmarc = TransformKohaToMarc($mungeditem);
1356 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1357 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1358 my @fields = $itemmarc->fields();
1359 if ($#fields > -1) {
1360 $fields[0]->add_subfields(@$unlinked_item_subfields);
1368 =head1 PRIVATE FUNCTIONS AND VARIABLES
1370 The following functions are not meant to be called
1371 directly, but are documented in order to explain
1372 the inner workings of C<C4::Items>.
1376 =head2 %derived_columns
1378 This hash keeps track of item columns that
1379 are strictly derived from other columns in
1380 the item record and are not meant to be set
1383 Each key in the hash should be the name of a
1384 column (as named by TransformMarcToKoha). Each
1385 value should be hashref whose keys are the
1386 columns on which the derived column depends. The
1387 hashref should also contain a 'BUILDER' key
1388 that is a reference to a sub that calculates
1393 my %derived_columns = (
1394 'items.cn_sort' => {
1395 'itemcallnumber' => 1,
1396 'items.cn_source' => 1,
1397 'BUILDER' => \&_calc_items_cn_sort,
1401 =head2 _set_derived_columns_for_add
1405 _set_derived_column_for_add($item);
1409 Given an item hash representing a new item to be added,
1410 calculate any derived columns. Currently the only
1411 such column is C<items.cn_sort>.
1415 sub _set_derived_columns_for_add {
1418 foreach my $column (keys %derived_columns) {
1419 my $builder = $derived_columns{$column}->{'BUILDER'};
1420 my $source_values = {};
1421 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1422 next if $source_column eq 'BUILDER';
1423 $source_values->{$source_column} = $item->{$source_column};
1425 $builder->($item, $source_values);
1429 =head2 _set_derived_columns_for_mod
1433 _set_derived_column_for_mod($item);
1437 Given an item hash representing a new item to be modified.
1438 calculate any derived columns. Currently the only
1439 such column is C<items.cn_sort>.
1441 This routine differs from C<_set_derived_columns_for_add>
1442 in that it needs to handle partial item records. In other
1443 words, the caller of C<ModItem> may have supplied only one
1444 or two columns to be changed, so this function needs to
1445 determine whether any of the columns to be changed affect
1446 any of the derived columns. Also, if a derived column
1447 depends on more than one column, but the caller is not
1448 changing all of then, this routine retrieves the unchanged
1449 values from the database in order to ensure a correct
1454 sub _set_derived_columns_for_mod {
1457 foreach my $column (keys %derived_columns) {
1458 my $builder = $derived_columns{$column}->{'BUILDER'};
1459 my $source_values = {};
1460 my %missing_sources = ();
1461 my $must_recalc = 0;
1462 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1463 next if $source_column eq 'BUILDER';
1464 if (exists $item->{$source_column}) {
1466 $source_values->{$source_column} = $item->{$source_column};
1468 $missing_sources{$source_column} = 1;
1472 foreach my $source_column (keys %missing_sources) {
1473 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1475 $builder->($item, $source_values);
1480 =head2 _do_column_fixes_for_mod
1484 _do_column_fixes_for_mod($item);
1488 Given an item hashref containing one or more
1489 columns to modify, fix up certain values.
1490 Specifically, set to 0 any passed value
1491 of C<notforloan>, C<damaged>, C<itemlost>, or
1492 C<wthdrawn> that is either undefined or
1493 contains the empty string.
1497 sub _do_column_fixes_for_mod {
1500 if (exists $item->{'notforloan'} and
1501 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1502 $item->{'notforloan'} = 0;
1504 if (exists $item->{'damaged'} and
1505 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1506 $item->{'damaged'} = 0;
1508 if (exists $item->{'itemlost'} and
1509 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1510 $item->{'itemlost'} = 0;
1512 if (exists $item->{'wthdrawn'} and
1513 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1514 $item->{'wthdrawn'} = 0;
1518 =head2 _get_single_item_column
1522 _get_single_item_column($column, $itemnumber);
1526 Retrieves the value of a single column from an C<items>
1527 row specified by C<$itemnumber>.
1531 sub _get_single_item_column {
1533 my $itemnumber = shift;
1535 my $dbh = C4::Context->dbh;
1536 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1537 $sth->execute($itemnumber);
1538 my ($value) = $sth->fetchrow();
1542 =head2 _calc_items_cn_sort
1546 _calc_items_cn_sort($item, $source_values);
1550 Helper routine to calculate C<items.cn_sort>.
1554 sub _calc_items_cn_sort {
1556 my $source_values = shift;
1558 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1561 =head2 _set_defaults_for_add
1565 _set_defaults_for_add($item_hash);
1569 Given an item hash representing an item to be added, set
1570 correct default values for columns whose default value
1571 is not handled by the DBMS. This includes the following
1578 C<items.dateaccessioned>
1600 sub _set_defaults_for_add {
1603 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
1604 if (!(exists $item->{'dateaccessioned'}) ||
1605 ($item->{'dateaccessioned'} eq '')) {
1606 # FIXME add check for invalid date
1607 my $today = C4::Dates->new();
1608 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
1611 # various item status fields cannot be null
1612 $item->{'notforloan'} = 0 unless exists $item->{'notforloan'} and defined $item->{'notforloan'} and $item->{'notforloan'} ne '';
1613 $item->{'damaged'} = 0 unless exists $item->{'damaged'} and defined $item->{'damaged'} and $item->{'damaged'} ne '';
1614 $item->{'itemlost'} = 0 unless exists $item->{'itemlost'} and defined $item->{'itemlost'} and $item->{'itemlost'} ne '';
1615 $item->{'wthdrawn'} = 0 unless exists $item->{'wthdrawn'} and defined $item->{'wthdrawn'} and $item->{'wthdrawn'} ne '';
1618 =head2 _koha_new_item
1622 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1626 Perform the actual insert into the C<items> table.
1630 sub _koha_new_item {
1631 my ( $item, $barcode ) = @_;
1632 my $dbh=C4::Context->dbh;
1635 "INSERT INTO items SET
1637 biblioitemnumber = ?,
1639 dateaccessioned = ?,
1643 replacementprice = ?,
1644 replacementpricedate = NOW(),
1645 datelastborrowed = ?,
1646 datelastseen = NOW(),
1668 more_subfields_xml = ?
1670 my $sth = $dbh->prepare($query);
1672 $item->{'biblionumber'},
1673 $item->{'biblioitemnumber'},
1675 $item->{'dateaccessioned'},
1676 $item->{'booksellerid'},
1677 $item->{'homebranch'},
1679 $item->{'replacementprice'},
1680 $item->{datelastborrowed},
1682 $item->{'notforloan'},
1684 $item->{'itemlost'},
1685 $item->{'wthdrawn'},
1686 $item->{'itemcallnumber'},
1687 $item->{'restricted'},
1688 $item->{'itemnotes'},
1689 $item->{'holdingbranch'},
1691 $item->{'location'},
1694 $item->{'renewals'},
1695 $item->{'reserves'},
1696 $item->{'items.cn_source'},
1697 $item->{'items.cn_sort'},
1700 $item->{'materials'},
1702 $item->{'more_subfields_xml'},
1704 my $itemnumber = $dbh->{'mysql_insertid'};
1705 if ( defined $sth->errstr ) {
1706 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1709 return ( $itemnumber, $error );
1712 =head2 _koha_modify_item
1716 my ($itemnumber,$error) =_koha_modify_item( $item );
1720 Perform the actual update of the C<items> row. Note that this
1721 routine accepts a hashref specifying the columns to update.
1725 sub _koha_modify_item {
1727 my $dbh=C4::Context->dbh;
1730 my $query = "UPDATE items SET ";
1732 for my $key ( keys %$item ) {
1734 push @bind, $item->{$key};
1737 $query .= " WHERE itemnumber=?";
1738 push @bind, $item->{'itemnumber'};
1739 my $sth = C4::Context->dbh->prepare($query);
1740 $sth->execute(@bind);
1741 if ( C4::Context->dbh->errstr ) {
1742 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1746 return ($item->{'itemnumber'},$error);
1749 =head2 _koha_delete_item
1753 _koha_delete_item( $dbh, $itemnum );
1757 Internal function to delete an item record from the koha tables
1761 sub _koha_delete_item {
1762 my ( $dbh, $itemnum ) = @_;
1764 # save the deleted item to deleteditems table
1765 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1766 $sth->execute($itemnum);
1767 my $data = $sth->fetchrow_hashref();
1769 my $query = "INSERT INTO deleteditems SET ";
1771 foreach my $key ( keys %$data ) {
1772 $query .= "$key = ?,";
1773 push( @bind, $data->{$key} );
1776 $sth = $dbh->prepare($query);
1777 $sth->execute(@bind);
1780 # delete from items table
1781 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1782 $sth->execute($itemnum);
1787 =head2 _marc_from_item_hash
1791 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1795 Given an item hash representing a complete item record,
1796 create a C<MARC::Record> object containing an embedded
1797 tag representing that item.
1799 The third, optional parameter C<$unlinked_item_subfields> is
1800 an arrayref of subfields (not mapped to C<items> fields per the
1801 framework) to be added to the MARC representation
1806 sub _marc_from_item_hash {
1808 my $frameworkcode = shift;
1809 my $unlinked_item_subfields;
1811 $unlinked_item_subfields = shift;
1814 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
1815 # Also, don't emit a subfield if the underlying field is blank.
1816 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
1817 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
1818 : () } keys %{ $item } };
1820 my $item_marc = MARC::Record->new();
1821 foreach my $item_field (keys %{ $mungeditem }) {
1822 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
1823 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
1824 if (my $field = $item_marc->field($tag)) {
1825 $field->add_subfields($subfield => $mungeditem->{$item_field});
1827 my $add_subfields = [];
1828 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1829 $add_subfields = $unlinked_item_subfields;
1831 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
1838 =head2 _add_item_field_to_biblio
1842 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
1846 Adds the fields from a MARC record containing the
1847 representation of a Koha item record to the MARC
1848 biblio record. The input C<$item_marc> record
1849 is expect to contain just one field, the embedded
1850 item information field.
1854 sub _add_item_field_to_biblio {
1855 my ($item_marc, $biblionumber, $frameworkcode) = @_;
1857 my $biblio_marc = GetMarcBiblio($biblionumber);
1859 foreach my $field ($item_marc->fields()) {
1860 $biblio_marc->append_fields($field);
1863 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
1866 =head2 _replace_item_field_in_biblio
1870 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
1874 Given a MARC::Record C<$item_marc> containing one tag with the MARC
1875 representation of the item, examine the biblio MARC
1876 for the corresponding tag for that item and
1877 replace it with the tag from C<$item_marc>.
1881 sub _replace_item_field_in_biblio {
1882 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
1883 my $dbh = C4::Context->dbh;
1885 # get complete MARC record & replace the item field by the new one
1886 my $completeRecord = GetMarcBiblio($biblionumber);
1887 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
1888 my $itemField = $ItemRecord->field($itemtag);
1889 my @items = $completeRecord->field($itemtag);
1892 if ($_->subfield($itemsubfield) eq $itemnumber) {
1893 $_->replace_with($itemField);
1899 # If we haven't found the matching field,
1900 # just add it. However, this means that
1901 # there is likely a bug.
1902 $completeRecord->append_fields($itemField);
1906 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
1909 =head2 _repack_item_errors
1911 Add an error message hash generated by C<CheckItemPreSave>
1912 to a list of errors.
1916 sub _repack_item_errors {
1917 my $item_sequence_num = shift;
1918 my $item_ref = shift;
1919 my $error_ref = shift;
1921 my @repacked_errors = ();
1923 foreach my $error_code (sort keys %{ $error_ref }) {
1924 my $repacked_error = {};
1925 $repacked_error->{'item_sequence'} = $item_sequence_num;
1926 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
1927 $repacked_error->{'error_code'} = $error_code;
1928 $repacked_error->{'error_information'} = $error_ref->{$error_code};
1929 push @repacked_errors, $repacked_error;
1932 return @repacked_errors;
1935 =head2 _get_unlinked_item_subfields
1939 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
1945 sub _get_unlinked_item_subfields {
1946 my $original_item_marc = shift;
1947 my $frameworkcode = shift;
1949 my $marcstructure = GetMarcStructure(1, $frameworkcode);
1951 # assume that this record has only one field, and that that
1952 # field contains only the item information
1954 my @fields = $original_item_marc->fields();
1955 if ($#fields > -1) {
1956 my $field = $fields[0];
1957 my $tag = $field->tag();
1958 foreach my $subfield ($field->subfields()) {
1959 if (defined $subfield->[1] and
1960 $subfield->[1] ne '' and
1961 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
1962 push @$subfields, $subfield->[0] => $subfield->[1];
1969 =head2 _get_unlinked_subfields_xml
1973 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
1979 sub _get_unlinked_subfields_xml {
1980 my $unlinked_item_subfields = shift;
1983 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
1984 my $marc = MARC::Record->new();
1985 # use of tag 999 is arbitrary, and doesn't need to match the item tag
1986 # used in the framework
1987 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
1988 $xml = $marc->as_xml();
1994 =head2 _parse_unlinked_item_subfields_from_xml
1998 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2004 sub _parse_unlinked_item_subfields_from_xml {
2007 return unless defined $xml and $xml ne "";
2008 my $marc = MARC::Record->new_from_xml($xml, 'UTF-8', C4::Context->preference("marcflavour"));
2009 my $unlinked_subfields = [];
2010 my @fields = $marc->fields();
2011 if ($#fields > -1) {
2012 foreach my $subfield ($fields[0]->subfields()) {
2013 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2016 return $unlinked_subfields;