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.
359 This function uses the hash %default_values_for_mod_from_marc,
360 which contains default values for item fields to
361 apply when modifying an item. This is needed beccause
362 if an item field's value is cleared, TransformMarcToKoha
363 does not include the column in the
364 hash that's passed to ModItem, which without
365 use of this hash makes it impossible to clear
366 an item field's value. See bug 2466.
368 Note that only columns that can be directly
369 changed from the cataloging and serials
370 item editors are included in this hash.
374 my %default_values_for_mod_from_marc = (
376 booksellerid => undef,
378 'items.cn_source' => undef,
381 dateaccessioned => undef,
383 holdingbranch => undef,
385 itemcallnumber => undef,
394 replacementprice => undef,
395 replacementpricedate => undef,
402 sub ModItemFromMarc {
403 my $item_marc = shift;
404 my $biblionumber = shift;
405 my $itemnumber = shift;
407 my $dbh = C4::Context->dbh;
408 my $frameworkcode = GetFrameworkCode( $biblionumber );
409 my $item = &TransformMarcToKoha( $dbh, $item_marc, $frameworkcode );
410 foreach my $item_field (keys %default_values_for_mod_from_marc) {
411 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless exists $item->{$item_field};
413 my $unlinked_item_subfields = _get_unlinked_item_subfields($item_marc, $frameworkcode);
415 return ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
422 ModItem({ column => $newvalue }, $biblionumber, $itemnumber[, $original_item_marc]);
426 Change one or more columns in an item record and update
427 the MARC representation of the item.
429 The first argument is a hashref mapping from item column
430 names to the new values. The second and third arguments
431 are the biblionumber and itemnumber, respectively.
433 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
434 an arrayref containing subfields present in the original MARC
435 representation of the item (e.g., from the item editor) that are
436 not mapped to C<items> columns directly but should instead
437 be stored in C<items.more_subfields_xml> and included in
438 the biblio items tag for display and indexing.
440 If one of the changed columns is used to calculate
441 the derived value of a column such as C<items.cn_sort>,
442 this routine will perform the necessary calculation
449 my $biblionumber = shift;
450 my $itemnumber = shift;
452 # if $biblionumber is undefined, get it from the current item
453 unless (defined $biblionumber) {
454 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
457 my $dbh = @_ ? shift : C4::Context->dbh;
458 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
460 my $unlinked_item_subfields;
462 $unlinked_item_subfields = shift;
463 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
466 $item->{'itemnumber'} = $itemnumber or return undef;
467 _set_derived_columns_for_mod($item);
468 _do_column_fixes_for_mod($item);
471 # attempt to change itemnumber
472 # attempt to change biblionumber (if we want
473 # an API to relink an item to a different bib,
474 # it should be a separate function)
477 _koha_modify_item($item);
479 # update biblio MARC XML
480 my $whole_item = GetItem($itemnumber) or die "FAILED GetItem($itemnumber)";
482 unless (defined $unlinked_item_subfields) {
483 $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'});
485 my $new_item_marc = _marc_from_item_hash($whole_item, $frameworkcode, $unlinked_item_subfields)
486 or die "FAILED _marc_from_item_hash($whole_item, $frameworkcode)";
488 _replace_item_field_in_biblio($new_item_marc, $biblionumber, $itemnumber, $frameworkcode);
489 ($new_item_marc eq '0') and die "$new_item_marc is '0', not hashref"; # logaction line would crash anyway
490 logaction("CATALOGUING", "MODIFY", $itemnumber, $new_item_marc->as_formatted) if C4::Context->preference("CataloguingLog");
493 =head2 ModItemTransfer
497 ModItemTransfer($itenumber, $frombranch, $tobranch);
501 Marks an item as being transferred from one branch
506 sub ModItemTransfer {
507 my ( $itemnumber, $frombranch, $tobranch ) = @_;
509 my $dbh = C4::Context->dbh;
511 #new entry in branchtransfers....
512 my $sth = $dbh->prepare(
513 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
514 VALUES (?, ?, NOW(), ?)");
515 $sth->execute($itemnumber, $frombranch, $tobranch);
517 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
518 ModDateLastSeen($itemnumber);
522 =head2 ModDateLastSeen
526 ModDateLastSeen($itemnum);
530 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
531 C<$itemnum> is the item number
535 sub ModDateLastSeen {
536 my ($itemnumber) = @_;
538 my $today = C4::Dates->new();
539 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
546 DelItem($biblionumber, $itemnumber);
550 Exported function (core API) for deleting an item record in Koha.
555 my ( $dbh, $biblionumber, $itemnumber ) = @_;
557 # FIXME check the item has no current issues
559 _koha_delete_item( $dbh, $itemnumber );
561 # get the MARC record
562 my $record = GetMarcBiblio($biblionumber);
563 my $frameworkcode = GetFrameworkCode($biblionumber);
566 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
567 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
569 #search item field code
570 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
571 my @fields = $record->field($itemtag);
573 # delete the item specified
574 foreach my $field (@fields) {
575 if ( $field->subfield($itemsubfield) eq $itemnumber ) {
576 $record->delete_field($field);
579 &ModBiblioMarc( $record, $biblionumber, $frameworkcode );
580 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
583 =head2 CheckItemPreSave
587 my $item_ref = TransformMarcToKoha($marc, 'items');
589 my %errors = CheckItemPreSave($item_ref);
590 if (exists $errors{'duplicate_barcode'}) {
591 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
592 } elsif (exists $errors{'invalid_homebranch'}) {
593 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
594 } elsif (exists $errors{'invalid_holdingbranch'}) {
595 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
602 Given a hashref containing item fields, determine if it can be
603 inserted or updated in the database. Specifically, checks for
604 database integrity issues, and returns a hash containing any
605 of the following keys, if applicable.
609 =item duplicate_barcode
611 Barcode, if it duplicates one already found in the database.
613 =item invalid_homebranch
615 Home branch, if not defined in branches table.
617 =item invalid_holdingbranch
619 Holding branch, if not defined in branches table.
623 This function does NOT implement any policy-related checks,
624 e.g., whether current operator is allowed to save an
625 item that has a given branch code.
629 sub CheckItemPreSave {
630 my $item_ref = shift;
634 # check for duplicate barcode
635 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
636 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
637 if ($existing_itemnumber) {
638 if (!exists $item_ref->{'itemnumber'} # new item
639 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
640 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
645 # check for valid home branch
646 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
647 my $branch_name = GetBranchName($item_ref->{'homebranch'});
648 unless (defined $branch_name) {
649 # relies on fact that branches.branchname is a non-NULL column,
650 # so GetBranchName returns undef only if branch does not exist
651 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
655 # check for valid holding branch
656 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
657 my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
658 unless (defined $branch_name) {
659 # relies on fact that branches.branchname is a non-NULL column,
660 # so GetBranchName returns undef only if branch does not exist
661 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
669 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
671 The following functions provide various ways of
672 getting an item record, a set of item records, or
673 lists of authorized values for certain item fields.
675 Some of the functions in this group are candidates
676 for refactoring -- for example, some of the code
677 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
678 has copy-and-paste work.
686 $itemstatushash = GetItemStatus($fwkcode);
690 Returns a list of valid values for the
691 C<items.notforloan> field.
693 NOTE: does B<not> return an individual item's
696 Can be MARC dependant.
698 But basically could be can be loan or not
699 Create a status selector with the following code
701 =head3 in PERL SCRIPT
705 my $itemstatushash = getitemstatus;
707 foreach my $thisstatus (keys %$itemstatushash) {
708 my %row =(value => $thisstatus,
709 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
711 push @itemstatusloop, \%row;
713 $template->param(statusloop=>\@itemstatusloop);
721 <select name="statusloop">
722 <option value="">Default</option>
723 <!-- TMPL_LOOP name="statusloop" -->
724 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
734 # returns a reference to a hash of references to status...
737 my $dbh = C4::Context->dbh;
739 $fwk = '' unless ($fwk);
740 my ( $tag, $subfield ) =
741 GetMarcFromKohaField( "items.notforloan", $fwk );
742 if ( $tag and $subfield ) {
745 "SELECT authorised_value
746 FROM marc_subfield_structure
752 $sth->execute( $tag, $subfield, $fwk );
753 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
756 "SELECT authorised_value,lib
757 FROM authorised_values
762 $authvalsth->execute($authorisedvaluecat);
763 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
764 $itemstatus{$authorisedvalue} = $lib;
780 $itemstatus{"1"} = "Not For Loan";
784 =head2 GetItemLocation
788 $itemlochash = GetItemLocation($fwk);
792 Returns a list of valid values for the
793 C<items.location> field.
795 NOTE: does B<not> return an individual item's
798 where fwk stands for an optional framework code.
799 Create a location selector with the following code
801 =head3 in PERL SCRIPT
805 my $itemlochash = getitemlocation;
807 foreach my $thisloc (keys %$itemlochash) {
808 my $selected = 1 if $thisbranch eq $branch;
809 my %row =(locval => $thisloc,
810 selected => $selected,
811 locname => $itemlochash->{$thisloc},
813 push @itemlocloop, \%row;
815 $template->param(itemlocationloop => \@itemlocloop);
823 <select name="location">
824 <option value="">Default</option>
825 <!-- TMPL_LOOP name="itemlocationloop" -->
826 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
834 sub GetItemLocation {
836 # returns a reference to a hash of references to location...
839 my $dbh = C4::Context->dbh;
841 $fwk = '' unless ($fwk);
842 my ( $tag, $subfield ) =
843 GetMarcFromKohaField( "items.location", $fwk );
844 if ( $tag and $subfield ) {
847 "SELECT authorised_value
848 FROM marc_subfield_structure
853 $sth->execute( $tag, $subfield, $fwk );
854 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
857 "SELECT authorised_value,lib
858 FROM authorised_values
862 $authvalsth->execute($authorisedvaluecat);
863 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
864 $itemlocation{$authorisedvalue} = $lib;
867 return \%itemlocation;
880 $itemlocation{"1"} = "Not For Loan";
881 return \%itemlocation;
888 $items = GetLostItems( $where, $orderby );
892 This function gets a list of lost items.
898 C<$where> is a hashref. it containts a field of the items table as key
899 and the value to match as value. For example:
901 { barcode => 'abc123',
902 homebranch => 'CPL', }
904 C<$orderby> is a field of the items table by which the resultset
909 C<$items> is a reference to an array full of hashrefs with columns
910 from the "items" table as keys.
912 =item usage in the perl script:
914 my $where = { barcode => '0001548' };
915 my $items = GetLostItems( $where, "homebranch" );
916 $template->param( itemsloop => $items );
923 # Getting input args.
926 my $dbh = C4::Context->dbh;
930 FROM items, biblio, authorised_values
932 items.biblionumber = biblio.biblionumber
933 AND items.itemlost = authorised_values.authorised_value
934 AND authorised_values.category = 'LOST'
935 AND itemlost IS NOT NULL
939 my @query_parameters;
940 foreach my $key (keys %$where) {
941 $query .= " AND $key LIKE ?";
942 push @query_parameters, "%$where->{$key}%";
944 if ( defined $orderby ) {
945 $query .= ' ORDER BY ?';
946 push @query_parameters, $orderby;
949 my $sth = $dbh->prepare($query);
950 $sth->execute( @query_parameters );
952 while ( my $row = $sth->fetchrow_hashref ){
958 =head2 GetItemsForInventory
962 $itemlist = GetItemsForInventory($minlocation, $maxlocation, $location, $itemtype $datelastseen, $branch, $offset, $size);
966 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
968 The sub returns a reference to a list of hashes, each containing
969 itemnumber, author, title, barcode, item callnumber, and date last
970 seen. It is ordered by callnumber then title.
972 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
973 the datelastseen can be used to specify that you want to see items not seen since a past date only.
974 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
978 sub GetItemsForInventory {
979 my ( $minlocation, $maxlocation,$location, $itemtype, $datelastseen, $branch, $offset, $size ) = @_;
980 my $dbh = C4::Context->dbh;
982 my $query = <<'END_SQL';
983 SELECT itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
985 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
986 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
987 WHERE itemcallnumber >= ?
988 AND itemcallnumber <= ?
990 my @bind_params = ( $minlocation, $maxlocation );
993 $datelastseen = format_date_in_iso($datelastseen);
994 $query .= ' AND (datelastseen < ? OR datelastseen IS NULL) ';
995 push @bind_params, $datelastseen;
999 $query.= ' AND items.location = ? ';
1000 push @bind_params, $location;
1004 $query.= ' AND items.homebranch = ? ';
1005 push @bind_params, $branch;
1009 $query.= ' AND biblioitems.itemtype = ? ';
1010 push @bind_params, $itemtype;
1013 $query .= ' ORDER BY itemcallnumber, title';
1014 my $sth = $dbh->prepare($query);
1015 $sth->execute( @bind_params );
1019 while ( my $row = $sth->fetchrow_hashref ) {
1020 $offset-- if ($offset);
1021 $row->{datelastseen}=format_date($row->{datelastseen});
1022 if ( ( !$offset ) && $size ) {
1023 push @results, $row;
1030 =head2 GetItemsCount
1033 $count = &GetItemsCount( $biblionumber);
1037 This function return count of item with $biblionumber
1042 my ( $biblionumber ) = @_;
1043 my $dbh = C4::Context->dbh;
1044 my $query = "SELECT count(*)
1046 WHERE biblionumber=?";
1047 my $sth = $dbh->prepare($query);
1048 $sth->execute($biblionumber);
1049 my $count = $sth->fetchrow;
1054 =head2 GetItemInfosOf
1058 GetItemInfosOf(@itemnumbers);
1064 sub GetItemInfosOf {
1065 my @itemnumbers = @_;
1070 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1072 return get_infos_of( $query, 'itemnumber' );
1075 =head2 GetItemsByBiblioitemnumber
1079 GetItemsByBiblioitemnumber($biblioitemnumber);
1083 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1084 Called by C<C4::XISBN>
1088 sub GetItemsByBiblioitemnumber {
1089 my ( $bibitem ) = @_;
1090 my $dbh = C4::Context->dbh;
1091 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1092 # Get all items attached to a biblioitem
1095 $sth->execute($bibitem) || die $sth->errstr;
1096 while ( my $data = $sth->fetchrow_hashref ) {
1097 # Foreach item, get circulation information
1098 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1099 WHERE itemnumber = ?
1100 AND issues.borrowernumber = borrowers.borrowernumber"
1102 $sth2->execute( $data->{'itemnumber'} );
1103 if ( my $data2 = $sth2->fetchrow_hashref ) {
1104 # if item is out, set the due date and who it is out too
1105 $data->{'date_due'} = $data2->{'date_due'};
1106 $data->{'cardnumber'} = $data2->{'cardnumber'};
1107 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1110 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1111 $data->{'date_due'} = '';
1114 # Find the last 3 people who borrowed this item.
1115 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1116 AND old_issues.borrowernumber = borrowers.borrowernumber
1117 ORDER BY returndate desc,timestamp desc LIMIT 3";
1118 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1119 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1121 while ( my $data2 = $sth2->fetchrow_hashref ) {
1122 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1123 $data->{"card$i2"} = $data2->{'cardnumber'};
1124 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1128 push(@results,$data);
1138 @results = GetItemsInfo($biblionumber, $type);
1142 Returns information about books with the given biblionumber.
1144 C<$type> may be either C<intra> or anything else. If it is not set to
1145 C<intra>, then the search will exclude lost, very overdue, and
1148 C<GetItemsInfo> returns a list of references-to-hash. Each element
1149 contains a number of keys. Most of them are table items from the
1150 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1151 Koha database. Other keys include:
1155 =item C<$data-E<gt>{branchname}>
1157 The name (not the code) of the branch to which the book belongs.
1159 =item C<$data-E<gt>{datelastseen}>
1161 This is simply C<items.datelastseen>, except that while the date is
1162 stored in YYYY-MM-DD format in the database, here it is converted to
1163 DD/MM/YYYY format. A NULL date is returned as C<//>.
1165 =item C<$data-E<gt>{datedue}>
1167 =item C<$data-E<gt>{class}>
1169 This is the concatenation of C<biblioitems.classification>, the book's
1170 Dewey code, and C<biblioitems.subclass>.
1172 =item C<$data-E<gt>{ocount}>
1174 I think this is the number of copies of the book available.
1176 =item C<$data-E<gt>{order}>
1178 If this is set, it is set to C<One Order>.
1185 my ( $biblionumber, $type ) = @_;
1186 my $dbh = C4::Context->dbh;
1187 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1193 biblioitems.itemtype,
1196 biblioitems.publicationyear,
1197 biblioitems.publishercode,
1198 biblioitems.volumedate,
1199 biblioitems.volumedesc,
1202 items.notforloan as itemnotforloan,
1203 itemtypes.description
1205 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1206 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1207 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1208 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1209 $query .= " WHERE items.biblionumber = ? ORDER BY items.dateaccessioned desc" ;
1210 my $sth = $dbh->prepare($query);
1211 $sth->execute($biblionumber);
1214 my ( $date_due, $count_reserves, $serial );
1216 my $isth = $dbh->prepare(
1217 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1218 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1219 WHERE itemnumber = ?"
1221 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1222 while ( my $data = $sth->fetchrow_hashref ) {
1224 $isth->execute( $data->{'itemnumber'} );
1225 if ( my $idata = $isth->fetchrow_hashref ) {
1226 $data->{borrowernumber} = $idata->{borrowernumber};
1227 $data->{cardnumber} = $idata->{cardnumber};
1228 $data->{surname} = $idata->{surname};
1229 $data->{firstname} = $idata->{firstname};
1230 $datedue = $idata->{'date_due'};
1231 if (C4::Context->preference("IndependantBranches")){
1232 my $userenv = C4::Context->userenv;
1233 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1234 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1238 if ( $data->{'serial'}) {
1239 $ssth->execute($data->{'itemnumber'}) ;
1240 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1243 if ( $datedue eq '' ) {
1244 my ( $restype, $reserves ) =
1245 C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1247 $count_reserves = $restype;
1252 #get branch information.....
1253 my $bsth = $dbh->prepare(
1254 "SELECT * FROM branches WHERE branchcode = ?
1257 $bsth->execute( $data->{'holdingbranch'} );
1258 if ( my $bdata = $bsth->fetchrow_hashref ) {
1259 $data->{'branchname'} = $bdata->{'branchname'};
1261 $data->{'datedue'} = $datedue;
1262 $data->{'count_reserves'} = $count_reserves;
1264 # get notforloan complete status if applicable
1265 my $sthnflstatus = $dbh->prepare(
1266 'SELECT authorised_value
1267 FROM marc_subfield_structure
1268 WHERE kohafield="items.notforloan"
1272 $sthnflstatus->execute;
1273 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1274 if ($authorised_valuecode) {
1275 $sthnflstatus = $dbh->prepare(
1276 "SELECT lib FROM authorised_values
1278 AND authorised_value=?"
1280 $sthnflstatus->execute( $authorised_valuecode,
1281 $data->{itemnotforloan} );
1282 my ($lib) = $sthnflstatus->fetchrow;
1283 $data->{notforloanvalue} = $lib;
1285 $data->{itypenotforloan} = $data->{notforloan} if (C4::Context->preference('item-level_itypes'));
1287 # my stack procedures
1288 my $stackstatus = $dbh->prepare(
1289 'SELECT authorised_value
1290 FROM marc_subfield_structure
1291 WHERE kohafield="items.stack"
1294 $stackstatus->execute;
1296 ($authorised_valuecode) = $stackstatus->fetchrow;
1297 if ($authorised_valuecode) {
1298 $stackstatus = $dbh->prepare(
1300 FROM authorised_values
1302 AND authorised_value=?
1305 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1306 my ($lib) = $stackstatus->fetchrow;
1307 $data->{stack} = $lib;
1309 # Find the last 3 people who borrowed this item.
1310 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1311 WHERE itemnumber = ?
1312 AND old_issues.borrowernumber = borrowers.borrowernumber
1313 ORDER BY returndate DESC
1315 $sth2->execute($data->{'itemnumber'});
1317 while (my $data2 = $sth2->fetchrow_hashref()) {
1318 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1319 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1320 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1324 $results[$i] = $data;
1328 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1334 =head2 get_itemnumbers_of
1338 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1342 Given a list of biblionumbers, return the list of corresponding itemnumbers
1343 for each biblionumber.
1345 Return a reference on a hash where keys are biblionumbers and values are
1346 references on array of itemnumbers.
1350 sub get_itemnumbers_of {
1351 my @biblionumbers = @_;
1353 my $dbh = C4::Context->dbh;
1359 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1361 my $sth = $dbh->prepare($query);
1362 $sth->execute(@biblionumbers);
1366 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1367 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1370 return \%itemnumbers_of;
1373 =head2 GetItemnumberFromBarcode
1377 $result = GetItemnumberFromBarcode($barcode);
1383 sub GetItemnumberFromBarcode {
1385 my $dbh = C4::Context->dbh;
1388 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1389 $rq->execute($barcode);
1390 my ($result) = $rq->fetchrow;
1394 =head3 get_item_authorised_values
1396 find the types and values for all authorised values assigned to this item.
1401 returns: a hashref malling the authorised value to the value set for this itemnumber
1403 $authorised_values = {
1409 'RESTRICTED' => undef,
1412 'branches' => 'CPL',
1413 'cn_source' => undef,
1414 'itemtypes' => 'SER',
1417 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1421 sub get_item_authorised_values {
1422 my $itemnumber = shift;
1424 # assume that these entries in the authorised_value table are item level.
1425 my $query = q(SELECT distinct authorised_value, kohafield
1426 FROM marc_subfield_structure
1427 WHERE kohafield like 'item%'
1428 AND authorised_value != '' );
1430 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1431 my $iteminfo = GetItem( $itemnumber );
1432 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1434 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1435 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1436 $field =~ s/^items\.//;
1437 if ( exists $iteminfo->{ $field } ) {
1438 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1441 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1445 =head3 get_authorised_value_images
1447 find a list of icons that are appropriate for display based on the
1448 authorised values for a biblio.
1450 parameters: listref of authorised values, such as comes from
1451 get_item_ahtorised_values or
1452 from C4::Biblio::get_biblio_authorised_values
1454 returns: listref of hashrefs for each image. Each hashref looks like
1457 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1462 Notes: Currently, I put on the full path to the images on the staff
1463 side. This should either be configurable or not done at all. Since I
1464 have to deal with 'intranet' or 'opac' in
1465 get_biblio_authorised_values, perhaps I should be passing it in.
1469 sub get_authorised_value_images {
1470 my $authorised_values = shift;
1474 my $authorised_value_list = GetAuthorisedValues();
1475 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1476 foreach my $this_authorised_value ( @$authorised_value_list ) {
1477 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1478 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1479 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1480 if ( defined $this_authorised_value->{'imageurl'} ) {
1481 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1482 label => $this_authorised_value->{'lib'},
1483 category => $this_authorised_value->{'category'},
1484 value => $this_authorised_value->{'authorised_value'}, };
1489 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1494 =head1 LIMITED USE FUNCTIONS
1496 The following functions, while part of the public API,
1497 are not exported. This is generally because they are
1498 meant to be used by only one script for a specific
1499 purpose, and should not be used in any other context
1500 without careful thought.
1508 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1512 Returns MARC::Record of the item passed in parameter.
1513 This function is meant for use only in C<cataloguing/additem.pl>,
1514 where it is needed to support that script's MARC-like
1520 my ( $biblionumber, $itemnumber ) = @_;
1522 # GetMarcItem has been revised so that it does the following:
1523 # 1. Gets the item information from the items table.
1524 # 2. Converts it to a MARC field for storage in the bib record.
1526 # The previous behavior was:
1527 # 1. Get the bib record.
1528 # 2. Return the MARC tag corresponding to the item record.
1530 # The difference is that one treats the items row as authoritative,
1531 # while the other treats the MARC representation as authoritative
1532 # under certain circumstances.
1534 my $itemrecord = GetItem($itemnumber);
1536 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1537 # Also, don't emit a subfield if the underlying field is blank.
1540 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1541 } keys %{ $itemrecord }
1543 my $itemmarc = TransformKohaToMarc($mungeditem);
1545 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1546 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1547 my @fields = $itemmarc->fields();
1548 if ($#fields > -1) {
1549 $fields[0]->add_subfields(@$unlinked_item_subfields);
1557 =head1 PRIVATE FUNCTIONS AND VARIABLES
1559 The following functions are not meant to be called
1560 directly, but are documented in order to explain
1561 the inner workings of C<C4::Items>.
1565 =head2 %derived_columns
1567 This hash keeps track of item columns that
1568 are strictly derived from other columns in
1569 the item record and are not meant to be set
1572 Each key in the hash should be the name of a
1573 column (as named by TransformMarcToKoha). Each
1574 value should be hashref whose keys are the
1575 columns on which the derived column depends. The
1576 hashref should also contain a 'BUILDER' key
1577 that is a reference to a sub that calculates
1582 my %derived_columns = (
1583 'items.cn_sort' => {
1584 'itemcallnumber' => 1,
1585 'items.cn_source' => 1,
1586 'BUILDER' => \&_calc_items_cn_sort,
1590 =head2 _set_derived_columns_for_add
1594 _set_derived_column_for_add($item);
1598 Given an item hash representing a new item to be added,
1599 calculate any derived columns. Currently the only
1600 such column is C<items.cn_sort>.
1604 sub _set_derived_columns_for_add {
1607 foreach my $column (keys %derived_columns) {
1608 my $builder = $derived_columns{$column}->{'BUILDER'};
1609 my $source_values = {};
1610 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1611 next if $source_column eq 'BUILDER';
1612 $source_values->{$source_column} = $item->{$source_column};
1614 $builder->($item, $source_values);
1618 =head2 _set_derived_columns_for_mod
1622 _set_derived_column_for_mod($item);
1626 Given an item hash representing a new item to be modified.
1627 calculate any derived columns. Currently the only
1628 such column is C<items.cn_sort>.
1630 This routine differs from C<_set_derived_columns_for_add>
1631 in that it needs to handle partial item records. In other
1632 words, the caller of C<ModItem> may have supplied only one
1633 or two columns to be changed, so this function needs to
1634 determine whether any of the columns to be changed affect
1635 any of the derived columns. Also, if a derived column
1636 depends on more than one column, but the caller is not
1637 changing all of then, this routine retrieves the unchanged
1638 values from the database in order to ensure a correct
1643 sub _set_derived_columns_for_mod {
1646 foreach my $column (keys %derived_columns) {
1647 my $builder = $derived_columns{$column}->{'BUILDER'};
1648 my $source_values = {};
1649 my %missing_sources = ();
1650 my $must_recalc = 0;
1651 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1652 next if $source_column eq 'BUILDER';
1653 if (exists $item->{$source_column}) {
1655 $source_values->{$source_column} = $item->{$source_column};
1657 $missing_sources{$source_column} = 1;
1661 foreach my $source_column (keys %missing_sources) {
1662 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1664 $builder->($item, $source_values);
1669 =head2 _do_column_fixes_for_mod
1673 _do_column_fixes_for_mod($item);
1677 Given an item hashref containing one or more
1678 columns to modify, fix up certain values.
1679 Specifically, set to 0 any passed value
1680 of C<notforloan>, C<damaged>, C<itemlost>, or
1681 C<wthdrawn> that is either undefined or
1682 contains the empty string.
1686 sub _do_column_fixes_for_mod {
1689 if (exists $item->{'notforloan'} and
1690 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1691 $item->{'notforloan'} = 0;
1693 if (exists $item->{'damaged'} and
1694 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1695 $item->{'damaged'} = 0;
1697 if (exists $item->{'itemlost'} and
1698 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1699 $item->{'itemlost'} = 0;
1701 if (exists $item->{'wthdrawn'} and
1702 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1703 $item->{'wthdrawn'} = 0;
1707 =head2 _get_single_item_column
1711 _get_single_item_column($column, $itemnumber);
1715 Retrieves the value of a single column from an C<items>
1716 row specified by C<$itemnumber>.
1720 sub _get_single_item_column {
1722 my $itemnumber = shift;
1724 my $dbh = C4::Context->dbh;
1725 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
1726 $sth->execute($itemnumber);
1727 my ($value) = $sth->fetchrow();
1731 =head2 _calc_items_cn_sort
1735 _calc_items_cn_sort($item, $source_values);
1739 Helper routine to calculate C<items.cn_sort>.
1743 sub _calc_items_cn_sort {
1745 my $source_values = shift;
1747 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
1750 =head2 _set_defaults_for_add
1754 _set_defaults_for_add($item_hash);
1758 Given an item hash representing an item to be added, set
1759 correct default values for columns whose default value
1760 is not handled by the DBMS. This includes the following
1767 C<items.dateaccessioned>
1789 sub _set_defaults_for_add {
1792 # if dateaccessioned is provided, use it. Otherwise, set to NOW()
1793 if (!(exists $item->{'dateaccessioned'}) ||
1794 ($item->{'dateaccessioned'} eq '')) {
1795 # FIXME add check for invalid date
1796 my $today = C4::Dates->new();
1797 $item->{'dateaccessioned'} = $today->output("iso"); #TODO: check time issues
1800 # various item status fields cannot be null
1801 $item->{'notforloan'} = 0 unless exists $item->{'notforloan'} and defined $item->{'notforloan'} and $item->{'notforloan'} ne '';
1802 $item->{'damaged'} = 0 unless exists $item->{'damaged'} and defined $item->{'damaged'} and $item->{'damaged'} ne '';
1803 $item->{'itemlost'} = 0 unless exists $item->{'itemlost'} and defined $item->{'itemlost'} and $item->{'itemlost'} ne '';
1804 $item->{'wthdrawn'} = 0 unless exists $item->{'wthdrawn'} and defined $item->{'wthdrawn'} and $item->{'wthdrawn'} ne '';
1807 =head2 _koha_new_item
1811 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
1815 Perform the actual insert into the C<items> table.
1819 sub _koha_new_item {
1820 my ( $item, $barcode ) = @_;
1821 my $dbh=C4::Context->dbh;
1824 "INSERT INTO items SET
1826 biblioitemnumber = ?,
1828 dateaccessioned = ?,
1832 replacementprice = ?,
1833 replacementpricedate = NOW(),
1834 datelastborrowed = ?,
1835 datelastseen = NOW(),
1858 more_subfields_xml = ?,
1861 my $sth = $dbh->prepare($query);
1863 $item->{'biblionumber'},
1864 $item->{'biblioitemnumber'},
1866 $item->{'dateaccessioned'},
1867 $item->{'booksellerid'},
1868 $item->{'homebranch'},
1870 $item->{'replacementprice'},
1871 $item->{datelastborrowed},
1873 $item->{'notforloan'},
1875 $item->{'itemlost'},
1876 $item->{'wthdrawn'},
1877 $item->{'itemcallnumber'},
1878 $item->{'restricted'},
1879 $item->{'itemnotes'},
1880 $item->{'holdingbranch'},
1882 $item->{'location'},
1885 $item->{'renewals'},
1886 $item->{'reserves'},
1887 $item->{'items.cn_source'},
1888 $item->{'items.cn_sort'},
1891 $item->{'materials'},
1893 $item->{'enumchron'},
1894 $item->{'more_subfields_xml'},
1895 $item->{'copynumber'},
1897 my $itemnumber = $dbh->{'mysql_insertid'};
1898 if ( defined $sth->errstr ) {
1899 $error.="ERROR in _koha_new_item $query".$sth->errstr;
1902 return ( $itemnumber, $error );
1905 =head2 _koha_modify_item
1909 my ($itemnumber,$error) =_koha_modify_item( $item );
1913 Perform the actual update of the C<items> row. Note that this
1914 routine accepts a hashref specifying the columns to update.
1918 sub _koha_modify_item {
1920 my $dbh=C4::Context->dbh;
1923 my $query = "UPDATE items SET ";
1925 for my $key ( keys %$item ) {
1927 push @bind, $item->{$key};
1930 $query .= " WHERE itemnumber=?";
1931 push @bind, $item->{'itemnumber'};
1932 my $sth = C4::Context->dbh->prepare($query);
1933 $sth->execute(@bind);
1934 if ( C4::Context->dbh->errstr ) {
1935 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
1939 return ($item->{'itemnumber'},$error);
1942 =head2 _koha_delete_item
1946 _koha_delete_item( $dbh, $itemnum );
1950 Internal function to delete an item record from the koha tables
1954 sub _koha_delete_item {
1955 my ( $dbh, $itemnum ) = @_;
1957 # save the deleted item to deleteditems table
1958 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
1959 $sth->execute($itemnum);
1960 my $data = $sth->fetchrow_hashref();
1962 my $query = "INSERT INTO deleteditems SET ";
1964 foreach my $key ( keys %$data ) {
1965 $query .= "$key = ?,";
1966 push( @bind, $data->{$key} );
1969 $sth = $dbh->prepare($query);
1970 $sth->execute(@bind);
1973 # delete from items table
1974 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
1975 $sth->execute($itemnum);
1980 =head2 _marc_from_item_hash
1984 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
1988 Given an item hash representing a complete item record,
1989 create a C<MARC::Record> object containing an embedded
1990 tag representing that item.
1992 The third, optional parameter C<$unlinked_item_subfields> is
1993 an arrayref of subfields (not mapped to C<items> fields per the
1994 framework) to be added to the MARC representation
1999 sub _marc_from_item_hash {
2001 my $frameworkcode = shift;
2002 my $unlinked_item_subfields;
2004 $unlinked_item_subfields = shift;
2007 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2008 # Also, don't emit a subfield if the underlying field is blank.
2009 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2010 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2011 : () } keys %{ $item } };
2013 my $item_marc = MARC::Record->new();
2014 foreach my $item_field (keys %{ $mungeditem }) {
2015 my ($tag, $subfield) = GetMarcFromKohaField($item_field, $frameworkcode);
2016 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2017 if (my $field = $item_marc->field($tag)) {
2018 $field->add_subfields($subfield => $mungeditem->{$item_field});
2020 my $add_subfields = [];
2021 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2022 $add_subfields = $unlinked_item_subfields;
2024 $item_marc->add_fields( $tag, " ", " ", $subfield => $mungeditem->{$item_field}, @$add_subfields);
2031 =head2 _add_item_field_to_biblio
2035 _add_item_field_to_biblio($item_marc, $biblionumber, $frameworkcode);
2039 Adds the fields from a MARC record containing the
2040 representation of a Koha item record to the MARC
2041 biblio record. The input C<$item_marc> record
2042 is expect to contain just one field, the embedded
2043 item information field.
2047 sub _add_item_field_to_biblio {
2048 my ($item_marc, $biblionumber, $frameworkcode) = @_;
2050 my $biblio_marc = GetMarcBiblio($biblionumber);
2051 foreach my $field ($item_marc->fields()) {
2052 $biblio_marc->append_fields($field);
2055 ModBiblioMarc($biblio_marc, $biblionumber, $frameworkcode);
2058 =head2 _replace_item_field_in_biblio
2062 &_replace_item_field_in_biblio($item_marc, $biblionumber, $itemnumber, $frameworkcode)
2066 Given a MARC::Record C<$item_marc> containing one tag with the MARC
2067 representation of the item, examine the biblio MARC
2068 for the corresponding tag for that item and
2069 replace it with the tag from C<$item_marc>.
2073 sub _replace_item_field_in_biblio {
2074 my ($ItemRecord, $biblionumber, $itemnumber, $frameworkcode) = @_;
2075 my $dbh = C4::Context->dbh;
2077 # get complete MARC record & replace the item field by the new one
2078 my $completeRecord = GetMarcBiblio($biblionumber);
2079 my ($itemtag,$itemsubfield) = GetMarcFromKohaField("items.itemnumber",$frameworkcode);
2080 my $itemField = $ItemRecord->field($itemtag);
2081 my @items = $completeRecord->field($itemtag);
2084 if ($_->subfield($itemsubfield) eq $itemnumber) {
2085 $_->replace_with($itemField);
2091 # If we haven't found the matching field,
2092 # just add it. However, this means that
2093 # there is likely a bug.
2094 $completeRecord->append_fields($itemField);
2098 ModBiblioMarc($completeRecord, $biblionumber, $frameworkcode);
2101 =head2 _repack_item_errors
2103 Add an error message hash generated by C<CheckItemPreSave>
2104 to a list of errors.
2108 sub _repack_item_errors {
2109 my $item_sequence_num = shift;
2110 my $item_ref = shift;
2111 my $error_ref = shift;
2113 my @repacked_errors = ();
2115 foreach my $error_code (sort keys %{ $error_ref }) {
2116 my $repacked_error = {};
2117 $repacked_error->{'item_sequence'} = $item_sequence_num;
2118 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2119 $repacked_error->{'error_code'} = $error_code;
2120 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2121 push @repacked_errors, $repacked_error;
2124 return @repacked_errors;
2127 =head2 _get_unlinked_item_subfields
2131 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2137 sub _get_unlinked_item_subfields {
2138 my $original_item_marc = shift;
2139 my $frameworkcode = shift;
2141 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2143 # assume that this record has only one field, and that that
2144 # field contains only the item information
2146 my @fields = $original_item_marc->fields();
2147 if ($#fields > -1) {
2148 my $field = $fields[0];
2149 my $tag = $field->tag();
2150 foreach my $subfield ($field->subfields()) {
2151 if (defined $subfield->[1] and
2152 $subfield->[1] ne '' and
2153 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2154 push @$subfields, $subfield->[0] => $subfield->[1];
2161 =head2 _get_unlinked_subfields_xml
2165 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2171 sub _get_unlinked_subfields_xml {
2172 my $unlinked_item_subfields = shift;
2175 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2176 my $marc = MARC::Record->new();
2177 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2178 # used in the framework
2179 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2180 $marc->encoding("UTF-8");
2181 $xml = $marc->as_xml("USMARC");
2187 =head2 _parse_unlinked_item_subfields_from_xml
2191 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2197 sub _parse_unlinked_item_subfields_from_xml {
2200 return unless defined $xml and $xml ne "";
2201 my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2202 my $unlinked_subfields = [];
2203 my @fields = $marc->fields();
2204 if ($#fields > -1) {
2205 foreach my $subfield ($fields[0]->subfields()) {
2206 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2209 return $unlinked_subfields;