Bug 7982: [SIGNED-OFF] Typo in moremember-receipt.tt
[koha.git] / C4 / Items.pm
blob52423a27d5153ec51ceb1ae213b7d3fa2813e73c
1 package C4::Items;
3 # Copyright 2007 LibLime, Inc.
4 # Parts Copyright Biblibre 2010
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 use strict;
22 #use warnings; FIXME - Bug 2505
24 use Carp;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Biblio;
28 use C4::Dates qw/format_date format_date_in_iso/;
29 use MARC::Record;
30 use C4::ClassSource;
31 use C4::Log;
32 use List::MoreUtils qw/any/;
33 use C4::Search;
34 use Data::Dumper; # used as part of logging item record changes, not just for
35 # debugging; so please don't remove this
37 use vars qw($VERSION @ISA @EXPORT);
39 BEGIN {
40 $VERSION = 3.01;
42 require Exporter;
43 @ISA = qw( Exporter );
45 # function exports
46 @EXPORT = qw(
47 GetItem
48 AddItemFromMarc
49 AddItem
50 AddItemBatchFromMarc
51 ModItemFromMarc
52 Item2Marc
53 ModItem
54 ModDateLastSeen
55 ModItemTransfer
56 DelItem
58 CheckItemPreSave
60 GetItemStatus
61 GetItemLocation
62 GetLostItems
63 GetItemsForInventory
64 GetItemsCount
65 GetItemInfosOf
66 GetItemsByBiblioitemnumber
67 GetItemsInfo
68 GetItemsLocationInfo
69 GetHostItemsInfo
70 GetItemnumbersForBiblio
71 get_itemnumbers_of
72 get_hostitemnumbers_of
73 GetItemnumberFromBarcode
74 GetBarcodeFromItemnumber
75 GetHiddenItemnumbers
76 DelItemCheck
77 MoveItemFromBiblio
78 GetLatestAcquisitions
79 CartToShelf
81 GetAnalyticsCount
82 GetItemHolds
85 PrepareItemrecordDisplay
90 =head1 NAME
92 C4::Items - item management functions
94 =head1 DESCRIPTION
96 This module contains an API for manipulating item
97 records in Koha, and is used by cataloguing, circulation,
98 acquisitions, and serials management.
100 A Koha item record is stored in two places: the
101 items table and embedded in a MARC tag in the XML
102 version of the associated bib record in C<biblioitems.marcxml>.
103 This is done to allow the item information to be readily
104 indexed (e.g., by Zebra), but means that each item
105 modification transaction must keep the items table
106 and the MARC XML in sync at all times.
108 Consequently, all code that creates, modifies, or deletes
109 item records B<must> use an appropriate function from
110 C<C4::Items>. If no existing function is suitable, it is
111 better to add one to C<C4::Items> than to use add
112 one-off SQL statements to add or modify items.
114 The items table will be considered authoritative. In other
115 words, if there is ever a discrepancy between the items
116 table and the MARC XML, the items table should be considered
117 accurate.
119 =head1 HISTORICAL NOTE
121 Most of the functions in C<C4::Items> were originally in
122 the C<C4::Biblio> module.
124 =head1 CORE EXPORTED FUNCTIONS
126 The following functions are meant for use by users
127 of C<C4::Items>
129 =cut
131 =head2 GetItem
133 $item = GetItem($itemnumber,$barcode,$serial);
135 Return item information, for a given itemnumber or barcode.
136 The return value is a hashref mapping item column
137 names to values. If C<$serial> is true, include serial publication data.
139 =cut
141 sub GetItem {
142 my ($itemnumber,$barcode, $serial) = @_;
143 my $dbh = C4::Context->dbh;
144 my $data;
145 if ($itemnumber) {
146 my $sth = $dbh->prepare("
147 SELECT * FROM items
148 WHERE itemnumber = ?");
149 $sth->execute($itemnumber);
150 $data = $sth->fetchrow_hashref;
151 } else {
152 my $sth = $dbh->prepare("
153 SELECT * FROM items
154 WHERE barcode = ?"
156 $sth->execute($barcode);
157 $data = $sth->fetchrow_hashref;
159 if ( $serial) {
160 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
161 $ssth->execute($data->{'itemnumber'}) ;
162 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
164 #if we don't have an items.itype, use biblioitems.itemtype.
165 if( ! $data->{'itype'} ) {
166 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
167 $sth->execute($data->{'biblionumber'});
168 ($data->{'itype'}) = $sth->fetchrow_array;
170 return $data;
171 } # sub GetItem
173 =head2 CartToShelf
175 CartToShelf($itemnumber);
177 Set the current shelving location of the item record
178 to its stored permanent shelving location. This is
179 primarily used to indicate when an item whose current
180 location is a special processing ('PROC') or shelving cart
181 ('CART') location is back in the stacks.
183 =cut
185 sub CartToShelf {
186 my ( $itemnumber ) = @_;
188 unless ( $itemnumber ) {
189 croak "FAILED CartToShelf() - no itemnumber supplied";
192 my $item = GetItem($itemnumber);
193 $item->{location} = $item->{permanent_location};
194 ModItem($item, undef, $itemnumber);
197 =head2 AddItemFromMarc
199 my ($biblionumber, $biblioitemnumber, $itemnumber)
200 = AddItemFromMarc($source_item_marc, $biblionumber);
202 Given a MARC::Record object containing an embedded item
203 record and a biblionumber, create a new item record.
205 =cut
207 sub AddItemFromMarc {
208 my ( $source_item_marc, $biblionumber ) = @_;
209 my $dbh = C4::Context->dbh;
211 # parse item hash from MARC
212 my $frameworkcode = GetFrameworkCode( $biblionumber );
213 my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
215 my $localitemmarc=MARC::Record->new;
216 $localitemmarc->append_fields($source_item_marc->field($itemtag));
217 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
218 my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
219 return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
222 =head2 AddItem
224 my ($biblionumber, $biblioitemnumber, $itemnumber)
225 = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
227 Given a hash containing item column names as keys,
228 create a new Koha item record.
230 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
231 do not need to be supplied for general use; they exist
232 simply to allow them to be picked up from AddItemFromMarc.
234 The final optional parameter, C<$unlinked_item_subfields>, contains
235 an arrayref containing subfields present in the original MARC
236 representation of the item (e.g., from the item editor) that are
237 not mapped to C<items> columns directly but should instead
238 be stored in C<items.more_subfields_xml> and included in
239 the biblio items tag for display and indexing.
241 =cut
243 sub AddItem {
244 my $item = shift;
245 my $biblionumber = shift;
247 my $dbh = @_ ? shift : C4::Context->dbh;
248 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
249 my $unlinked_item_subfields;
250 if (@_) {
251 $unlinked_item_subfields = shift
254 # needs old biblionumber and biblioitemnumber
255 $item->{'biblionumber'} = $biblionumber;
256 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
257 $sth->execute( $item->{'biblionumber'} );
258 ($item->{'biblioitemnumber'}) = $sth->fetchrow;
260 _set_defaults_for_add($item);
261 _set_derived_columns_for_add($item);
262 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
263 # FIXME - checks here
264 unless ( $item->{itype} ) { # default to biblioitem.itemtype if no itype
265 my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
266 $itype_sth->execute( $item->{'biblionumber'} );
267 ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
270 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
271 $item->{'itemnumber'} = $itemnumber;
273 ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
275 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
277 return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
280 =head2 AddItemBatchFromMarc
282 ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record,
283 $biblionumber, $biblioitemnumber, $frameworkcode);
285 Efficiently create item records from a MARC biblio record with
286 embedded item fields. This routine is suitable for batch jobs.
288 This API assumes that the bib record has already been
289 saved to the C<biblio> and C<biblioitems> tables. It does
290 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
291 are populated, but it will do so via a call to ModBibiloMarc.
293 The goal of this API is to have a similar effect to using AddBiblio
294 and AddItems in succession, but without inefficient repeated
295 parsing of the MARC XML bib record.
297 This function returns an arrayref of new itemsnumbers and an arrayref of item
298 errors encountered during the processing. Each entry in the errors
299 list is a hashref containing the following keys:
301 =over
303 =item item_sequence
305 Sequence number of original item tag in the MARC record.
307 =item item_barcode
309 Item barcode, provide to assist in the construction of
310 useful error messages.
312 =item error_code
314 Code representing the error condition. Can be 'duplicate_barcode',
315 'invalid_homebranch', or 'invalid_holdingbranch'.
317 =item error_information
319 Additional information appropriate to the error condition.
321 =back
323 =cut
325 sub AddItemBatchFromMarc {
326 my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
327 my $error;
328 my @itemnumbers = ();
329 my @errors = ();
330 my $dbh = C4::Context->dbh;
332 # We modify the record, so lets work on a clone so we don't change the
333 # original.
334 $record = $record->clone();
335 # loop through the item tags and start creating items
336 my @bad_item_fields = ();
337 my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
338 my $item_sequence_num = 0;
339 ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
340 $item_sequence_num++;
341 # we take the item field and stick it into a new
342 # MARC record -- this is required so far because (FIXME)
343 # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
344 # and there is no TransformMarcFieldToKoha
345 my $temp_item_marc = MARC::Record->new();
346 $temp_item_marc->append_fields($item_field);
348 # add biblionumber and biblioitemnumber
349 my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
350 my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
351 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
352 $item->{'biblionumber'} = $biblionumber;
353 $item->{'biblioitemnumber'} = $biblioitemnumber;
355 # check for duplicate barcode
356 my %item_errors = CheckItemPreSave($item);
357 if (%item_errors) {
358 push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
359 push @bad_item_fields, $item_field;
360 next ITEMFIELD;
363 _set_defaults_for_add($item);
364 _set_derived_columns_for_add($item);
365 my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
366 warn $error if $error;
367 push @itemnumbers, $itemnumber; # FIXME not checking error
368 $item->{'itemnumber'} = $itemnumber;
370 logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
372 my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
373 $item_field->replace_with($new_item_marc->field($itemtag));
376 # remove any MARC item fields for rejected items
377 foreach my $item_field (@bad_item_fields) {
378 $record->delete_field($item_field);
381 # update the MARC biblio
382 # $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
384 return (\@itemnumbers, \@errors);
387 =head2 ModItemFromMarc
389 ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
391 This function updates an item record based on a supplied
392 C<MARC::Record> object containing an embedded item field.
393 This API is meant for the use of C<additem.pl>; for
394 other purposes, C<ModItem> should be used.
396 This function uses the hash %default_values_for_mod_from_marc,
397 which contains default values for item fields to
398 apply when modifying an item. This is needed beccause
399 if an item field's value is cleared, TransformMarcToKoha
400 does not include the column in the
401 hash that's passed to ModItem, which without
402 use of this hash makes it impossible to clear
403 an item field's value. See bug 2466.
405 Note that only columns that can be directly
406 changed from the cataloging and serials
407 item editors are included in this hash.
409 Returns item record
411 =cut
413 my %default_values_for_mod_from_marc = (
414 barcode => undef,
415 booksellerid => undef,
416 ccode => undef,
417 'items.cn_source' => undef,
418 copynumber => undef,
419 damaged => 0,
420 # dateaccessioned => undef,
421 enumchron => undef,
422 holdingbranch => undef,
423 homebranch => undef,
424 itemcallnumber => undef,
425 itemlost => 0,
426 itemnotes => undef,
427 itype => undef,
428 location => undef,
429 permanent_location => undef,
430 materials => undef,
431 notforloan => 0,
432 paidfor => undef,
433 price => undef,
434 replacementprice => undef,
435 replacementpricedate => undef,
436 restricted => undef,
437 stack => undef,
438 stocknumber => undef,
439 uri => undef,
440 wthdrawn => 0,
443 sub ModItemFromMarc {
444 my $item_marc = shift;
445 my $biblionumber = shift;
446 my $itemnumber = shift;
448 my $dbh = C4::Context->dbh;
449 my $frameworkcode = GetFrameworkCode($biblionumber);
450 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
452 my $localitemmarc = MARC::Record->new;
453 $localitemmarc->append_fields( $item_marc->field($itemtag) );
454 my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
455 foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
456 $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
458 my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
460 ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields);
461 return $item;
464 =head2 ModItem
466 ModItem({ column => $newvalue }, $biblionumber, $itemnumber);
468 Change one or more columns in an item record and update
469 the MARC representation of the item.
471 The first argument is a hashref mapping from item column
472 names to the new values. The second and third arguments
473 are the biblionumber and itemnumber, respectively.
475 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
476 an arrayref containing subfields present in the original MARC
477 representation of the item (e.g., from the item editor) that are
478 not mapped to C<items> columns directly but should instead
479 be stored in C<items.more_subfields_xml> and included in
480 the biblio items tag for display and indexing.
482 If one of the changed columns is used to calculate
483 the derived value of a column such as C<items.cn_sort>,
484 this routine will perform the necessary calculation
485 and set the value.
487 =cut
489 sub ModItem {
490 my $item = shift;
491 my $biblionumber = shift;
492 my $itemnumber = shift;
494 # if $biblionumber is undefined, get it from the current item
495 unless (defined $biblionumber) {
496 $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
499 my $dbh = @_ ? shift : C4::Context->dbh;
500 my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
502 my $unlinked_item_subfields;
503 if (@_) {
504 $unlinked_item_subfields = shift;
505 $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
508 $item->{'itemnumber'} = $itemnumber or return undef;
510 $item->{onloan} = undef if $item->{itemlost};
512 _set_derived_columns_for_mod($item);
513 _do_column_fixes_for_mod($item);
514 # FIXME add checks
515 # duplicate barcode
516 # attempt to change itemnumber
517 # attempt to change biblionumber (if we want
518 # an API to relink an item to a different bib,
519 # it should be a separate function)
521 # update items table
522 _koha_modify_item($item);
524 # request that bib be reindexed so that searching on current
525 # item status is possible
526 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
528 logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
531 =head2 ModItemTransfer
533 ModItemTransfer($itenumber, $frombranch, $tobranch);
535 Marks an item as being transferred from one branch
536 to another.
538 =cut
540 sub ModItemTransfer {
541 my ( $itemnumber, $frombranch, $tobranch ) = @_;
543 my $dbh = C4::Context->dbh;
545 #new entry in branchtransfers....
546 my $sth = $dbh->prepare(
547 "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
548 VALUES (?, ?, NOW(), ?)");
549 $sth->execute($itemnumber, $frombranch, $tobranch);
551 ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
552 ModDateLastSeen($itemnumber);
553 return;
556 =head2 ModDateLastSeen
558 ModDateLastSeen($itemnum);
560 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
561 C<$itemnum> is the item number
563 =cut
565 sub ModDateLastSeen {
566 my ($itemnumber) = @_;
568 my $today = C4::Dates->new();
569 ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
572 =head2 DelItem
574 DelItem($dbh, $biblionumber, $itemnumber);
576 Exported function (core API) for deleting an item record in Koha.
578 =cut
580 sub DelItem {
581 my ( $dbh, $biblionumber, $itemnumber ) = @_;
583 # FIXME check the item has no current issues
585 _koha_delete_item( $dbh, $itemnumber );
587 # get the MARC record
588 my $record = GetMarcBiblio($biblionumber);
589 ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
591 # backup the record
592 my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
593 $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
594 # This last update statement makes that the timestamp column in deleteditems is updated too. If you remove these lines, please add a line to update the timestamp separately. See Bugzilla report 7146 and Biblio.pm (DelBiblio).
596 #search item field code
597 logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
600 =head2 CheckItemPreSave
602 my $item_ref = TransformMarcToKoha($marc, 'items');
603 # do stuff
604 my %errors = CheckItemPreSave($item_ref);
605 if (exists $errors{'duplicate_barcode'}) {
606 print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
607 } elsif (exists $errors{'invalid_homebranch'}) {
608 print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
609 } elsif (exists $errors{'invalid_holdingbranch'}) {
610 print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
611 } else {
612 print "item is OK";
615 Given a hashref containing item fields, determine if it can be
616 inserted or updated in the database. Specifically, checks for
617 database integrity issues, and returns a hash containing any
618 of the following keys, if applicable.
620 =over 2
622 =item duplicate_barcode
624 Barcode, if it duplicates one already found in the database.
626 =item invalid_homebranch
628 Home branch, if not defined in branches table.
630 =item invalid_holdingbranch
632 Holding branch, if not defined in branches table.
634 =back
636 This function does NOT implement any policy-related checks,
637 e.g., whether current operator is allowed to save an
638 item that has a given branch code.
640 =cut
642 sub CheckItemPreSave {
643 my $item_ref = shift;
644 require C4::Branch;
646 my %errors = ();
648 # check for duplicate barcode
649 if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
650 my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
651 if ($existing_itemnumber) {
652 if (!exists $item_ref->{'itemnumber'} # new item
653 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
654 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
659 # check for valid home branch
660 if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
661 my $branch_name = C4::Branch::GetBranchName($item_ref->{'homebranch'});
662 unless (defined $branch_name) {
663 # relies on fact that branches.branchname is a non-NULL column,
664 # so GetBranchName returns undef only if branch does not exist
665 $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
669 # check for valid holding branch
670 if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
671 my $branch_name = C4::Branch::GetBranchName($item_ref->{'holdingbranch'});
672 unless (defined $branch_name) {
673 # relies on fact that branches.branchname is a non-NULL column,
674 # so GetBranchName returns undef only if branch does not exist
675 $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
679 return %errors;
683 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
685 The following functions provide various ways of
686 getting an item record, a set of item records, or
687 lists of authorized values for certain item fields.
689 Some of the functions in this group are candidates
690 for refactoring -- for example, some of the code
691 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
692 has copy-and-paste work.
694 =cut
696 =head2 GetItemStatus
698 $itemstatushash = GetItemStatus($fwkcode);
700 Returns a list of valid values for the
701 C<items.notforloan> field.
703 NOTE: does B<not> return an individual item's
704 status.
706 Can be MARC dependant.
707 fwkcode is optional.
708 But basically could be can be loan or not
709 Create a status selector with the following code
711 =head3 in PERL SCRIPT
713 my $itemstatushash = getitemstatus;
714 my @itemstatusloop;
715 foreach my $thisstatus (keys %$itemstatushash) {
716 my %row =(value => $thisstatus,
717 statusname => $itemstatushash->{$thisstatus}->{'statusname'},
719 push @itemstatusloop, \%row;
721 $template->param(statusloop=>\@itemstatusloop);
723 =head3 in TEMPLATE
725 <select name="statusloop">
726 <option value="">Default</option>
727 <!-- TMPL_LOOP name="statusloop" -->
728 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
729 <!-- /TMPL_LOOP -->
730 </select>
732 =cut
734 sub GetItemStatus {
736 # returns a reference to a hash of references to status...
737 my ($fwk) = @_;
738 my %itemstatus;
739 my $dbh = C4::Context->dbh;
740 my $sth;
741 $fwk = '' unless ($fwk);
742 my ( $tag, $subfield ) =
743 GetMarcFromKohaField( "items.notforloan", $fwk );
744 if ( $tag and $subfield ) {
745 my $sth =
746 $dbh->prepare(
747 "SELECT authorised_value
748 FROM marc_subfield_structure
749 WHERE tagfield=?
750 AND tagsubfield=?
751 AND frameworkcode=?
754 $sth->execute( $tag, $subfield, $fwk );
755 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
756 my $authvalsth =
757 $dbh->prepare(
758 "SELECT authorised_value,lib
759 FROM authorised_values
760 WHERE category=?
761 ORDER BY lib
764 $authvalsth->execute($authorisedvaluecat);
765 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
766 $itemstatus{$authorisedvalue} = $lib;
768 return \%itemstatus;
769 exit 1;
771 else {
773 #No authvalue list
774 # build default
778 #No authvalue list
779 #build default
780 $itemstatus{"1"} = "Not For Loan";
781 return \%itemstatus;
784 =head2 GetItemLocation
786 $itemlochash = GetItemLocation($fwk);
788 Returns a list of valid values for the
789 C<items.location> field.
791 NOTE: does B<not> return an individual item's
792 location.
794 where fwk stands for an optional framework code.
795 Create a location selector with the following code
797 =head3 in PERL SCRIPT
799 my $itemlochash = getitemlocation;
800 my @itemlocloop;
801 foreach my $thisloc (keys %$itemlochash) {
802 my $selected = 1 if $thisbranch eq $branch;
803 my %row =(locval => $thisloc,
804 selected => $selected,
805 locname => $itemlochash->{$thisloc},
807 push @itemlocloop, \%row;
809 $template->param(itemlocationloop => \@itemlocloop);
811 =head3 in TEMPLATE
813 <select name="location">
814 <option value="">Default</option>
815 <!-- TMPL_LOOP name="itemlocationloop" -->
816 <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
817 <!-- /TMPL_LOOP -->
818 </select>
820 =cut
822 sub GetItemLocation {
824 # returns a reference to a hash of references to location...
825 my ($fwk) = @_;
826 my %itemlocation;
827 my $dbh = C4::Context->dbh;
828 my $sth;
829 $fwk = '' unless ($fwk);
830 my ( $tag, $subfield ) =
831 GetMarcFromKohaField( "items.location", $fwk );
832 if ( $tag and $subfield ) {
833 my $sth =
834 $dbh->prepare(
835 "SELECT authorised_value
836 FROM marc_subfield_structure
837 WHERE tagfield=?
838 AND tagsubfield=?
839 AND frameworkcode=?"
841 $sth->execute( $tag, $subfield, $fwk );
842 if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
843 my $authvalsth =
844 $dbh->prepare(
845 "SELECT authorised_value,lib
846 FROM authorised_values
847 WHERE category=?
848 ORDER BY lib"
850 $authvalsth->execute($authorisedvaluecat);
851 while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
852 $itemlocation{$authorisedvalue} = $lib;
854 return \%itemlocation;
855 exit 1;
857 else {
859 #No authvalue list
860 # build default
864 #No authvalue list
865 #build default
866 $itemlocation{"1"} = "Not For Loan";
867 return \%itemlocation;
870 =head2 GetLostItems
872 $items = GetLostItems( $where, $orderby );
874 This function gets a list of lost items.
876 =over 2
878 =item input:
880 C<$where> is a hashref. it containts a field of the items table as key
881 and the value to match as value. For example:
883 { barcode => 'abc123',
884 homebranch => 'CPL', }
886 C<$orderby> is a field of the items table by which the resultset
887 should be orderd.
889 =item return:
891 C<$items> is a reference to an array full of hashrefs with columns
892 from the "items" table as keys.
894 =item usage in the perl script:
896 my $where = { barcode => '0001548' };
897 my $items = GetLostItems( $where, "homebranch" );
898 $template->param( itemsloop => $items );
900 =back
902 =cut
904 sub GetLostItems {
905 # Getting input args.
906 my $where = shift;
907 my $orderby = shift;
908 my $dbh = C4::Context->dbh;
910 my $query = "
911 SELECT *
912 FROM items
913 LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
914 LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
915 LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
916 WHERE
917 authorised_values.category = 'LOST'
918 AND itemlost IS NOT NULL
919 AND itemlost <> 0
921 my @query_parameters;
922 foreach my $key (keys %$where) {
923 $query .= " AND $key LIKE ?";
924 push @query_parameters, "%$where->{$key}%";
926 my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
928 if ( defined $orderby && grep($orderby, @ordervalues)) {
929 $query .= ' ORDER BY '.$orderby;
932 my $sth = $dbh->prepare($query);
933 $sth->execute( @query_parameters );
934 my $items = [];
935 while ( my $row = $sth->fetchrow_hashref ){
936 push @$items, $row;
938 return $items;
941 =head2 GetItemsForInventory
943 $itemlist = GetItemsForInventory($minlocation, $maxlocation,
944 $location, $itemtype $datelastseen, $branch,
945 $offset, $size, $statushash);
947 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
949 The sub returns a reference to a list of hashes, each containing
950 itemnumber, author, title, barcode, item callnumber, and date last
951 seen. It is ordered by callnumber then title.
953 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
954 the datelastseen can be used to specify that you want to see items not seen since a past date only.
955 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
956 $statushash requires a hashref that has the authorized values fieldname (intems.notforloan, etc...) as keys, and an arrayref of statuscodes we are searching for as values.
958 =cut
960 sub GetItemsForInventory {
961 my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
962 my $dbh = C4::Context->dbh;
963 my ( @bind_params, @where_strings );
965 my $query = <<'END_SQL';
966 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
967 FROM items
968 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
969 LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
970 END_SQL
971 if ($statushash){
972 for my $authvfield (keys %$statushash){
973 if ( scalar @{$statushash->{$authvfield}} > 0 ){
974 my $joinedvals = join ',', @{$statushash->{$authvfield}};
975 push @where_strings, "$authvfield in (" . $joinedvals . ")";
980 if ($minlocation) {
981 push @where_strings, 'itemcallnumber >= ?';
982 push @bind_params, $minlocation;
985 if ($maxlocation) {
986 push @where_strings, 'itemcallnumber <= ?';
987 push @bind_params, $maxlocation;
990 if ($datelastseen) {
991 $datelastseen = format_date_in_iso($datelastseen);
992 push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
993 push @bind_params, $datelastseen;
996 if ( $location ) {
997 push @where_strings, 'items.location = ?';
998 push @bind_params, $location;
1001 if ( $branchcode ) {
1002 if($branch eq "homebranch"){
1003 push @where_strings, 'items.homebranch = ?';
1004 }else{
1005 push @where_strings, 'items.holdingbranch = ?';
1007 push @bind_params, $branchcode;
1010 if ( $itemtype ) {
1011 push @where_strings, 'biblioitems.itemtype = ?';
1012 push @bind_params, $itemtype;
1015 if ( $ignoreissued) {
1016 $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1017 push @where_strings, 'issues.date_due IS NULL';
1020 if ( @where_strings ) {
1021 $query .= 'WHERE ';
1022 $query .= join ' AND ', @where_strings;
1024 $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1025 my $sth = $dbh->prepare($query);
1026 $sth->execute( @bind_params );
1028 my @results;
1029 $size--;
1030 while ( my $row = $sth->fetchrow_hashref ) {
1031 $offset-- if ($offset);
1032 $row->{datelastseen}=format_date($row->{datelastseen});
1033 if ( ( !$offset ) && $size ) {
1034 push @results, $row;
1035 $size--;
1038 return \@results;
1041 =head2 GetItemsCount
1043 $count = &GetItemsCount( $biblionumber);
1045 This function return count of item with $biblionumber
1047 =cut
1049 sub GetItemsCount {
1050 my ( $biblionumber ) = @_;
1051 my $dbh = C4::Context->dbh;
1052 my $query = "SELECT count(*)
1053 FROM items
1054 WHERE biblionumber=?";
1055 my $sth = $dbh->prepare($query);
1056 $sth->execute($biblionumber);
1057 my $count = $sth->fetchrow;
1058 return ($count);
1061 =head2 GetItemInfosOf
1063 GetItemInfosOf(@itemnumbers);
1065 =cut
1067 sub GetItemInfosOf {
1068 my @itemnumbers = @_;
1070 my $query = '
1071 SELECT *
1072 FROM items
1073 WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1075 return get_infos_of( $query, 'itemnumber' );
1078 =head2 GetItemsByBiblioitemnumber
1080 GetItemsByBiblioitemnumber($biblioitemnumber);
1082 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1083 Called by C<C4::XISBN>
1085 =cut
1087 sub GetItemsByBiblioitemnumber {
1088 my ( $bibitem ) = @_;
1089 my $dbh = C4::Context->dbh;
1090 my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1091 # Get all items attached to a biblioitem
1092 my $i = 0;
1093 my @results;
1094 $sth->execute($bibitem) || die $sth->errstr;
1095 while ( my $data = $sth->fetchrow_hashref ) {
1096 # Foreach item, get circulation information
1097 my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1098 WHERE itemnumber = ?
1099 AND issues.borrowernumber = borrowers.borrowernumber"
1101 $sth2->execute( $data->{'itemnumber'} );
1102 if ( my $data2 = $sth2->fetchrow_hashref ) {
1103 # if item is out, set the due date and who it is out too
1104 $data->{'date_due'} = $data2->{'date_due'};
1105 $data->{'cardnumber'} = $data2->{'cardnumber'};
1106 $data->{'borrowernumber'} = $data2->{'borrowernumber'};
1108 else {
1109 # set date_due to blank, so in the template we check itemlost, and wthdrawn
1110 $data->{'date_due'} = '';
1111 } # else
1112 # Find the last 3 people who borrowed this item.
1113 my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1114 AND old_issues.borrowernumber = borrowers.borrowernumber
1115 ORDER BY returndate desc,timestamp desc LIMIT 3";
1116 $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1117 $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1118 my $i2 = 0;
1119 while ( my $data2 = $sth2->fetchrow_hashref ) {
1120 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1121 $data->{"card$i2"} = $data2->{'cardnumber'};
1122 $data->{"borrower$i2"} = $data2->{'borrowernumber'};
1123 $i2++;
1125 push(@results,$data);
1127 return (\@results);
1130 =head2 GetItemsInfo
1132 @results = GetItemsInfo($biblionumber);
1134 Returns information about items with the given biblionumber.
1136 C<GetItemsInfo> returns a list of references-to-hash. Each element
1137 contains a number of keys. Most of them are attributes from the
1138 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1139 Koha database. Other keys include:
1141 =over 2
1143 =item C<$data-E<gt>{branchname}>
1145 The name (not the code) of the branch to which the book belongs.
1147 =item C<$data-E<gt>{datelastseen}>
1149 This is simply C<items.datelastseen>, except that while the date is
1150 stored in YYYY-MM-DD format in the database, here it is converted to
1151 DD/MM/YYYY format. A NULL date is returned as C<//>.
1153 =item C<$data-E<gt>{datedue}>
1155 =item C<$data-E<gt>{class}>
1157 This is the concatenation of C<biblioitems.classification>, the book's
1158 Dewey code, and C<biblioitems.subclass>.
1160 =item C<$data-E<gt>{ocount}>
1162 I think this is the number of copies of the book available.
1164 =item C<$data-E<gt>{order}>
1166 If this is set, it is set to C<One Order>.
1168 =back
1170 =cut
1172 sub GetItemsInfo {
1173 my ( $biblionumber ) = @_;
1174 my $dbh = C4::Context->dbh;
1175 # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1176 my $query = "
1177 SELECT items.*,
1178 biblio.*,
1179 biblioitems.volume,
1180 biblioitems.number,
1181 biblioitems.itemtype,
1182 biblioitems.isbn,
1183 biblioitems.issn,
1184 biblioitems.publicationyear,
1185 biblioitems.publishercode,
1186 biblioitems.volumedate,
1187 biblioitems.volumedesc,
1188 biblioitems.lccn,
1189 biblioitems.url,
1190 items.notforloan as itemnotforloan,
1191 itemtypes.description,
1192 itemtypes.notforloan as notforloan_per_itemtype,
1193 holding.branchurl,
1194 holding.branchname,
1195 holding.opac_info as branch_opac_info
1196 FROM items
1197 LEFT JOIN branches AS holding ON items.holdingbranch = holding.branchcode
1198 LEFT JOIN branches AS home ON items.homebranch=home.branchcode
1199 LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1200 LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1201 LEFT JOIN itemtypes ON itemtypes.itemtype = "
1202 . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1203 $query .= " WHERE items.biblionumber = ? ORDER BY home.branchname,items.dateaccessioned desc" ;
1204 my $sth = $dbh->prepare($query);
1205 $sth->execute($biblionumber);
1206 my $i = 0;
1207 my @results;
1208 my $serial;
1210 my $isth = $dbh->prepare(
1211 "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1212 FROM issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1213 WHERE itemnumber = ?"
1215 my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? ");
1216 while ( my $data = $sth->fetchrow_hashref ) {
1217 my $datedue = '';
1218 $isth->execute( $data->{'itemnumber'} );
1219 if ( my $idata = $isth->fetchrow_hashref ) {
1220 $data->{borrowernumber} = $idata->{borrowernumber};
1221 $data->{cardnumber} = $idata->{cardnumber};
1222 $data->{surname} = $idata->{surname};
1223 $data->{firstname} = $idata->{firstname};
1224 $data->{lastreneweddate} = $idata->{lastreneweddate};
1225 $datedue = $idata->{'date_due'};
1226 if (C4::Context->preference("IndependantBranches")){
1227 my $userenv = C4::Context->userenv;
1228 if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) {
1229 $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1233 if ( $data->{'serial'}) {
1234 $ssth->execute($data->{'itemnumber'}) ;
1235 ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1236 $serial = 1;
1238 #get branch information.....
1239 my $bsth = $dbh->prepare(
1240 "SELECT * FROM branches WHERE branchcode = ?
1243 $bsth->execute( $data->{'holdingbranch'} );
1244 if ( my $bdata = $bsth->fetchrow_hashref ) {
1245 $data->{'branchname'} = $bdata->{'branchname'};
1247 $data->{'datedue'} = $datedue;
1249 # get notforloan complete status if applicable
1250 my $sthnflstatus = $dbh->prepare(
1251 'SELECT authorised_value
1252 FROM marc_subfield_structure
1253 WHERE kohafield="items.notforloan"
1257 $sthnflstatus->execute;
1258 my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1259 if ($authorised_valuecode) {
1260 $sthnflstatus = $dbh->prepare(
1261 "SELECT lib FROM authorised_values
1262 WHERE category=?
1263 AND authorised_value=?"
1265 $sthnflstatus->execute( $authorised_valuecode,
1266 $data->{itemnotforloan} );
1267 my ($lib) = $sthnflstatus->fetchrow;
1268 $data->{notforloanvalue} = $lib;
1271 # get restricted status and description if applicable
1272 my $restrictedstatus = $dbh->prepare(
1273 'SELECT authorised_value
1274 FROM marc_subfield_structure
1275 WHERE kohafield="items.restricted"
1279 $restrictedstatus->execute;
1280 ($authorised_valuecode) = $restrictedstatus->fetchrow;
1281 if ($authorised_valuecode) {
1282 $restrictedstatus = $dbh->prepare(
1283 "SELECT lib,lib_opac FROM authorised_values
1284 WHERE category=?
1285 AND authorised_value=?"
1287 $restrictedstatus->execute( $authorised_valuecode,
1288 $data->{restricted} );
1290 if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1291 $data->{restricted} = $rstdata->{'lib'};
1292 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1296 # my stack procedures
1297 my $stackstatus = $dbh->prepare(
1298 'SELECT authorised_value
1299 FROM marc_subfield_structure
1300 WHERE kohafield="items.stack"
1303 $stackstatus->execute;
1305 ($authorised_valuecode) = $stackstatus->fetchrow;
1306 if ($authorised_valuecode) {
1307 $stackstatus = $dbh->prepare(
1308 "SELECT lib
1309 FROM authorised_values
1310 WHERE category=?
1311 AND authorised_value=?
1314 $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1315 my ($lib) = $stackstatus->fetchrow;
1316 $data->{stack} = $lib;
1318 # Find the last 3 people who borrowed this item.
1319 my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1320 WHERE itemnumber = ?
1321 AND old_issues.borrowernumber = borrowers.borrowernumber
1322 ORDER BY returndate DESC
1323 LIMIT 3");
1324 $sth2->execute($data->{'itemnumber'});
1325 my $ii = 0;
1326 while (my $data2 = $sth2->fetchrow_hashref()) {
1327 $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1328 $data->{"card$ii"} = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1329 $data->{"borrower$ii"} = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1330 $ii++;
1333 $results[$i] = $data;
1334 $i++;
1336 if($serial) {
1337 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1338 } else {
1339 return (@results);
1343 =head2 GetItemsLocationInfo
1345 my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1347 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1349 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1351 =over 2
1353 =item C<$data-E<gt>{homebranch}>
1355 Branch Name of the item's homebranch
1357 =item C<$data-E<gt>{holdingbranch}>
1359 Branch Name of the item's holdingbranch
1361 =item C<$data-E<gt>{location}>
1363 Item's shelving location code
1365 =item C<$data-E<gt>{location_intranet}>
1367 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1369 =item C<$data-E<gt>{location_opac}>
1371 The OPAC description for the Shelving Location as set in authorised_values 'LOC'. Falls back to intranet description if no OPAC
1372 description is set.
1374 =item C<$data-E<gt>{itemcallnumber}>
1376 Item's itemcallnumber
1378 =item C<$data-E<gt>{cn_sort}>
1380 Item's call number normalized for sorting
1382 =back
1384 =cut
1386 sub GetItemsLocationInfo {
1387 my $biblionumber = shift;
1388 my @results;
1390 my $dbh = C4::Context->dbh;
1391 my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch,
1392 location, itemcallnumber, cn_sort
1393 FROM items, branches as a, branches as b
1394 WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode
1395 AND biblionumber = ?
1396 ORDER BY cn_sort ASC";
1397 my $sth = $dbh->prepare($query);
1398 $sth->execute($biblionumber);
1400 while ( my $data = $sth->fetchrow_hashref ) {
1401 $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1402 $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1403 push @results, $data;
1405 return @results;
1408 =head2 GetHostItemsInfo
1410 $hostiteminfo = GetHostItemsInfo($hostfield);
1411 Returns the iteminfo for items linked to records via a host field
1413 =cut
1415 sub GetHostItemsInfo {
1416 my ($record) = @_;
1417 my @returnitemsInfo;
1419 if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1420 C4::Context->preference('marcflavour') eq 'NORMARC'){
1421 foreach my $hostfield ( $record->field('773') ) {
1422 my $hostbiblionumber = $hostfield->subfield("0");
1423 my $linkeditemnumber = $hostfield->subfield("9");
1424 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1425 foreach my $hostitemInfo (@hostitemInfos){
1426 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1427 push (@returnitemsInfo,$hostitemInfo);
1428 last;
1432 } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1433 foreach my $hostfield ( $record->field('461') ) {
1434 my $hostbiblionumber = $hostfield->subfield("0");
1435 my $linkeditemnumber = $hostfield->subfield("9");
1436 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1437 foreach my $hostitemInfo (@hostitemInfos){
1438 if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1439 push (@returnitemsInfo,$hostitemInfo);
1440 last;
1445 return @returnitemsInfo;
1449 =head2 GetLastAcquisitions
1451 my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'),
1452 'itemtypes' => ('BK','BD')}, 10);
1454 =cut
1456 sub GetLastAcquisitions {
1457 my ($data,$max) = @_;
1459 my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1461 my $number_of_branches = @{$data->{branches}};
1462 my $number_of_itemtypes = @{$data->{itemtypes}};
1465 my @where = ('WHERE 1 ');
1466 $number_of_branches and push @where
1467 , 'AND holdingbranch IN ('
1468 , join(',', ('?') x $number_of_branches )
1469 , ')'
1472 $number_of_itemtypes and push @where
1473 , "AND $itemtype IN ("
1474 , join(',', ('?') x $number_of_itemtypes )
1475 , ')'
1478 my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1479 FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber)
1480 RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1481 @where
1482 GROUP BY biblio.biblionumber
1483 ORDER BY dateaccessioned DESC LIMIT $max";
1485 my $dbh = C4::Context->dbh;
1486 my $sth = $dbh->prepare($query);
1488 $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1490 my @results;
1491 while( my $row = $sth->fetchrow_hashref){
1492 push @results, {date => $row->{dateaccessioned}
1493 , biblionumber => $row->{biblionumber}
1494 , title => $row->{title}};
1497 return @results;
1500 =head2 GetItemnumbersForBiblio
1502 my $itemnumbers = GetItemnumbersForBiblio($biblionumber);
1504 Given a single biblionumber, return an arrayref of all the corresponding itemnumbers
1506 =cut
1508 sub GetItemnumbersForBiblio {
1509 my $biblionumber = shift;
1510 my @items;
1511 my $dbh = C4::Context->dbh;
1512 my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1513 $sth->execute($biblionumber);
1514 while (my $result = $sth->fetchrow_hashref) {
1515 push @items, $result->{'itemnumber'};
1517 return \@items;
1520 =head2 get_itemnumbers_of
1522 my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1524 Given a list of biblionumbers, return the list of corresponding itemnumbers
1525 for each biblionumber.
1527 Return a reference on a hash where keys are biblionumbers and values are
1528 references on array of itemnumbers.
1530 =cut
1532 sub get_itemnumbers_of {
1533 my @biblionumbers = @_;
1535 my $dbh = C4::Context->dbh;
1537 my $query = '
1538 SELECT itemnumber,
1539 biblionumber
1540 FROM items
1541 WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1543 my $sth = $dbh->prepare($query);
1544 $sth->execute(@biblionumbers);
1546 my %itemnumbers_of;
1548 while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1549 push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1552 return \%itemnumbers_of;
1555 =head2 get_hostitemnumbers_of
1557 my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1559 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1561 Return a reference on a hash where key is a biblionumber and values are
1562 references on array of itemnumbers.
1564 =cut
1567 sub get_hostitemnumbers_of {
1568 my ($biblionumber) = @_;
1569 my $marcrecord = GetMarcBiblio($biblionumber);
1570 my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1572 my $marcflavor = C4::Context->preference('marcflavour');
1573 if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1574 $tag='773';
1575 $biblio_s='0';
1576 $item_s='9';
1577 } elsif ($marcflavor eq 'UNIMARC') {
1578 $tag='461';
1579 $biblio_s='0';
1580 $item_s='9';
1583 foreach my $hostfield ( $marcrecord->field($tag) ) {
1584 my $hostbiblionumber = $hostfield->subfield($biblio_s);
1585 my $linkeditemnumber = $hostfield->subfield($item_s);
1586 my @itemnumbers;
1587 if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1589 @itemnumbers = @$itemnumbers;
1591 foreach my $itemnumber (@itemnumbers){
1592 if ($itemnumber eq $linkeditemnumber){
1593 push (@returnhostitemnumbers,$itemnumber);
1594 last;
1598 return @returnhostitemnumbers;
1602 =head2 GetItemnumberFromBarcode
1604 $result = GetItemnumberFromBarcode($barcode);
1606 =cut
1608 sub GetItemnumberFromBarcode {
1609 my ($barcode) = @_;
1610 my $dbh = C4::Context->dbh;
1612 my $rq =
1613 $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1614 $rq->execute($barcode);
1615 my ($result) = $rq->fetchrow;
1616 return ($result);
1619 =head2 GetBarcodeFromItemnumber
1621 $result = GetBarcodeFromItemnumber($itemnumber);
1623 =cut
1625 sub GetBarcodeFromItemnumber {
1626 my ($itemnumber) = @_;
1627 my $dbh = C4::Context->dbh;
1629 my $rq =
1630 $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1631 $rq->execute($itemnumber);
1632 my ($result) = $rq->fetchrow;
1633 return ($result);
1636 =head2 GetHiddenItemnumbers
1638 =over 4
1640 $result = GetHiddenItemnumbers(@items);
1642 =back
1644 =cut
1646 sub GetHiddenItemnumbers {
1647 my (@items) = @_;
1648 my @resultitems;
1650 my $yaml = C4::Context->preference('OpacHiddenItems');
1651 $yaml = "$yaml\n\n"; # YAML is anal on ending \n. Surplus does not hurt
1652 my $hidingrules;
1653 eval {
1654 $hidingrules = YAML::Load($yaml);
1656 if ($@) {
1657 warn "Unable to parse OpacHiddenItems syspref : $@";
1658 return ();
1660 my $dbh = C4::Context->dbh;
1662 # For each item
1663 foreach my $item (@items) {
1665 # We check each rule
1666 foreach my $field (keys %$hidingrules) {
1667 my $val;
1668 if (exists $item->{$field}) {
1669 $val = $item->{$field};
1671 else {
1672 my $query = "SELECT $field from items where itemnumber = ?";
1673 $val = $dbh->selectrow_array($query, undef, $item->{'itemnumber'});
1675 $val = '' unless defined $val;
1677 # If the results matches the values in the yaml file
1678 if (any { $val eq $_ } @{$hidingrules->{$field}}) {
1680 # We add the itemnumber to the list
1681 push @resultitems, $item->{'itemnumber'};
1683 # If at least one rule matched for an item, no need to test the others
1684 last;
1688 return @resultitems;
1691 =head3 get_item_authorised_values
1693 find the types and values for all authorised values assigned to this item.
1695 parameters: itemnumber
1697 returns: a hashref malling the authorised value to the value set for this itemnumber
1699 $authorised_values = {
1700 'CCODE' => undef,
1701 'DAMAGED' => '0',
1702 'LOC' => '3',
1703 'LOST' => '0'
1704 'NOT_LOAN' => '0',
1705 'RESTRICTED' => undef,
1706 'STACK' => undef,
1707 'WITHDRAWN' => '0',
1708 'branches' => 'CPL',
1709 'cn_source' => undef,
1710 'itemtypes' => 'SER',
1713 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1715 =cut
1717 sub get_item_authorised_values {
1718 my $itemnumber = shift;
1720 # assume that these entries in the authorised_value table are item level.
1721 my $query = q(SELECT distinct authorised_value, kohafield
1722 FROM marc_subfield_structure
1723 WHERE kohafield like 'item%'
1724 AND authorised_value != '' );
1726 my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1727 my $iteminfo = GetItem( $itemnumber );
1728 # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1729 my $return;
1730 foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1731 my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1732 $field =~ s/^items\.//;
1733 if ( exists $iteminfo->{ $field } ) {
1734 $return->{ $this_authorised_value } = $iteminfo->{ $field };
1737 # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1738 return $return;
1741 =head3 get_authorised_value_images
1743 find a list of icons that are appropriate for display based on the
1744 authorised values for a biblio.
1746 parameters: listref of authorised values, such as comes from
1747 get_item_authorised_values or
1748 from C4::Biblio::get_biblio_authorised_values
1750 returns: listref of hashrefs for each image. Each hashref looks like this:
1752 { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1753 label => '',
1754 category => '',
1755 value => '', }
1757 Notes: Currently, I put on the full path to the images on the staff
1758 side. This should either be configurable or not done at all. Since I
1759 have to deal with 'intranet' or 'opac' in
1760 get_biblio_authorised_values, perhaps I should be passing it in.
1762 =cut
1764 sub get_authorised_value_images {
1765 my $authorised_values = shift;
1767 my @imagelist;
1769 my $authorised_value_list = GetAuthorisedValues();
1770 # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1771 foreach my $this_authorised_value ( @$authorised_value_list ) {
1772 if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1773 && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1774 # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1775 if ( defined $this_authorised_value->{'imageurl'} ) {
1776 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1777 label => $this_authorised_value->{'lib'},
1778 category => $this_authorised_value->{'category'},
1779 value => $this_authorised_value->{'authorised_value'}, };
1784 # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1785 return \@imagelist;
1789 =head1 LIMITED USE FUNCTIONS
1791 The following functions, while part of the public API,
1792 are not exported. This is generally because they are
1793 meant to be used by only one script for a specific
1794 purpose, and should not be used in any other context
1795 without careful thought.
1797 =cut
1799 =head2 GetMarcItem
1801 my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1803 Returns MARC::Record of the item passed in parameter.
1804 This function is meant for use only in C<cataloguing/additem.pl>,
1805 where it is needed to support that script's MARC-like
1806 editor.
1808 =cut
1810 sub GetMarcItem {
1811 my ( $biblionumber, $itemnumber ) = @_;
1813 # GetMarcItem has been revised so that it does the following:
1814 # 1. Gets the item information from the items table.
1815 # 2. Converts it to a MARC field for storage in the bib record.
1817 # The previous behavior was:
1818 # 1. Get the bib record.
1819 # 2. Return the MARC tag corresponding to the item record.
1821 # The difference is that one treats the items row as authoritative,
1822 # while the other treats the MARC representation as authoritative
1823 # under certain circumstances.
1825 my $itemrecord = GetItem($itemnumber);
1827 # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1828 # Also, don't emit a subfield if the underlying field is blank.
1831 return Item2Marc($itemrecord,$biblionumber);
1834 sub Item2Marc {
1835 my ($itemrecord,$biblionumber)=@_;
1836 my $mungeditem = {
1837 map {
1838 defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()
1839 } keys %{ $itemrecord }
1841 my $itemmarc = TransformKohaToMarc($mungeditem);
1842 my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1844 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1845 if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1846 foreach my $field ($itemmarc->field($itemtag)){
1847 $field->add_subfields(@$unlinked_item_subfields);
1850 return $itemmarc;
1853 =head1 PRIVATE FUNCTIONS AND VARIABLES
1855 The following functions are not meant to be called
1856 directly, but are documented in order to explain
1857 the inner workings of C<C4::Items>.
1859 =cut
1861 =head2 %derived_columns
1863 This hash keeps track of item columns that
1864 are strictly derived from other columns in
1865 the item record and are not meant to be set
1866 independently.
1868 Each key in the hash should be the name of a
1869 column (as named by TransformMarcToKoha). Each
1870 value should be hashref whose keys are the
1871 columns on which the derived column depends. The
1872 hashref should also contain a 'BUILDER' key
1873 that is a reference to a sub that calculates
1874 the derived value.
1876 =cut
1878 my %derived_columns = (
1879 'items.cn_sort' => {
1880 'itemcallnumber' => 1,
1881 'items.cn_source' => 1,
1882 'BUILDER' => \&_calc_items_cn_sort,
1886 =head2 _set_derived_columns_for_add
1888 _set_derived_column_for_add($item);
1890 Given an item hash representing a new item to be added,
1891 calculate any derived columns. Currently the only
1892 such column is C<items.cn_sort>.
1894 =cut
1896 sub _set_derived_columns_for_add {
1897 my $item = shift;
1899 foreach my $column (keys %derived_columns) {
1900 my $builder = $derived_columns{$column}->{'BUILDER'};
1901 my $source_values = {};
1902 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1903 next if $source_column eq 'BUILDER';
1904 $source_values->{$source_column} = $item->{$source_column};
1906 $builder->($item, $source_values);
1910 =head2 _set_derived_columns_for_mod
1912 _set_derived_column_for_mod($item);
1914 Given an item hash representing a new item to be modified.
1915 calculate any derived columns. Currently the only
1916 such column is C<items.cn_sort>.
1918 This routine differs from C<_set_derived_columns_for_add>
1919 in that it needs to handle partial item records. In other
1920 words, the caller of C<ModItem> may have supplied only one
1921 or two columns to be changed, so this function needs to
1922 determine whether any of the columns to be changed affect
1923 any of the derived columns. Also, if a derived column
1924 depends on more than one column, but the caller is not
1925 changing all of then, this routine retrieves the unchanged
1926 values from the database in order to ensure a correct
1927 calculation.
1929 =cut
1931 sub _set_derived_columns_for_mod {
1932 my $item = shift;
1934 foreach my $column (keys %derived_columns) {
1935 my $builder = $derived_columns{$column}->{'BUILDER'};
1936 my $source_values = {};
1937 my %missing_sources = ();
1938 my $must_recalc = 0;
1939 foreach my $source_column (keys %{ $derived_columns{$column} }) {
1940 next if $source_column eq 'BUILDER';
1941 if (exists $item->{$source_column}) {
1942 $must_recalc = 1;
1943 $source_values->{$source_column} = $item->{$source_column};
1944 } else {
1945 $missing_sources{$source_column} = 1;
1948 if ($must_recalc) {
1949 foreach my $source_column (keys %missing_sources) {
1950 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1952 $builder->($item, $source_values);
1957 =head2 _do_column_fixes_for_mod
1959 _do_column_fixes_for_mod($item);
1961 Given an item hashref containing one or more
1962 columns to modify, fix up certain values.
1963 Specifically, set to 0 any passed value
1964 of C<notforloan>, C<damaged>, C<itemlost>, or
1965 C<wthdrawn> that is either undefined or
1966 contains the empty string.
1968 =cut
1970 sub _do_column_fixes_for_mod {
1971 my $item = shift;
1973 if (exists $item->{'notforloan'} and
1974 (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1975 $item->{'notforloan'} = 0;
1977 if (exists $item->{'damaged'} and
1978 (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1979 $item->{'damaged'} = 0;
1981 if (exists $item->{'itemlost'} and
1982 (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1983 $item->{'itemlost'} = 0;
1985 if (exists $item->{'wthdrawn'} and
1986 (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1987 $item->{'wthdrawn'} = 0;
1989 if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1990 $item->{'permanent_location'} = $item->{'location'};
1992 if (exists $item->{'timestamp'}) {
1993 delete $item->{'timestamp'};
1997 =head2 _get_single_item_column
1999 _get_single_item_column($column, $itemnumber);
2001 Retrieves the value of a single column from an C<items>
2002 row specified by C<$itemnumber>.
2004 =cut
2006 sub _get_single_item_column {
2007 my $column = shift;
2008 my $itemnumber = shift;
2010 my $dbh = C4::Context->dbh;
2011 my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
2012 $sth->execute($itemnumber);
2013 my ($value) = $sth->fetchrow();
2014 return $value;
2017 =head2 _calc_items_cn_sort
2019 _calc_items_cn_sort($item, $source_values);
2021 Helper routine to calculate C<items.cn_sort>.
2023 =cut
2025 sub _calc_items_cn_sort {
2026 my $item = shift;
2027 my $source_values = shift;
2029 $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2032 =head2 _set_defaults_for_add
2034 _set_defaults_for_add($item_hash);
2036 Given an item hash representing an item to be added, set
2037 correct default values for columns whose default value
2038 is not handled by the DBMS. This includes the following
2039 columns:
2041 =over 2
2043 =item *
2045 C<items.dateaccessioned>
2047 =item *
2049 C<items.notforloan>
2051 =item *
2053 C<items.damaged>
2055 =item *
2057 C<items.itemlost>
2059 =item *
2061 C<items.wthdrawn>
2063 =back
2065 =cut
2067 sub _set_defaults_for_add {
2068 my $item = shift;
2069 $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2070 $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
2073 =head2 _koha_new_item
2075 my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2077 Perform the actual insert into the C<items> table.
2079 =cut
2081 sub _koha_new_item {
2082 my ( $item, $barcode ) = @_;
2083 my $dbh=C4::Context->dbh;
2084 my $error;
2085 my $query =
2086 "INSERT INTO items SET
2087 biblionumber = ?,
2088 biblioitemnumber = ?,
2089 barcode = ?,
2090 dateaccessioned = ?,
2091 booksellerid = ?,
2092 homebranch = ?,
2093 price = ?,
2094 replacementprice = ?,
2095 replacementpricedate = ?,
2096 datelastborrowed = ?,
2097 datelastseen = ?,
2098 stack = ?,
2099 notforloan = ?,
2100 damaged = ?,
2101 itemlost = ?,
2102 wthdrawn = ?,
2103 itemcallnumber = ?,
2104 restricted = ?,
2105 itemnotes = ?,
2106 holdingbranch = ?,
2107 paidfor = ?,
2108 location = ?,
2109 permanent_location = ?,
2110 onloan = ?,
2111 issues = ?,
2112 renewals = ?,
2113 reserves = ?,
2114 cn_source = ?,
2115 cn_sort = ?,
2116 ccode = ?,
2117 itype = ?,
2118 materials = ?,
2119 uri = ?,
2120 enumchron = ?,
2121 more_subfields_xml = ?,
2122 copynumber = ?,
2123 stocknumber = ?
2125 my $sth = $dbh->prepare($query);
2126 my $today = C4::Dates->today('iso');
2127 $sth->execute(
2128 $item->{'biblionumber'},
2129 $item->{'biblioitemnumber'},
2130 $barcode,
2131 $item->{'dateaccessioned'},
2132 $item->{'booksellerid'},
2133 $item->{'homebranch'},
2134 $item->{'price'},
2135 $item->{'replacementprice'},
2136 $item->{'replacementpricedate'} || $today,
2137 $item->{datelastborrowed},
2138 $item->{datelastseen} || $today,
2139 $item->{stack},
2140 $item->{'notforloan'},
2141 $item->{'damaged'},
2142 $item->{'itemlost'},
2143 $item->{'wthdrawn'},
2144 $item->{'itemcallnumber'},
2145 $item->{'restricted'},
2146 $item->{'itemnotes'},
2147 $item->{'holdingbranch'},
2148 $item->{'paidfor'},
2149 $item->{'location'},
2150 $item->{'permanent_location'},
2151 $item->{'onloan'},
2152 $item->{'issues'},
2153 $item->{'renewals'},
2154 $item->{'reserves'},
2155 $item->{'items.cn_source'},
2156 $item->{'items.cn_sort'},
2157 $item->{'ccode'},
2158 $item->{'itype'},
2159 $item->{'materials'},
2160 $item->{'uri'},
2161 $item->{'enumchron'},
2162 $item->{'more_subfields_xml'},
2163 $item->{'copynumber'},
2164 $item->{'stocknumber'},
2167 my $itemnumber;
2168 if ( defined $sth->errstr ) {
2169 $error.="ERROR in _koha_new_item $query".$sth->errstr;
2171 else {
2172 $itemnumber = $dbh->{'mysql_insertid'};
2175 return ( $itemnumber, $error );
2178 =head2 MoveItemFromBiblio
2180 MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2182 Moves an item from a biblio to another
2184 Returns undef if the move failed or the biblionumber of the destination record otherwise
2186 =cut
2188 sub MoveItemFromBiblio {
2189 my ($itemnumber, $frombiblio, $tobiblio) = @_;
2190 my $dbh = C4::Context->dbh;
2191 my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2192 $sth->execute( $tobiblio );
2193 my ( $tobiblioitem ) = $sth->fetchrow();
2194 $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2195 my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2196 if ($return == 1) {
2197 ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2198 ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2199 # Checking if the item we want to move is in an order
2200 require C4::Acquisition;
2201 my $order = C4::Acquisition::GetOrderFromItemnumber($itemnumber);
2202 if ($order) {
2203 # Replacing the biblionumber within the order if necessary
2204 $order->{'biblionumber'} = $tobiblio;
2205 C4::Acquisition::ModOrder($order);
2207 return $tobiblio;
2209 return;
2212 =head2 DelItemCheck
2214 DelItemCheck($dbh, $biblionumber, $itemnumber);
2216 Exported function (core API) for deleting an item record in Koha if there no current issue.
2218 =cut
2220 sub DelItemCheck {
2221 my ( $dbh, $biblionumber, $itemnumber ) = @_;
2222 my $error;
2224 my $countanalytics=GetAnalyticsCount($itemnumber);
2227 # check that there is no issue on this item before deletion.
2228 my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2229 $sth->execute($itemnumber);
2231 my $item = GetItem($itemnumber);
2232 my $onloan=$sth->fetchrow;
2234 if ($onloan){
2235 $error = "book_on_loan"
2237 elsif ( !(C4::Context->userenv->{flags} & 1) and
2238 C4::Context->preference("IndependantBranches") and
2239 (C4::Context->userenv->{branch} ne
2240 $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
2242 $error = "not_same_branch";
2244 else{
2245 # check it doesnt have a waiting reserve
2246 $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2247 $sth->execute($itemnumber);
2248 my $reserve=$sth->fetchrow;
2249 if ($reserve){
2250 $error = "book_reserved";
2251 } elsif ($countanalytics > 0){
2252 $error = "linked_analytics";
2253 } else {
2254 DelItem($dbh, $biblionumber, $itemnumber);
2255 return 1;
2258 return $error;
2261 =head2 _koha_modify_item
2263 my ($itemnumber,$error) =_koha_modify_item( $item );
2265 Perform the actual update of the C<items> row. Note that this
2266 routine accepts a hashref specifying the columns to update.
2268 =cut
2270 sub _koha_modify_item {
2271 my ( $item ) = @_;
2272 my $dbh=C4::Context->dbh;
2273 my $error;
2275 my $query = "UPDATE items SET ";
2276 my @bind;
2277 for my $key ( keys %$item ) {
2278 $query.="$key=?,";
2279 push @bind, $item->{$key};
2281 $query =~ s/,$//;
2282 $query .= " WHERE itemnumber=?";
2283 push @bind, $item->{'itemnumber'};
2284 my $sth = C4::Context->dbh->prepare($query);
2285 $sth->execute(@bind);
2286 if ( C4::Context->dbh->errstr ) {
2287 $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2288 warn $error;
2290 return ($item->{'itemnumber'},$error);
2293 =head2 _koha_delete_item
2295 _koha_delete_item( $dbh, $itemnum );
2297 Internal function to delete an item record from the koha tables
2299 =cut
2301 sub _koha_delete_item {
2302 my ( $dbh, $itemnum ) = @_;
2304 # save the deleted item to deleteditems table
2305 my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2306 $sth->execute($itemnum);
2307 my $data = $sth->fetchrow_hashref();
2308 my $query = "INSERT INTO deleteditems SET ";
2309 my @bind = ();
2310 foreach my $key ( keys %$data ) {
2311 $query .= "$key = ?,";
2312 push( @bind, $data->{$key} );
2314 $query =~ s/\,$//;
2315 $sth = $dbh->prepare($query);
2316 $sth->execute(@bind);
2318 # delete from items table
2319 $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2320 $sth->execute($itemnum);
2321 return undef;
2324 =head2 _marc_from_item_hash
2326 my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2328 Given an item hash representing a complete item record,
2329 create a C<MARC::Record> object containing an embedded
2330 tag representing that item.
2332 The third, optional parameter C<$unlinked_item_subfields> is
2333 an arrayref of subfields (not mapped to C<items> fields per the
2334 framework) to be added to the MARC representation
2335 of the item.
2337 =cut
2339 sub _marc_from_item_hash {
2340 my $item = shift;
2341 my $frameworkcode = shift;
2342 my $unlinked_item_subfields;
2343 if (@_) {
2344 $unlinked_item_subfields = shift;
2347 # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2348 # Also, don't emit a subfield if the underlying field is blank.
2349 my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ?
2350 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_}))
2351 : () } keys %{ $item } };
2353 my $item_marc = MARC::Record->new();
2354 foreach my $item_field ( keys %{$mungeditem} ) {
2355 my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2356 next unless defined $tag and defined $subfield; # skip if not mapped to MARC field
2357 my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2358 foreach my $value (@values){
2359 if ( my $field = $item_marc->field($tag) ) {
2360 $field->add_subfields( $subfield => $value );
2361 } else {
2362 my $add_subfields = [];
2363 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2364 $add_subfields = $unlinked_item_subfields;
2366 $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2371 return $item_marc;
2374 =head2 _repack_item_errors
2376 Add an error message hash generated by C<CheckItemPreSave>
2377 to a list of errors.
2379 =cut
2381 sub _repack_item_errors {
2382 my $item_sequence_num = shift;
2383 my $item_ref = shift;
2384 my $error_ref = shift;
2386 my @repacked_errors = ();
2388 foreach my $error_code (sort keys %{ $error_ref }) {
2389 my $repacked_error = {};
2390 $repacked_error->{'item_sequence'} = $item_sequence_num;
2391 $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2392 $repacked_error->{'error_code'} = $error_code;
2393 $repacked_error->{'error_information'} = $error_ref->{$error_code};
2394 push @repacked_errors, $repacked_error;
2397 return @repacked_errors;
2400 =head2 _get_unlinked_item_subfields
2402 my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2404 =cut
2406 sub _get_unlinked_item_subfields {
2407 my $original_item_marc = shift;
2408 my $frameworkcode = shift;
2410 my $marcstructure = GetMarcStructure(1, $frameworkcode);
2412 # assume that this record has only one field, and that that
2413 # field contains only the item information
2414 my $subfields = [];
2415 my @fields = $original_item_marc->fields();
2416 if ($#fields > -1) {
2417 my $field = $fields[0];
2418 my $tag = $field->tag();
2419 foreach my $subfield ($field->subfields()) {
2420 if (defined $subfield->[1] and
2421 $subfield->[1] ne '' and
2422 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2423 push @$subfields, $subfield->[0] => $subfield->[1];
2427 return $subfields;
2430 =head2 _get_unlinked_subfields_xml
2432 my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2434 =cut
2436 sub _get_unlinked_subfields_xml {
2437 my $unlinked_item_subfields = shift;
2439 my $xml;
2440 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2441 my $marc = MARC::Record->new();
2442 # use of tag 999 is arbitrary, and doesn't need to match the item tag
2443 # used in the framework
2444 $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2445 $marc->encoding("UTF-8");
2446 $xml = $marc->as_xml("USMARC");
2449 return $xml;
2452 =head2 _parse_unlinked_item_subfields_from_xml
2454 my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2456 =cut
2458 sub _parse_unlinked_item_subfields_from_xml {
2459 my $xml = shift;
2460 require C4::Charset;
2461 return unless defined $xml and $xml ne "";
2462 my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8');
2463 my $unlinked_subfields = [];
2464 my @fields = $marc->fields();
2465 if ($#fields > -1) {
2466 foreach my $subfield ($fields[0]->subfields()) {
2467 push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2470 return $unlinked_subfields;
2473 =head2 GetAnalyticsCount
2475 $count= &GetAnalyticsCount($itemnumber)
2477 counts Usage of itemnumber in Analytical bibliorecords.
2479 =cut
2481 sub GetAnalyticsCount {
2482 my ($itemnumber) = @_;
2483 if (C4::Context->preference('NoZebra')) {
2484 # Read the index Koha-Auth-Number for this authid and count the lines
2485 my $result = C4::Search::NZanalyse("hi=$itemnumber");
2486 my @tab = split /;/,$result;
2487 return scalar @tab;
2488 } else {
2489 ### ZOOM search here
2490 my $query;
2491 $query= "hi=".$itemnumber;
2492 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2493 return ($result);
2497 =head2 GetItemHolds
2499 =over 4
2500 $holds = &GetItemHolds($biblionumber, $itemnumber);
2502 =back
2504 This function return the count of holds with $biblionumber and $itemnumber
2506 =cut
2508 sub GetItemHolds {
2509 my ($biblionumber, $itemnumber) = @_;
2510 my $holds;
2511 my $dbh = C4::Context->dbh;
2512 my $query = "SELECT count(*)
2513 FROM reserves
2514 WHERE biblionumber=? AND itemnumber=?";
2515 my $sth = $dbh->prepare($query);
2516 $sth->execute($biblionumber, $itemnumber);
2517 $holds = $sth->fetchrow;
2518 return $holds;
2520 =head1 OTHER FUNCTIONS
2522 =head2 _find_value
2524 ($indicators, $value) = _find_value($tag, $subfield, $record,$encoding);
2526 Find the given $subfield in the given $tag in the given
2527 MARC::Record $record. If the subfield is found, returns
2528 the (indicators, value) pair; otherwise, (undef, undef) is
2529 returned.
2531 PROPOSITION :
2532 Such a function is used in addbiblio AND additem and serial-edit and maybe could be used in Authorities.
2533 I suggest we export it from this module.
2535 =cut
2537 sub _find_value {
2538 my ( $tagfield, $insubfield, $record, $encoding ) = @_;
2539 my @result;
2540 my $indicator;
2541 if ( $tagfield < 10 ) {
2542 if ( $record->field($tagfield) ) {
2543 push @result, $record->field($tagfield)->data();
2544 } else {
2545 push @result, "";
2547 } else {
2548 foreach my $field ( $record->field($tagfield) ) {
2549 my @subfields = $field->subfields();
2550 foreach my $subfield (@subfields) {
2551 if ( @$subfield[0] eq $insubfield ) {
2552 push @result, @$subfield[1];
2553 $indicator = $field->indicator(1) . $field->indicator(2);
2558 return ( $indicator, @result );
2562 =head2 PrepareItemrecordDisplay
2564 PrepareItemrecordDisplay($itemrecord,$bibnum,$itemumber,$frameworkcode);
2566 Returns a hash with all the fields for Display a given item data in a template
2568 The $frameworkcode returns the item for the given frameworkcode, ONLY if bibnum is not provided
2570 =cut
2572 sub PrepareItemrecordDisplay {
2574 my ( $bibnum, $itemnum, $defaultvalues, $frameworkcode ) = @_;
2576 my $dbh = C4::Context->dbh;
2577 $frameworkcode = &GetFrameworkCode($bibnum) if $bibnum;
2578 my ( $itemtagfield, $itemtagsubfield ) = &GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
2579 my $tagslib = &GetMarcStructure( 1, $frameworkcode );
2581 # return nothing if we don't have found an existing framework.
2582 return q{} unless $tagslib;
2583 my $itemrecord;
2584 if ($itemnum) {
2585 $itemrecord = C4::Items::GetMarcItem( $bibnum, $itemnum );
2587 my @loop_data;
2588 my $authorised_values_sth = $dbh->prepare( "SELECT authorised_value,lib FROM authorised_values WHERE category=? ORDER BY lib" );
2589 foreach my $tag ( sort keys %{$tagslib} ) {
2590 my $previous_tag = '';
2591 if ( $tag ne '' ) {
2593 # loop through each subfield
2594 my $cntsubf;
2595 foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
2596 next if ( subfield_is_koha_internal_p($subfield) );
2597 next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "10" );
2598 my %subfield_data;
2599 $subfield_data{tag} = $tag;
2600 $subfield_data{subfield} = $subfield;
2601 $subfield_data{countsubfield} = $cntsubf++;
2602 $subfield_data{kohafield} = $tagslib->{$tag}->{$subfield}->{'kohafield'};
2603 $subfield_data{id} = "tag_".$tag."_subfield_".$subfield."_".int(rand(1000000));
2605 # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib};
2606 $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib};
2607 $subfield_data{mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory};
2608 $subfield_data{repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable};
2609 $subfield_data{hidden} = "display:none"
2610 if $tagslib->{$tag}->{$subfield}->{hidden};
2611 my ( $x, $defaultvalue );
2612 if ($itemrecord) {
2613 ( $x, $defaultvalue ) = _find_value( $tag, $subfield, $itemrecord );
2615 $defaultvalue = $tagslib->{$tag}->{$subfield}->{defaultvalue} unless $defaultvalue;
2616 if ( !defined $defaultvalue ) {
2617 $defaultvalue = q||;
2619 $defaultvalue =~ s/"/&quot;/g;
2621 # search for itemcallnumber if applicable
2622 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2623 && C4::Context->preference('itemcallnumber') ) {
2624 my $CNtag = substr( C4::Context->preference('itemcallnumber'), 0, 3 );
2625 my $CNsubfield = substr( C4::Context->preference('itemcallnumber'), 3, 1 );
2626 if ($itemrecord) {
2627 my $temp = $itemrecord->field($CNtag);
2628 if ($temp) {
2629 $defaultvalue = $temp->subfield($CNsubfield);
2633 if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.itemcallnumber'
2634 && $defaultvalues
2635 && $defaultvalues->{'callnumber'} ) {
2636 my $temp;
2637 if ($itemrecord) {
2638 $temp = $itemrecord->field($subfield);
2640 unless ($temp) {
2641 $defaultvalue = $defaultvalues->{'callnumber'} if $defaultvalues;
2644 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.holdingbranch' || $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.homebranch' )
2645 && $defaultvalues
2646 && $defaultvalues->{'branchcode'} ) {
2647 my $temp;
2648 if ($itemrecord) {
2649 $temp = $itemrecord->field($subfield);
2651 unless ($temp) {
2652 $defaultvalue = $defaultvalues->{branchcode} if $defaultvalues;
2655 if ( ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'items.location' )
2656 && $defaultvalues
2657 && $defaultvalues->{'location'} ) {
2658 my $temp = $itemrecord->field($subfield) if ($itemrecord);
2659 unless ($temp) {
2660 $defaultvalue = $defaultvalues->{location} if $defaultvalues;
2663 if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) {
2664 my @authorised_values;
2665 my %authorised_lib;
2667 # builds list, depending on authorised value...
2668 #---- branch
2669 if ( $tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
2670 if ( ( C4::Context->preference("IndependantBranches") )
2671 && ( C4::Context->userenv->{flags} % 2 != 1 ) ) {
2672 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" );
2673 $sth->execute( C4::Context->userenv->{branch} );
2674 push @authorised_values, ""
2675 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2676 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2677 push @authorised_values, $branchcode;
2678 $authorised_lib{$branchcode} = $branchname;
2680 } else {
2681 my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" );
2682 $sth->execute;
2683 push @authorised_values, ""
2684 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2685 while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) {
2686 push @authorised_values, $branchcode;
2687 $authorised_lib{$branchcode} = $branchname;
2691 #----- itemtypes
2692 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "itemtypes" ) {
2693 my $sth = $dbh->prepare( "SELECT itemtype,description FROM itemtypes ORDER BY description" );
2694 $sth->execute;
2695 push @authorised_values, ""
2696 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2697 while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) {
2698 push @authorised_values, $itemtype;
2699 $authorised_lib{$itemtype} = $description;
2701 #---- class_sources
2702 } elsif ( $tagslib->{$tag}->{$subfield}->{authorised_value} eq "cn_source" ) {
2703 push @authorised_values, "" unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2705 my $class_sources = GetClassSources();
2706 my $default_source = C4::Context->preference("DefaultClassificationSource");
2708 foreach my $class_source (sort keys %$class_sources) {
2709 next unless $class_sources->{$class_source}->{'used'} or
2710 ($class_source eq $default_source);
2711 push @authorised_values, $class_source;
2712 $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'};
2715 #---- "true" authorised value
2716 } else {
2717 $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} );
2718 push @authorised_values, ""
2719 unless ( $tagslib->{$tag}->{$subfield}->{mandatory} );
2720 while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) {
2721 push @authorised_values, $value;
2722 $authorised_lib{$value} = $lib;
2725 $subfield_data{marc_value} = CGI::scrolling_list(
2726 -name => 'field_value',
2727 -values => \@authorised_values,
2728 -default => "$defaultvalue",
2729 -labels => \%authorised_lib,
2730 -size => 1,
2731 -tabindex => '',
2732 -multiple => 0,
2734 } elsif ( $tagslib->{$tag}->{$subfield}->{value_builder} ) {
2735 # opening plugin
2736 my $plugin = C4::Context->intranetdir . "/cataloguing/value_builder/" . $tagslib->{$tag}->{$subfield}->{'value_builder'};
2737 if (do $plugin) {
2738 my $temp;
2739 my $extended_param = plugin_parameters( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2740 my ( $function_name, $javascript ) = plugin_javascript( $dbh, $temp, $tagslib, $subfield_data{id}, undef );
2741 $subfield_data{random} = int(rand(1000000)); # why do we need 2 different randoms?
2742 $subfield_data{marc_value} = qq[<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255"
2743 onfocus="Focus$function_name($subfield_data{random}, '$subfield_data{id}');"
2744 onblur=" Blur$function_name($subfield_data{random}, '$subfield_data{id}');" />
2745 <a href="#" class="buttonDot" onclick="Clic$function_name('$subfield_data{id}'); return false;" title="Tag Editor">...</a>
2746 $javascript];
2747 } else {
2748 warn "Plugin Failed: $plugin";
2749 $subfield_data{marc_value} = qq(<input tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" />); # supply default input form
2752 elsif ( $tag eq '' ) { # it's an hidden field
2753 $subfield_data{marc_value} = qq(<input type="hidden" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
2755 elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ?
2756 $subfield_data{marc_value} = qq(<input type="text" tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255" value="$defaultvalue" />);
2758 elsif ( length($defaultvalue) > 100
2759 or (C4::Context->preference("marcflavour") eq "UNIMARC" and
2760 300 <= $tag && $tag < 400 && $subfield eq 'a' )
2761 or (C4::Context->preference("marcflavour") eq "MARC21" and
2762 500 <= $tag && $tag < 600 )
2764 # oversize field (textarea)
2765 $subfield_data{marc_value} = qq(<textarea tabindex="1" id="$subfield_data{id}" name="field_value" class="input_marceditor" size="67" maxlength="255">$defaultvalue</textarea>\n");
2766 } else {
2767 $subfield_data{marc_value} = "<input type=\"text\" name=\"field_value\" value=\"$defaultvalue\" size=\"50\" maxlength=\"255\" />";
2769 push( @loop_data, \%subfield_data );
2773 my $itemnumber;
2774 if ( $itemrecord && $itemrecord->field($itemtagfield) ) {
2775 $itemnumber = $itemrecord->subfield( $itemtagfield, $itemtagsubfield );
2777 return {
2778 'itemtagfield' => $itemtagfield,
2779 'itemtagsubfield' => $itemtagsubfield,
2780 'itemnumber' => $itemnumber,
2781 'iteminformation' => \@loop_data