Bug 7016 Followup: Add new GetItemnumberForBiblio subroutine
[koha.git] / C4 / Items.pm
1 package C4::Items;
2
3 # Copyright 2007 LibLime, Inc.
4 # Parts Copyright Biblibre 2010
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
16 #
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.
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23
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 C4::Branch;
33 require C4::Reserves;
34 use C4::Charset;
35 use C4::Acquisition;
36 use List::MoreUtils qw/any/;
37 use Data::Dumper; # used as part of logging item record changes, not just for
38                   # debugging; so please don't remove this
39
40 use vars qw($VERSION @ISA @EXPORT);
41
42 BEGIN {
43     $VERSION = 3.01;
44
45         require Exporter;
46     @ISA = qw( Exporter );
47
48     # function exports
49     @EXPORT = qw(
50         GetItem
51         AddItemFromMarc
52         AddItem
53         AddItemBatchFromMarc
54         ModItemFromMarc
55                 Item2Marc
56         ModItem
57         ModDateLastSeen
58         ModItemTransfer
59         DelItem
60     
61         CheckItemPreSave
62     
63         GetItemStatus
64         GetItemLocation
65         GetLostItems
66         GetItemsForInventory
67         GetItemsCount
68         GetItemInfosOf
69         GetItemsByBiblioitemnumber
70         GetItemsInfo
71         GetItemsLocationInfo
72         GetHostItemsInfo
73         GetItemnumbersForBiblio
74         get_itemnumbers_of
75         get_hostitemnumbers_of
76         GetItemnumberFromBarcode
77         GetBarcodeFromItemnumber
78         GetHiddenItemnumbers
79                 DelItemCheck
80                 MoveItemFromBiblio 
81                 GetLatestAcquisitions
82         CartToShelf
83
84         GetAnalyticsCount
85         GetItemHolds
86     );
87 }
88
89 =head1 NAME
90
91 C4::Items - item management functions
92
93 =head1 DESCRIPTION
94
95 This module contains an API for manipulating item 
96 records in Koha, and is used by cataloguing, circulation,
97 acquisitions, and serials management.
98
99 A Koha item record is stored in two places: the
100 items table and embedded in a MARC tag in the XML
101 version of the associated bib record in C<biblioitems.marcxml>.
102 This is done to allow the item information to be readily
103 indexed (e.g., by Zebra), but means that each item
104 modification transaction must keep the items table
105 and the MARC XML in sync at all times.
106
107 Consequently, all code that creates, modifies, or deletes
108 item records B<must> use an appropriate function from 
109 C<C4::Items>.  If no existing function is suitable, it is
110 better to add one to C<C4::Items> than to use add
111 one-off SQL statements to add or modify items.
112
113 The items table will be considered authoritative.  In other
114 words, if there is ever a discrepancy between the items
115 table and the MARC XML, the items table should be considered
116 accurate.
117
118 =head1 HISTORICAL NOTE
119
120 Most of the functions in C<C4::Items> were originally in
121 the C<C4::Biblio> module.
122
123 =head1 CORE EXPORTED FUNCTIONS
124
125 The following functions are meant for use by users
126 of C<C4::Items>
127
128 =cut
129
130 =head2 GetItem
131
132   $item = GetItem($itemnumber,$barcode,$serial);
133
134 Return item information, for a given itemnumber or barcode.
135 The return value is a hashref mapping item column
136 names to values.  If C<$serial> is true, include serial publication data.
137
138 =cut
139
140 sub GetItem {
141     my ($itemnumber,$barcode, $serial) = @_;
142     my $dbh = C4::Context->dbh;
143         my $data;
144     if ($itemnumber) {
145         my $sth = $dbh->prepare("
146             SELECT * FROM items 
147             WHERE itemnumber = ?");
148         $sth->execute($itemnumber);
149         $data = $sth->fetchrow_hashref;
150     } else {
151         my $sth = $dbh->prepare("
152             SELECT * FROM items 
153             WHERE barcode = ?"
154             );
155         $sth->execute($barcode);                
156         $data = $sth->fetchrow_hashref;
157     }
158     if ( $serial) {      
159     my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=?");
160         $ssth->execute($data->{'itemnumber'}) ;
161         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
162     }
163         #if we don't have an items.itype, use biblioitems.itemtype.
164         if( ! $data->{'itype'} ) {
165                 my $sth = $dbh->prepare("SELECT itemtype FROM biblioitems  WHERE biblionumber = ?");
166                 $sth->execute($data->{'biblionumber'});
167                 ($data->{'itype'}) = $sth->fetchrow_array;
168         }
169     return $data;
170 }    # sub GetItem
171
172 =head2 CartToShelf
173
174   CartToShelf($itemnumber);
175
176 Set the current shelving location of the item record
177 to its stored permanent shelving location.  This is
178 primarily used to indicate when an item whose current
179 location is a special processing ('PROC') or shelving cart
180 ('CART') location is back in the stacks.
181
182 =cut
183
184 sub CartToShelf {
185     my ( $itemnumber ) = @_;
186
187     unless ( $itemnumber ) {
188         croak "FAILED CartToShelf() - no itemnumber supplied";
189     }
190
191     my $item = GetItem($itemnumber);
192     $item->{location} = $item->{permanent_location};
193     ModItem($item, undef, $itemnumber);
194 }
195
196 =head2 AddItemFromMarc
197
198   my ($biblionumber, $biblioitemnumber, $itemnumber) 
199       = AddItemFromMarc($source_item_marc, $biblionumber);
200
201 Given a MARC::Record object containing an embedded item
202 record and a biblionumber, create a new item record.
203
204 =cut
205
206 sub AddItemFromMarc {
207     my ( $source_item_marc, $biblionumber ) = @_;
208     my $dbh = C4::Context->dbh;
209
210     # parse item hash from MARC
211     my $frameworkcode = GetFrameworkCode( $biblionumber );
212         my ($itemtag,$itemsubfield)=GetMarcFromKohaField("items.itemnumber",$frameworkcode);
213         
214         my $localitemmarc=MARC::Record->new;
215         $localitemmarc->append_fields($source_item_marc->field($itemtag));
216     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode ,'items');
217     my $unlinked_item_subfields = _get_unlinked_item_subfields($localitemmarc, $frameworkcode);
218     return AddItem($item, $biblionumber, $dbh, $frameworkcode, $unlinked_item_subfields);
219 }
220
221 =head2 AddItem
222
223   my ($biblionumber, $biblioitemnumber, $itemnumber) 
224       = AddItem($item, $biblionumber[, $dbh, $frameworkcode, $unlinked_item_subfields]);
225
226 Given a hash containing item column names as keys,
227 create a new Koha item record.
228
229 The first two optional parameters (C<$dbh> and C<$frameworkcode>)
230 do not need to be supplied for general use; they exist
231 simply to allow them to be picked up from AddItemFromMarc.
232
233 The final optional parameter, C<$unlinked_item_subfields>, contains
234 an arrayref containing subfields present in the original MARC
235 representation of the item (e.g., from the item editor) that are
236 not mapped to C<items> columns directly but should instead
237 be stored in C<items.more_subfields_xml> and included in 
238 the biblio items tag for display and indexing.
239
240 =cut
241
242 sub AddItem {
243     my $item = shift;
244     my $biblionumber = shift;
245
246     my $dbh           = @_ ? shift : C4::Context->dbh;
247     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
248     my $unlinked_item_subfields;  
249     if (@_) {
250         $unlinked_item_subfields = shift
251     };
252
253     # needs old biblionumber and biblioitemnumber
254     $item->{'biblionumber'} = $biblionumber;
255     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?");
256     $sth->execute( $item->{'biblionumber'} );
257     ($item->{'biblioitemnumber'}) = $sth->fetchrow;
258
259     _set_defaults_for_add($item);
260     _set_derived_columns_for_add($item);
261     $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
262     # FIXME - checks here
263     unless ( $item->{itype} ) {  # default to biblioitem.itemtype if no itype
264         my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?");
265         $itype_sth->execute( $item->{'biblionumber'} );
266         ( $item->{'itype'} ) = $itype_sth->fetchrow_array;
267     }
268
269         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
270     $item->{'itemnumber'} = $itemnumber;
271
272     ModZebra( $item->{biblionumber}, "specialUpdate", "biblioserver", undef, undef );
273    
274     logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
275     
276     return ($item->{biblionumber}, $item->{biblioitemnumber}, $itemnumber);
277 }
278
279 =head2 AddItemBatchFromMarc
280
281   ($itemnumber_ref, $error_ref) = AddItemBatchFromMarc($record, 
282              $biblionumber, $biblioitemnumber, $frameworkcode);
283
284 Efficiently create item records from a MARC biblio record with
285 embedded item fields.  This routine is suitable for batch jobs.
286
287 This API assumes that the bib record has already been
288 saved to the C<biblio> and C<biblioitems> tables.  It does
289 not expect that C<biblioitems.marc> and C<biblioitems.marcxml>
290 are populated, but it will do so via a call to ModBibiloMarc.
291
292 The goal of this API is to have a similar effect to using AddBiblio
293 and AddItems in succession, but without inefficient repeated
294 parsing of the MARC XML bib record.
295
296 This function returns an arrayref of new itemsnumbers and an arrayref of item
297 errors encountered during the processing.  Each entry in the errors
298 list is a hashref containing the following keys:
299
300 =over
301
302 =item item_sequence
303
304 Sequence number of original item tag in the MARC record.
305
306 =item item_barcode
307
308 Item barcode, provide to assist in the construction of
309 useful error messages.
310
311 =item error_condition
312
313 Code representing the error condition.  Can be 'duplicate_barcode',
314 'invalid_homebranch', or 'invalid_holdingbranch'.
315
316 =item error_information
317
318 Additional information appropriate to the error condition.
319
320 =back
321
322 =cut
323
324 sub AddItemBatchFromMarc {
325     my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_;
326     my $error;
327     my @itemnumbers = ();
328     my @errors = ();
329     my $dbh = C4::Context->dbh;
330
331     # loop through the item tags and start creating items
332     my @bad_item_fields = ();
333     my ($itemtag, $itemsubfield) = &GetMarcFromKohaField("items.itemnumber",'');
334     my $item_sequence_num = 0;
335     ITEMFIELD: foreach my $item_field ($record->field($itemtag)) {
336         $item_sequence_num++;
337         # we take the item field and stick it into a new
338         # MARC record -- this is required so far because (FIXME)
339         # TransformMarcToKoha requires a MARC::Record, not a MARC::Field
340         # and there is no TransformMarcFieldToKoha
341         my $temp_item_marc = MARC::Record->new();
342         $temp_item_marc->append_fields($item_field);
343     
344         # add biblionumber and biblioitemnumber
345         my $item = TransformMarcToKoha( $dbh, $temp_item_marc, $frameworkcode, 'items' );
346         my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode);
347         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
348         $item->{'biblionumber'} = $biblionumber;
349         $item->{'biblioitemnumber'} = $biblioitemnumber;
350
351         # check for duplicate barcode
352         my %item_errors = CheckItemPreSave($item);
353         if (%item_errors) {
354             push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors);
355             push @bad_item_fields, $item_field;
356             next ITEMFIELD;
357         }
358
359         _set_defaults_for_add($item);
360         _set_derived_columns_for_add($item);
361         my ( $itemnumber, $error ) = _koha_new_item( $item, $item->{barcode} );
362         warn $error if $error;
363         push @itemnumbers, $itemnumber; # FIXME not checking error
364         $item->{'itemnumber'} = $itemnumber;
365
366         logaction("CATALOGUING", "ADD", $itemnumber, "item") if C4::Context->preference("CataloguingLog"); 
367
368         my $new_item_marc = _marc_from_item_hash($item, $frameworkcode, $unlinked_item_subfields);
369         $item_field->replace_with($new_item_marc->field($itemtag));
370     }
371
372     # remove any MARC item fields for rejected items
373     foreach my $item_field (@bad_item_fields) {
374         $record->delete_field($item_field);
375     }
376
377     # update the MARC biblio
378  #   $biblionumber = ModBiblioMarc( $record, $biblionumber, $frameworkcode );
379
380     return (\@itemnumbers, \@errors);
381 }
382
383 =head2 ModItemFromMarc
384
385   ModItemFromMarc($item_marc, $biblionumber, $itemnumber);
386
387 This function updates an item record based on a supplied
388 C<MARC::Record> object containing an embedded item field.
389 This API is meant for the use of C<additem.pl>; for 
390 other purposes, C<ModItem> should be used.
391
392 This function uses the hash %default_values_for_mod_from_marc,
393 which contains default values for item fields to
394 apply when modifying an item.  This is needed beccause
395 if an item field's value is cleared, TransformMarcToKoha
396 does not include the column in the
397 hash that's passed to ModItem, which without
398 use of this hash makes it impossible to clear
399 an item field's value.  See bug 2466.
400
401 Note that only columns that can be directly
402 changed from the cataloging and serials
403 item editors are included in this hash.
404
405 Returns item record
406
407 =cut
408
409 my %default_values_for_mod_from_marc = (
410     barcode              => undef, 
411     booksellerid         => undef, 
412     ccode                => undef, 
413     'items.cn_source'    => undef, 
414     copynumber           => undef, 
415     damaged              => 0,
416 #    dateaccessioned      => undef,
417     enumchron            => undef, 
418     holdingbranch        => undef, 
419     homebranch           => undef, 
420     itemcallnumber       => undef, 
421     itemlost             => 0,
422     itemnotes            => undef, 
423     itype                => undef, 
424     location             => undef, 
425     permanent_location   => undef,
426     materials            => undef, 
427     notforloan           => 0,
428     paidfor              => undef, 
429     price                => undef, 
430     replacementprice     => undef, 
431     replacementpricedate => undef, 
432     restricted           => undef, 
433     stack                => undef, 
434     stocknumber          => undef, 
435     uri                  => undef, 
436     wthdrawn             => 0,
437 );
438
439 sub ModItemFromMarc {
440     my $item_marc = shift;
441     my $biblionumber = shift;
442     my $itemnumber = shift;
443
444     my $dbh           = C4::Context->dbh;
445     my $frameworkcode = GetFrameworkCode($biblionumber);
446     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber", $frameworkcode );
447
448     my $localitemmarc = MARC::Record->new;
449     $localitemmarc->append_fields( $item_marc->field($itemtag) );
450     my $item = &TransformMarcToKoha( $dbh, $localitemmarc, $frameworkcode, 'items' );
451     foreach my $item_field ( keys %default_values_for_mod_from_marc ) {
452         $item->{$item_field} = $default_values_for_mod_from_marc{$item_field} unless (exists $item->{$item_field});
453     }
454     my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode );
455
456     ModItem($item, $biblionumber, $itemnumber, $dbh, $frameworkcode, $unlinked_item_subfields); 
457     return $item;
458 }
459
460 =head2 ModItem
461
462   ModItem({ column => $newvalue }, $biblionumber, 
463                   $itemnumber[, $original_item_marc]);
464
465 Change one or more columns in an item record and update
466 the MARC representation of the item.
467
468 The first argument is a hashref mapping from item column
469 names to the new values.  The second and third arguments
470 are the biblionumber and itemnumber, respectively.
471
472 The fourth, optional parameter, C<$unlinked_item_subfields>, contains
473 an arrayref containing subfields present in the original MARC
474 representation of the item (e.g., from the item editor) that are
475 not mapped to C<items> columns directly but should instead
476 be stored in C<items.more_subfields_xml> and included in 
477 the biblio items tag for display and indexing.
478
479 If one of the changed columns is used to calculate
480 the derived value of a column such as C<items.cn_sort>, 
481 this routine will perform the necessary calculation
482 and set the value.
483
484 =cut
485
486 sub ModItem {
487     my $item = shift;
488     my $biblionumber = shift;
489     my $itemnumber = shift;
490
491     # if $biblionumber is undefined, get it from the current item
492     unless (defined $biblionumber) {
493         $biblionumber = _get_single_item_column('biblionumber', $itemnumber);
494     }
495
496     my $dbh           = @_ ? shift : C4::Context->dbh;
497     my $frameworkcode = @_ ? shift : GetFrameworkCode( $biblionumber );
498     
499     my $unlinked_item_subfields;  
500     if (@_) {
501         $unlinked_item_subfields = shift;
502         $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields);
503     };
504
505     $item->{'itemnumber'} = $itemnumber or return undef;
506
507     $item->{onloan} = undef if $item->{itemlost};
508
509     _set_derived_columns_for_mod($item);
510     _do_column_fixes_for_mod($item);
511     # FIXME add checks
512     # duplicate barcode
513     # attempt to change itemnumber
514     # attempt to change biblionumber (if we want
515     # an API to relink an item to a different bib,
516     # it should be a separate function)
517
518     # update items table
519     _koha_modify_item($item);
520
521     # request that bib be reindexed so that searching on current
522     # item status is possible
523     ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
524
525     logaction("CATALOGUING", "MODIFY", $itemnumber, Dumper($item)) if C4::Context->preference("CataloguingLog");
526 }
527
528 =head2 ModItemTransfer
529
530   ModItemTransfer($itenumber, $frombranch, $tobranch);
531
532 Marks an item as being transferred from one branch
533 to another.
534
535 =cut
536
537 sub ModItemTransfer {
538     my ( $itemnumber, $frombranch, $tobranch ) = @_;
539
540     my $dbh = C4::Context->dbh;
541
542     #new entry in branchtransfers....
543     my $sth = $dbh->prepare(
544         "INSERT INTO branchtransfers (itemnumber, frombranch, datesent, tobranch)
545         VALUES (?, ?, NOW(), ?)");
546     $sth->execute($itemnumber, $frombranch, $tobranch);
547
548     ModItem({ holdingbranch => $tobranch }, undef, $itemnumber);
549     ModDateLastSeen($itemnumber);
550     return;
551 }
552
553 =head2 ModDateLastSeen
554
555   ModDateLastSeen($itemnum);
556
557 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking.
558 C<$itemnum> is the item number
559
560 =cut
561
562 sub ModDateLastSeen {
563     my ($itemnumber) = @_;
564     
565     my $today = C4::Dates->new();    
566     ModItem({ itemlost => 0, datelastseen => $today->output("iso") }, undef, $itemnumber);
567 }
568
569 =head2 DelItem
570
571   DelItem($dbh, $biblionumber, $itemnumber);
572
573 Exported function (core API) for deleting an item record in Koha.
574
575 =cut
576
577 sub DelItem {
578     my ( $dbh, $biblionumber, $itemnumber ) = @_;
579     
580     # FIXME check the item has no current issues
581     
582     _koha_delete_item( $dbh, $itemnumber );
583
584     # get the MARC record
585     my $record = GetMarcBiblio($biblionumber);
586     ModZebra( $biblionumber, "specialUpdate", "biblioserver", undef, undef );
587
588     # backup the record
589     my $copy2deleted = $dbh->prepare("UPDATE deleteditems SET marc=? WHERE itemnumber=?");
590     $copy2deleted->execute( $record->as_usmarc(), $itemnumber );
591
592     #search item field code
593     logaction("CATALOGUING", "DELETE", $itemnumber, "item") if C4::Context->preference("CataloguingLog");
594 }
595
596 =head2 CheckItemPreSave
597
598     my $item_ref = TransformMarcToKoha($marc, 'items');
599     # do stuff
600     my %errors = CheckItemPreSave($item_ref);
601     if (exists $errors{'duplicate_barcode'}) {
602         print "item has duplicate barcode: ", $errors{'duplicate_barcode'}, "\n";
603     } elsif (exists $errors{'invalid_homebranch'}) {
604         print "item has invalid home branch: ", $errors{'invalid_homebranch'}, "\n";
605     } elsif (exists $errors{'invalid_holdingbranch'}) {
606         print "item has invalid holding branch: ", $errors{'invalid_holdingbranch'}, "\n";
607     } else {
608         print "item is OK";
609     }
610
611 Given a hashref containing item fields, determine if it can be
612 inserted or updated in the database.  Specifically, checks for
613 database integrity issues, and returns a hash containing any
614 of the following keys, if applicable.
615
616 =over 2
617
618 =item duplicate_barcode
619
620 Barcode, if it duplicates one already found in the database.
621
622 =item invalid_homebranch
623
624 Home branch, if not defined in branches table.
625
626 =item invalid_holdingbranch
627
628 Holding branch, if not defined in branches table.
629
630 =back
631
632 This function does NOT implement any policy-related checks,
633 e.g., whether current operator is allowed to save an
634 item that has a given branch code.
635
636 =cut
637
638 sub CheckItemPreSave {
639     my $item_ref = shift;
640
641     my %errors = ();
642
643     # check for duplicate barcode
644     if (exists $item_ref->{'barcode'} and defined $item_ref->{'barcode'}) {
645         my $existing_itemnumber = GetItemnumberFromBarcode($item_ref->{'barcode'});
646         if ($existing_itemnumber) {
647             if (!exists $item_ref->{'itemnumber'}                       # new item
648                 or $item_ref->{'itemnumber'} != $existing_itemnumber) { # existing item
649                 $errors{'duplicate_barcode'} = $item_ref->{'barcode'};
650             }
651         }
652     }
653
654     # check for valid home branch
655     if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) {
656         my $branch_name = GetBranchName($item_ref->{'homebranch'});
657         unless (defined $branch_name) {
658             # relies on fact that branches.branchname is a non-NULL column,
659             # so GetBranchName returns undef only if branch does not exist
660             $errors{'invalid_homebranch'} = $item_ref->{'homebranch'};
661         }
662     }
663
664     # check for valid holding branch
665     if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) {
666         my $branch_name = GetBranchName($item_ref->{'holdingbranch'});
667         unless (defined $branch_name) {
668             # relies on fact that branches.branchname is a non-NULL column,
669             # so GetBranchName returns undef only if branch does not exist
670             $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'};
671         }
672     }
673
674     return %errors;
675
676 }
677
678 =head1 EXPORTED SPECIAL ACCESSOR FUNCTIONS
679
680 The following functions provide various ways of 
681 getting an item record, a set of item records, or
682 lists of authorized values for certain item fields.
683
684 Some of the functions in this group are candidates
685 for refactoring -- for example, some of the code
686 in C<GetItemsByBiblioitemnumber> and C<GetItemsInfo>
687 has copy-and-paste work.
688
689 =cut
690
691 =head2 GetItemStatus
692
693   $itemstatushash = GetItemStatus($fwkcode);
694
695 Returns a list of valid values for the
696 C<items.notforloan> field.
697
698 NOTE: does B<not> return an individual item's
699 status.
700
701 Can be MARC dependant.
702 fwkcode is optional.
703 But basically could be can be loan or not
704 Create a status selector with the following code
705
706 =head3 in PERL SCRIPT
707
708  my $itemstatushash = getitemstatus;
709  my @itemstatusloop;
710  foreach my $thisstatus (keys %$itemstatushash) {
711      my %row =(value => $thisstatus,
712                  statusname => $itemstatushash->{$thisstatus}->{'statusname'},
713              );
714      push @itemstatusloop, \%row;
715  }
716  $template->param(statusloop=>\@itemstatusloop);
717
718 =head3 in TEMPLATE
719
720  <select name="statusloop">
721      <option value="">Default</option>
722  <!-- TMPL_LOOP name="statusloop" -->
723      <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="statusname" --></option>
724  <!-- /TMPL_LOOP -->
725  </select>
726
727 =cut
728
729 sub GetItemStatus {
730
731     # returns a reference to a hash of references to status...
732     my ($fwk) = @_;
733     my %itemstatus;
734     my $dbh = C4::Context->dbh;
735     my $sth;
736     $fwk = '' unless ($fwk);
737     my ( $tag, $subfield ) =
738       GetMarcFromKohaField( "items.notforloan", $fwk );
739     if ( $tag and $subfield ) {
740         my $sth =
741           $dbh->prepare(
742             "SELECT authorised_value
743             FROM marc_subfield_structure
744             WHERE tagfield=?
745                 AND tagsubfield=?
746                 AND frameworkcode=?
747             "
748           );
749         $sth->execute( $tag, $subfield, $fwk );
750         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
751             my $authvalsth =
752               $dbh->prepare(
753                 "SELECT authorised_value,lib
754                 FROM authorised_values 
755                 WHERE category=? 
756                 ORDER BY lib
757                 "
758               );
759             $authvalsth->execute($authorisedvaluecat);
760             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
761                 $itemstatus{$authorisedvalue} = $lib;
762             }
763             return \%itemstatus;
764             exit 1;
765         }
766         else {
767
768             #No authvalue list
769             # build default
770         }
771     }
772
773     #No authvalue list
774     #build default
775     $itemstatus{"1"} = "Not For Loan";
776     return \%itemstatus;
777 }
778
779 =head2 GetItemLocation
780
781   $itemlochash = GetItemLocation($fwk);
782
783 Returns a list of valid values for the
784 C<items.location> field.
785
786 NOTE: does B<not> return an individual item's
787 location.
788
789 where fwk stands for an optional framework code.
790 Create a location selector with the following code
791
792 =head3 in PERL SCRIPT
793
794   my $itemlochash = getitemlocation;
795   my @itemlocloop;
796   foreach my $thisloc (keys %$itemlochash) {
797       my $selected = 1 if $thisbranch eq $branch;
798       my %row =(locval => $thisloc,
799                   selected => $selected,
800                   locname => $itemlochash->{$thisloc},
801                );
802       push @itemlocloop, \%row;
803   }
804   $template->param(itemlocationloop => \@itemlocloop);
805
806 =head3 in TEMPLATE
807
808   <select name="location">
809       <option value="">Default</option>
810   <!-- TMPL_LOOP name="itemlocationloop" -->
811       <option value="<!-- TMPL_VAR name="locval" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="locname" --></option>
812   <!-- /TMPL_LOOP -->
813   </select>
814
815 =cut
816
817 sub GetItemLocation {
818
819     # returns a reference to a hash of references to location...
820     my ($fwk) = @_;
821     my %itemlocation;
822     my $dbh = C4::Context->dbh;
823     my $sth;
824     $fwk = '' unless ($fwk);
825     my ( $tag, $subfield ) =
826       GetMarcFromKohaField( "items.location", $fwk );
827     if ( $tag and $subfield ) {
828         my $sth =
829           $dbh->prepare(
830             "SELECT authorised_value
831             FROM marc_subfield_structure 
832             WHERE tagfield=? 
833                 AND tagsubfield=? 
834                 AND frameworkcode=?"
835           );
836         $sth->execute( $tag, $subfield, $fwk );
837         if ( my ($authorisedvaluecat) = $sth->fetchrow ) {
838             my $authvalsth =
839               $dbh->prepare(
840                 "SELECT authorised_value,lib
841                 FROM authorised_values
842                 WHERE category=?
843                 ORDER BY lib"
844               );
845             $authvalsth->execute($authorisedvaluecat);
846             while ( my ( $authorisedvalue, $lib ) = $authvalsth->fetchrow ) {
847                 $itemlocation{$authorisedvalue} = $lib;
848             }
849             return \%itemlocation;
850             exit 1;
851         }
852         else {
853
854             #No authvalue list
855             # build default
856         }
857     }
858
859     #No authvalue list
860     #build default
861     $itemlocation{"1"} = "Not For Loan";
862     return \%itemlocation;
863 }
864
865 =head2 GetLostItems
866
867   $items = GetLostItems( $where, $orderby );
868
869 This function gets a list of lost items.
870
871 =over 2
872
873 =item input:
874
875 C<$where> is a hashref. it containts a field of the items table as key
876 and the value to match as value. For example:
877
878 { barcode    => 'abc123',
879   homebranch => 'CPL',    }
880
881 C<$orderby> is a field of the items table by which the resultset
882 should be orderd.
883
884 =item return:
885
886 C<$items> is a reference to an array full of hashrefs with columns
887 from the "items" table as keys.
888
889 =item usage in the perl script:
890
891   my $where = { barcode => '0001548' };
892   my $items = GetLostItems( $where, "homebranch" );
893   $template->param( itemsloop => $items );
894
895 =back
896
897 =cut
898
899 sub GetLostItems {
900     # Getting input args.
901     my $where   = shift;
902     my $orderby = shift;
903     my $dbh     = C4::Context->dbh;
904
905     my $query   = "
906         SELECT *
907         FROM   items
908             LEFT JOIN biblio ON (items.biblionumber = biblio.biblionumber)
909             LEFT JOIN biblioitems ON (items.biblionumber = biblioitems.biblionumber)
910             LEFT JOIN authorised_values ON (items.itemlost = authorised_values.authorised_value)
911         WHERE
912                 authorised_values.category = 'LOST'
913                 AND itemlost IS NOT NULL
914                 AND itemlost <> 0
915     ";
916     my @query_parameters;
917     foreach my $key (keys %$where) {
918         $query .= " AND $key LIKE ?";
919         push @query_parameters, "%$where->{$key}%";
920     }
921     my @ordervalues = qw/title author homebranch itype barcode price replacementprice lib datelastseen location/;
922     
923     if ( defined $orderby && grep($orderby, @ordervalues)) {
924         $query .= ' ORDER BY '.$orderby;
925     }
926
927     my $sth = $dbh->prepare($query);
928     $sth->execute( @query_parameters );
929     my $items = [];
930     while ( my $row = $sth->fetchrow_hashref ){
931         push @$items, $row;
932     }
933     return $items;
934 }
935
936 =head2 GetItemsForInventory
937
938   $itemlist = GetItemsForInventory($minlocation, $maxlocation, 
939                  $location, $itemtype $datelastseen, $branch, 
940                  $offset, $size, $statushash);
941
942 Retrieve a list of title/authors/barcode/callnumber, for biblio inventory.
943
944 The sub returns a reference to a list of hashes, each containing
945 itemnumber, author, title, barcode, item callnumber, and date last
946 seen. It is ordered by callnumber then title.
947
948 The required minlocation & maxlocation parameters are used to specify a range of item callnumbers
949 the datelastseen can be used to specify that you want to see items not seen since a past date only.
950 offset & size can be used to retrieve only a part of the whole listing (defaut behaviour)
951 $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.
952
953 =cut
954
955 sub GetItemsForInventory {
956     my ( $minlocation, $maxlocation,$location, $itemtype, $ignoreissued, $datelastseen, $branchcode, $branch, $offset, $size, $statushash ) = @_;
957     my $dbh = C4::Context->dbh;
958     my ( @bind_params, @where_strings );
959
960     my $query = <<'END_SQL';
961 SELECT items.itemnumber, barcode, itemcallnumber, title, author, biblio.biblionumber, datelastseen
962 FROM items
963   LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
964   LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber
965 END_SQL
966     if ($statushash){
967         for my $authvfield (keys %$statushash){
968             if ( scalar @{$statushash->{$authvfield}} > 0 ){
969                 my $joinedvals = join ',', @{$statushash->{$authvfield}};
970                 push @where_strings, "$authvfield in (" . $joinedvals . ")";
971             }
972         }
973     }
974
975     if ($minlocation) {
976         push @where_strings, 'itemcallnumber >= ?';
977         push @bind_params, $minlocation;
978     }
979
980     if ($maxlocation) {
981         push @where_strings, 'itemcallnumber <= ?';
982         push @bind_params, $maxlocation;
983     }
984
985     if ($datelastseen) {
986         $datelastseen = format_date_in_iso($datelastseen);  
987         push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)';
988         push @bind_params, $datelastseen;
989     }
990
991     if ( $location ) {
992         push @where_strings, 'items.location = ?';
993         push @bind_params, $location;
994     }
995
996     if ( $branchcode ) {
997         if($branch eq "homebranch"){
998         push @where_strings, 'items.homebranch = ?';
999         }else{
1000             push @where_strings, 'items.holdingbranch = ?';
1001         }
1002         push @bind_params, $branchcode;
1003     }
1004     
1005     if ( $itemtype ) {
1006         push @where_strings, 'biblioitems.itemtype = ?';
1007         push @bind_params, $itemtype;
1008     }
1009
1010     if ( $ignoreissued) {
1011         $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber ";
1012         push @where_strings, 'issues.date_due IS NULL';
1013     }
1014
1015     if ( @where_strings ) {
1016         $query .= 'WHERE ';
1017         $query .= join ' AND ', @where_strings;
1018     }
1019     $query .= ' ORDER BY items.cn_sort, itemcallnumber, title';
1020     my $sth = $dbh->prepare($query);
1021     $sth->execute( @bind_params );
1022
1023     my @results;
1024     $size--;
1025     while ( my $row = $sth->fetchrow_hashref ) {
1026         $offset-- if ($offset);
1027         $row->{datelastseen}=format_date($row->{datelastseen});
1028         if ( ( !$offset ) && $size ) {
1029             push @results, $row;
1030             $size--;
1031         }
1032     }
1033     return \@results;
1034 }
1035
1036 =head2 GetItemsCount
1037
1038   $count = &GetItemsCount( $biblionumber);
1039
1040 This function return count of item with $biblionumber
1041
1042 =cut
1043
1044 sub GetItemsCount {
1045     my ( $biblionumber ) = @_;
1046     my $dbh = C4::Context->dbh;
1047     my $query = "SELECT count(*)
1048           FROM  items 
1049           WHERE biblionumber=?";
1050     my $sth = $dbh->prepare($query);
1051     $sth->execute($biblionumber);
1052     my $count = $sth->fetchrow;  
1053     return ($count);
1054 }
1055
1056 =head2 GetItemInfosOf
1057
1058   GetItemInfosOf(@itemnumbers);
1059
1060 =cut
1061
1062 sub GetItemInfosOf {
1063     my @itemnumbers = @_;
1064
1065     my $query = '
1066         SELECT *
1067         FROM items
1068         WHERE itemnumber IN (' . join( ',', @itemnumbers ) . ')
1069     ';
1070     return get_infos_of( $query, 'itemnumber' );
1071 }
1072
1073 =head2 GetItemsByBiblioitemnumber
1074
1075   GetItemsByBiblioitemnumber($biblioitemnumber);
1076
1077 Returns an arrayref of hashrefs suitable for use in a TMPL_LOOP
1078 Called by C<C4::XISBN>
1079
1080 =cut
1081
1082 sub GetItemsByBiblioitemnumber {
1083     my ( $bibitem ) = @_;
1084     my $dbh = C4::Context->dbh;
1085     my $sth = $dbh->prepare("SELECT * FROM items WHERE items.biblioitemnumber = ?") || die $dbh->errstr;
1086     # Get all items attached to a biblioitem
1087     my $i = 0;
1088     my @results; 
1089     $sth->execute($bibitem) || die $sth->errstr;
1090     while ( my $data = $sth->fetchrow_hashref ) {  
1091         # Foreach item, get circulation information
1092         my $sth2 = $dbh->prepare( "SELECT * FROM issues,borrowers
1093                                    WHERE itemnumber = ?
1094                                    AND issues.borrowernumber = borrowers.borrowernumber"
1095         );
1096         $sth2->execute( $data->{'itemnumber'} );
1097         if ( my $data2 = $sth2->fetchrow_hashref ) {
1098             # if item is out, set the due date and who it is out too
1099             $data->{'date_due'}   = $data2->{'date_due'};
1100             $data->{'cardnumber'} = $data2->{'cardnumber'};
1101             $data->{'borrowernumber'}   = $data2->{'borrowernumber'};
1102         }
1103         else {
1104             # set date_due to blank, so in the template we check itemlost, and wthdrawn 
1105             $data->{'date_due'} = '';                                                                                                         
1106         }    # else         
1107         # Find the last 3 people who borrowed this item.                  
1108         my $query2 = "SELECT * FROM old_issues, borrowers WHERE itemnumber = ?
1109                       AND old_issues.borrowernumber = borrowers.borrowernumber
1110                       ORDER BY returndate desc,timestamp desc LIMIT 3";
1111         $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1112         $sth2->execute( $data->{'itemnumber'} ) || die $sth2->errstr;
1113         my $i2 = 0;
1114         while ( my $data2 = $sth2->fetchrow_hashref ) {
1115             $data->{"timestamp$i2"} = $data2->{'timestamp'};
1116             $data->{"card$i2"}      = $data2->{'cardnumber'};
1117             $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1118             $i2++;
1119         }
1120         push(@results,$data);
1121     } 
1122     return (\@results); 
1123 }
1124
1125 =head2 GetItemsInfo
1126
1127   @results = GetItemsInfo($biblionumber);
1128
1129 Returns information about items with the given biblionumber.
1130
1131 C<GetItemsInfo> returns a list of references-to-hash. Each element
1132 contains a number of keys. Most of them are attributes from the
1133 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1134 Koha database. Other keys include:
1135
1136 =over 2
1137
1138 =item C<$data-E<gt>{branchname}>
1139
1140 The name (not the code) of the branch to which the book belongs.
1141
1142 =item C<$data-E<gt>{datelastseen}>
1143
1144 This is simply C<items.datelastseen>, except that while the date is
1145 stored in YYYY-MM-DD format in the database, here it is converted to
1146 DD/MM/YYYY format. A NULL date is returned as C<//>.
1147
1148 =item C<$data-E<gt>{datedue}>
1149
1150 =item C<$data-E<gt>{class}>
1151
1152 This is the concatenation of C<biblioitems.classification>, the book's
1153 Dewey code, and C<biblioitems.subclass>.
1154
1155 =item C<$data-E<gt>{ocount}>
1156
1157 I think this is the number of copies of the book available.
1158
1159 =item C<$data-E<gt>{order}>
1160
1161 If this is set, it is set to C<One Order>.
1162
1163 =back
1164
1165 =cut
1166
1167 sub GetItemsInfo {
1168     my ( $biblionumber ) = @_;
1169     my $dbh   = C4::Context->dbh;
1170     # note biblioitems.* must be avoided to prevent large marc and marcxml fields from killing performance.
1171     my $query = "
1172     SELECT items.*,
1173            biblio.*,
1174            biblioitems.volume,
1175            biblioitems.number,
1176            biblioitems.itemtype,
1177            biblioitems.isbn,
1178            biblioitems.issn,
1179            biblioitems.publicationyear,
1180            biblioitems.publishercode,
1181            biblioitems.volumedate,
1182            biblioitems.volumedesc,
1183            biblioitems.lccn,
1184            biblioitems.url,
1185            items.notforloan as itemnotforloan,
1186            itemtypes.description,
1187            itemtypes.notforloan as notforloan_per_itemtype,
1188            branchurl
1189      FROM items
1190      LEFT JOIN branches ON items.holdingbranch = branches.branchcode
1191      LEFT JOIN biblio      ON      biblio.biblionumber     = items.biblionumber
1192      LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber
1193      LEFT JOIN itemtypes   ON   itemtypes.itemtype         = "
1194      . (C4::Context->preference('item-level_itypes') ? 'items.itype' : 'biblioitems.itemtype');
1195     $query .= " WHERE items.biblionumber = ? ORDER BY branches.branchname,items.dateaccessioned desc" ;
1196     my $sth = $dbh->prepare($query);
1197     $sth->execute($biblionumber);
1198     my $i = 0;
1199     my @results;
1200     my $serial;
1201
1202     my $isth    = $dbh->prepare(
1203         "SELECT issues.*,borrowers.cardnumber,borrowers.surname,borrowers.firstname,borrowers.branchcode as bcode
1204         FROM   issues LEFT JOIN borrowers ON issues.borrowernumber=borrowers.borrowernumber
1205         WHERE  itemnumber = ?"
1206        );
1207         my $ssth = $dbh->prepare("SELECT serialseq,publisheddate from serialitems left join serial on serialitems.serialid=serial.serialid where serialitems.itemnumber=? "); 
1208         while ( my $data = $sth->fetchrow_hashref ) {
1209         my $datedue = '';
1210         my $count_reserves;
1211         $isth->execute( $data->{'itemnumber'} );
1212         if ( my $idata = $isth->fetchrow_hashref ) {
1213             $data->{borrowernumber} = $idata->{borrowernumber};
1214             $data->{cardnumber}     = $idata->{cardnumber};
1215             $data->{surname}     = $idata->{surname};
1216             $data->{firstname}     = $idata->{firstname};
1217             $datedue                = $idata->{'date_due'};
1218         if (C4::Context->preference("IndependantBranches")){
1219         my $userenv = C4::Context->userenv;
1220         if ( ($userenv) && ( $userenv->{flags} % 2 != 1 ) ) { 
1221             $data->{'NOTSAMEBRANCH'} = 1 if ($idata->{'bcode'} ne $userenv->{branch});
1222         }
1223         }
1224         }
1225                 if ( $data->{'serial'}) {       
1226                         $ssth->execute($data->{'itemnumber'}) ;
1227                         ($data->{'serialseq'} , $data->{'publisheddate'}) = $ssth->fetchrow_array();
1228                         $serial = 1;
1229         }
1230                 if ( $datedue eq '' ) {
1231             my ( $restype, $reserves ) =
1232               C4::Reserves::CheckReserves( $data->{'itemnumber'} );
1233 # Previous conditional check with if ($restype) is not needed because a true
1234 # result for one item will result in subsequent items defaulting to this true
1235 # value.
1236             $count_reserves = $restype;
1237         }
1238         #get branch information.....
1239         my $bsth = $dbh->prepare(
1240             "SELECT * FROM branches WHERE branchcode = ?
1241         "
1242         );
1243         $bsth->execute( $data->{'holdingbranch'} );
1244         if ( my $bdata = $bsth->fetchrow_hashref ) {
1245             $data->{'branchname'} = $bdata->{'branchname'};
1246         }
1247         $data->{'datedue'}        = $datedue;
1248         $data->{'count_reserves'} = $count_reserves;
1249
1250         # get notforloan complete status if applicable
1251         my $sthnflstatus = $dbh->prepare(
1252             'SELECT authorised_value
1253             FROM   marc_subfield_structure
1254             WHERE  kohafield="items.notforloan"
1255         '
1256         );
1257
1258         $sthnflstatus->execute;
1259         my ($authorised_valuecode) = $sthnflstatus->fetchrow;
1260         if ($authorised_valuecode) {
1261             $sthnflstatus = $dbh->prepare(
1262                 "SELECT lib FROM authorised_values
1263                  WHERE  category=?
1264                  AND authorised_value=?"
1265             );
1266             $sthnflstatus->execute( $authorised_valuecode,
1267                 $data->{itemnotforloan} );
1268             my ($lib) = $sthnflstatus->fetchrow;
1269             $data->{notforloanvalue} = $lib;
1270         }
1271
1272         # get restricted status and description if applicable
1273         my $restrictedstatus = $dbh->prepare(
1274             'SELECT authorised_value
1275             FROM   marc_subfield_structure
1276             WHERE  kohafield="items.restricted"
1277         '
1278         );
1279
1280         $restrictedstatus->execute;
1281         ($authorised_valuecode) = $restrictedstatus->fetchrow;
1282         if ($authorised_valuecode) {
1283             $restrictedstatus = $dbh->prepare(
1284                 "SELECT lib,lib_opac FROM authorised_values
1285                  WHERE  category=?
1286                  AND authorised_value=?"
1287             );
1288             $restrictedstatus->execute( $authorised_valuecode,
1289                 $data->{restricted} );
1290
1291             if ( my $rstdata = $restrictedstatus->fetchrow_hashref ) {
1292                 $data->{restricted} = $rstdata->{'lib'};
1293                 $data->{restrictedopac} = $rstdata->{'lib_opac'};
1294             }
1295         }
1296
1297         # my stack procedures
1298         my $stackstatus = $dbh->prepare(
1299             'SELECT authorised_value
1300              FROM   marc_subfield_structure
1301              WHERE  kohafield="items.stack"
1302         '
1303         );
1304         $stackstatus->execute;
1305
1306         ($authorised_valuecode) = $stackstatus->fetchrow;
1307         if ($authorised_valuecode) {
1308             $stackstatus = $dbh->prepare(
1309                 "SELECT lib
1310                  FROM   authorised_values
1311                  WHERE  category=?
1312                  AND    authorised_value=?
1313             "
1314             );
1315             $stackstatus->execute( $authorised_valuecode, $data->{stack} );
1316             my ($lib) = $stackstatus->fetchrow;
1317             $data->{stack} = $lib;
1318         }
1319         # Find the last 3 people who borrowed this item.
1320         my $sth2 = $dbh->prepare("SELECT * FROM old_issues,borrowers
1321                                     WHERE itemnumber = ?
1322                                     AND old_issues.borrowernumber = borrowers.borrowernumber
1323                                     ORDER BY returndate DESC
1324                                     LIMIT 3");
1325         $sth2->execute($data->{'itemnumber'});
1326         my $ii = 0;
1327         while (my $data2 = $sth2->fetchrow_hashref()) {
1328             $data->{"timestamp$ii"} = $data2->{'timestamp'} if $data2->{'timestamp'};
1329             $data->{"card$ii"}      = $data2->{'cardnumber'} if $data2->{'cardnumber'};
1330             $data->{"borrower$ii"}  = $data2->{'borrowernumber'} if $data2->{'borrowernumber'};
1331             $ii++;
1332         }
1333
1334         $results[$i] = $data;
1335         $i++;
1336     }
1337         if($serial) {
1338                 return( sort { ($b->{'publisheddate'} || $b->{'enumchron'}) cmp ($a->{'publisheddate'} || $a->{'enumchron'}) } @results );
1339         } else {
1340         return (@results);
1341         }
1342 }
1343
1344 =head2 GetItemsLocationInfo
1345
1346   my @itemlocinfo = GetItemsLocationInfo($biblionumber);
1347
1348 Returns the branch names, shelving location and itemcallnumber for each item attached to the biblio in question
1349
1350 C<GetItemsInfo> returns a list of references-to-hash. Data returned:
1351
1352 =over 2
1353
1354 =item C<$data-E<gt>{homebranch}>
1355
1356 Branch Name of the item's homebranch
1357
1358 =item C<$data-E<gt>{holdingbranch}>
1359
1360 Branch Name of the item's holdingbranch
1361
1362 =item C<$data-E<gt>{location}>
1363
1364 Item's shelving location code
1365
1366 =item C<$data-E<gt>{location_intranet}>
1367
1368 The intranet description for the Shelving Location as set in authorised_values 'LOC'
1369
1370 =item C<$data-E<gt>{location_opac}>
1371
1372 The OPAC description for the Shelving Location as set in authorised_values 'LOC'.  Falls back to intranet description if no OPAC 
1373 description is set.
1374
1375 =item C<$data-E<gt>{itemcallnumber}>
1376
1377 Item's itemcallnumber
1378
1379 =item C<$data-E<gt>{cn_sort}>
1380
1381 Item's call number normalized for sorting
1382
1383 =back
1384   
1385 =cut
1386
1387 sub GetItemsLocationInfo {
1388         my $biblionumber = shift;
1389         my @results;
1390
1391         my $dbh = C4::Context->dbh;
1392         my $query = "SELECT a.branchname as homebranch, b.branchname as holdingbranch, 
1393                             location, itemcallnumber, cn_sort
1394                      FROM items, branches as a, branches as b
1395                      WHERE homebranch = a.branchcode AND holdingbranch = b.branchcode 
1396                      AND biblionumber = ?
1397                      ORDER BY cn_sort ASC";
1398         my $sth = $dbh->prepare($query);
1399         $sth->execute($biblionumber);
1400
1401         while ( my $data = $sth->fetchrow_hashref ) {
1402              $data->{location_intranet} = GetKohaAuthorisedValueLib('LOC', $data->{location});
1403              $data->{location_opac}= GetKohaAuthorisedValueLib('LOC', $data->{location}, 1);
1404              push @results, $data;
1405         }
1406         return @results;
1407 }
1408
1409 =head2 GetHostItemsInfo
1410
1411         $hostiteminfo = GetHostItemsInfo($hostfield);
1412         Returns the iteminfo for items linked to records via a host field
1413
1414 =cut
1415
1416 sub GetHostItemsInfo {
1417         my ($record) = @_;
1418         my @returnitemsInfo;
1419
1420         if (C4::Context->preference('marcflavour') eq 'MARC21' ||
1421         C4::Context->preference('marcflavour') eq 'NORMARC'){
1422             foreach my $hostfield ( $record->field('773') ) {
1423                 my $hostbiblionumber = $hostfield->subfield("0");
1424                 my $linkeditemnumber = $hostfield->subfield("9");
1425                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1426                 foreach my $hostitemInfo (@hostitemInfos){
1427                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1428                                 push (@returnitemsInfo,$hostitemInfo);
1429                                 last;
1430                         }
1431                 }
1432             }
1433         } elsif ( C4::Context->preference('marcflavour') eq 'UNIMARC'){
1434             foreach my $hostfield ( $record->field('461') ) {
1435                 my $hostbiblionumber = $hostfield->subfield("0");
1436                 my $linkeditemnumber = $hostfield->subfield("9");
1437                 my @hostitemInfos = GetItemsInfo($hostbiblionumber);
1438                 foreach my $hostitemInfo (@hostitemInfos){
1439                         if ($hostitemInfo->{itemnumber} eq $linkeditemnumber){
1440                                 push (@returnitemsInfo,$hostitemInfo);
1441                                 last;
1442                         }
1443                 }
1444             }
1445         }
1446         return @returnitemsInfo;
1447 }
1448
1449
1450 =head2 GetLastAcquisitions
1451
1452   my $lastacq = GetLastAcquisitions({'branches' => ('branch1','branch2'), 
1453                                     'itemtypes' => ('BK','BD')}, 10);
1454
1455 =cut
1456
1457 sub  GetLastAcquisitions {
1458         my ($data,$max) = @_;
1459
1460         my $itemtype = C4::Context->preference('item-level_itypes') ? 'itype' : 'itemtype';
1461         
1462         my $number_of_branches = @{$data->{branches}};
1463         my $number_of_itemtypes   = @{$data->{itemtypes}};
1464         
1465         
1466         my @where = ('WHERE 1 '); 
1467         $number_of_branches and push @where
1468            , 'AND holdingbranch IN (' 
1469            , join(',', ('?') x $number_of_branches )
1470            , ')'
1471          ;
1472         
1473         $number_of_itemtypes and push @where
1474            , "AND $itemtype IN (" 
1475            , join(',', ('?') x $number_of_itemtypes )
1476            , ')'
1477          ;
1478
1479         my $query = "SELECT biblio.biblionumber as biblionumber, title, dateaccessioned
1480                                  FROM items RIGHT JOIN biblio ON (items.biblionumber=biblio.biblionumber) 
1481                                     RIGHT JOIN biblioitems ON (items.biblioitemnumber=biblioitems.biblioitemnumber)
1482                                     @where
1483                                     GROUP BY biblio.biblionumber 
1484                                     ORDER BY dateaccessioned DESC LIMIT $max";
1485
1486         my $dbh = C4::Context->dbh;
1487         my $sth = $dbh->prepare($query);
1488     
1489     $sth->execute((@{$data->{branches}}, @{$data->{itemtypes}}));
1490         
1491         my @results;
1492         while( my $row = $sth->fetchrow_hashref){
1493                 push @results, {date => $row->{dateaccessioned} 
1494                                                 , biblionumber => $row->{biblionumber}
1495                                                 , title => $row->{title}};
1496         }
1497         
1498         return @results;
1499 }
1500
1501 =head2 GetItemnumberForBiblio
1502
1503   my @itemnumbers = GetItemnumbersForBiblio($biblionumber);
1504
1505 Given a single biblionumber, return an array of all the corresponding itemnumbers
1506
1507 =cut
1508
1509 sub GetItemnumbersForBiblio {
1510     my $biblionumber = shift;
1511     my @items;
1512     my $dbh = C4::Context->dbh;
1513     my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber = ?");
1514     $sth->execute($biblionumber);
1515     while (my $result = $sth->fetchrow_hashref) {
1516         push @items, $result->{'itemnumber'};
1517     }
1518     return \@items;
1519 }
1520
1521 =head2 get_itemnumbers_of
1522
1523   my @itemnumbers_of = get_itemnumbers_of(@biblionumbers);
1524
1525 Given a list of biblionumbers, return the list of corresponding itemnumbers
1526 for each biblionumber.
1527
1528 Return a reference on a hash where keys are biblionumbers and values are
1529 references on array of itemnumbers.
1530
1531 =cut
1532
1533 sub get_itemnumbers_of {
1534     my @biblionumbers = @_;
1535
1536     my $dbh = C4::Context->dbh;
1537
1538     my $query = '
1539         SELECT itemnumber,
1540             biblionumber
1541         FROM items
1542         WHERE biblionumber IN (?' . ( ',?' x scalar @biblionumbers - 1 ) . ')
1543     ';
1544     my $sth = $dbh->prepare($query);
1545     $sth->execute(@biblionumbers);
1546
1547     my %itemnumbers_of;
1548
1549     while ( my ( $itemnumber, $biblionumber ) = $sth->fetchrow_array ) {
1550         push @{ $itemnumbers_of{$biblionumber} }, $itemnumber;
1551     }
1552
1553     return \%itemnumbers_of;
1554 }
1555
1556 =head2 get_hostitemnumbers_of
1557
1558   my @itemnumbers_of = get_hostitemnumbers_of($biblionumber);
1559
1560 Given a biblionumber, return the list of corresponding itemnumbers that are linked to it via host fields
1561
1562 Return a reference on a hash where key is a biblionumber and values are
1563 references on array of itemnumbers.
1564
1565 =cut
1566
1567
1568 sub get_hostitemnumbers_of {
1569         my ($biblionumber) = @_;
1570         my $marcrecord = GetMarcBiblio($biblionumber);
1571         my (@returnhostitemnumbers,$tag, $biblio_s, $item_s);
1572         
1573         my $marcflavor = C4::Context->preference('marcflavour');
1574         if ($marcflavor eq 'MARC21' || $marcflavor eq 'NORMARC') {
1575         $tag='773';
1576         $biblio_s='0';
1577         $item_s='9';
1578     } elsif ($marcflavor eq 'UNIMARC') {
1579         $tag='461';
1580         $biblio_s='0';
1581         $item_s='9';
1582     }
1583
1584     foreach my $hostfield ( $marcrecord->field($tag) ) {
1585         my $hostbiblionumber = $hostfield->subfield($biblio_s);
1586         my $linkeditemnumber = $hostfield->subfield($item_s);
1587         my @itemnumbers;
1588         if (my $itemnumbers = get_itemnumbers_of($hostbiblionumber)->{$hostbiblionumber})
1589         {
1590             @itemnumbers = @$itemnumbers;
1591         }
1592         foreach my $itemnumber (@itemnumbers){
1593             if ($itemnumber eq $linkeditemnumber){
1594                 push (@returnhostitemnumbers,$itemnumber);
1595                 last;
1596             }
1597         }
1598     }
1599     return @returnhostitemnumbers;
1600 }
1601
1602
1603 =head2 GetItemnumberFromBarcode
1604
1605   $result = GetItemnumberFromBarcode($barcode);
1606
1607 =cut
1608
1609 sub GetItemnumberFromBarcode {
1610     my ($barcode) = @_;
1611     my $dbh = C4::Context->dbh;
1612
1613     my $rq =
1614       $dbh->prepare("SELECT itemnumber FROM items WHERE items.barcode=?");
1615     $rq->execute($barcode);
1616     my ($result) = $rq->fetchrow;
1617     return ($result);
1618 }
1619
1620 =head2 GetBarcodeFromItemnumber
1621
1622   $result = GetBarcodeFromItemnumber($itemnumber);
1623
1624 =cut
1625
1626 sub GetBarcodeFromItemnumber {
1627     my ($itemnumber) = @_;
1628     my $dbh = C4::Context->dbh;
1629
1630     my $rq =
1631       $dbh->prepare("SELECT barcode FROM items WHERE items.itemnumber=?");
1632     $rq->execute($itemnumber);
1633     my ($result) = $rq->fetchrow;
1634     return ($result);
1635 }
1636
1637 =head2 GetHiddenItemnumbers
1638
1639 =over 4
1640
1641 $result = GetHiddenItemnumbers(@items);
1642
1643 =back
1644
1645 =cut
1646
1647 sub GetHiddenItemnumbers {
1648     my (@items) = @_;
1649     my @resultitems;
1650
1651     my $yaml = C4::Context->preference('OpacHiddenItems');
1652     my $hidingrules;
1653     eval {
1654         $hidingrules = YAML::Load($yaml);
1655     };
1656     if ($@) {
1657         warn "Unable to parse OpacHiddenItems syspref : $@";
1658         return ();
1659     } else {
1660     my $dbh = C4::Context->dbh;
1661
1662         # For each item
1663         foreach my $item (@items) {
1664
1665             # We check each rule
1666             foreach my $field (keys %$hidingrules) {
1667                 my $query = "SELECT $field from items where itemnumber = ?";
1668                 my $sth = $dbh->prepare($query);        
1669                 $sth->execute($item->{'itemnumber'});
1670                 my ($result) = $sth->fetchrow;
1671
1672                 # If the results matches the values in the yaml file
1673                 if (any { $result eq $_ } @{$hidingrules->{$field}}) {
1674
1675                     # We add the itemnumber to the list
1676                     push @resultitems, $item->{'itemnumber'};       
1677
1678                     # If at least one rule matched for an item, no need to test the others
1679                     last;
1680                 }
1681             }
1682         }
1683         return @resultitems;
1684     }
1685
1686  }
1687
1688 =head3 get_item_authorised_values
1689
1690 find the types and values for all authorised values assigned to this item.
1691
1692 parameters: itemnumber
1693
1694 returns: a hashref malling the authorised value to the value set for this itemnumber
1695
1696     $authorised_values = {
1697              'CCODE'      => undef,
1698              'DAMAGED'    => '0',
1699              'LOC'        => '3',
1700              'LOST'       => '0'
1701              'NOT_LOAN'   => '0',
1702              'RESTRICTED' => undef,
1703              'STACK'      => undef,
1704              'WITHDRAWN'  => '0',
1705              'branches'   => 'CPL',
1706              'cn_source'  => undef,
1707              'itemtypes'  => 'SER',
1708            };
1709
1710 Notes: see C4::Biblio::get_biblio_authorised_values for a similar method at the biblio level.
1711
1712 =cut
1713
1714 sub get_item_authorised_values {
1715     my $itemnumber = shift;
1716
1717     # assume that these entries in the authorised_value table are item level.
1718     my $query = q(SELECT distinct authorised_value, kohafield
1719                     FROM marc_subfield_structure
1720                     WHERE kohafield like 'item%'
1721                       AND authorised_value != '' );
1722
1723     my $itemlevel_authorised_values = C4::Context->dbh->selectall_hashref( $query, 'authorised_value' );
1724     my $iteminfo = GetItem( $itemnumber );
1725     # warn( Data::Dumper->Dump( [ $itemlevel_authorised_values ], [ 'itemlevel_authorised_values' ] ) );
1726     my $return;
1727     foreach my $this_authorised_value ( keys %$itemlevel_authorised_values ) {
1728         my $field = $itemlevel_authorised_values->{ $this_authorised_value }->{'kohafield'};
1729         $field =~ s/^items\.//;
1730         if ( exists $iteminfo->{ $field } ) {
1731             $return->{ $this_authorised_value } = $iteminfo->{ $field };
1732         }
1733     }
1734     # warn( Data::Dumper->Dump( [ $return ], [ 'return' ] ) );
1735     return $return;
1736 }
1737
1738 =head3 get_authorised_value_images
1739
1740 find a list of icons that are appropriate for display based on the
1741 authorised values for a biblio.
1742
1743 parameters: listref of authorised values, such as comes from
1744 get_item_authorised_values or
1745 from C4::Biblio::get_biblio_authorised_values
1746
1747 returns: listref of hashrefs for each image. Each hashref looks like this:
1748
1749       { imageurl => '/intranet-tmpl/prog/img/itemtypeimg/npl/WEB.gif',
1750         label    => '',
1751         category => '',
1752         value    => '', }
1753
1754 Notes: Currently, I put on the full path to the images on the staff
1755 side. This should either be configurable or not done at all. Since I
1756 have to deal with 'intranet' or 'opac' in
1757 get_biblio_authorised_values, perhaps I should be passing it in.
1758
1759 =cut
1760
1761 sub get_authorised_value_images {
1762     my $authorised_values = shift;
1763
1764     my @imagelist;
1765
1766     my $authorised_value_list = GetAuthorisedValues();
1767     # warn ( Data::Dumper->Dump( [ $authorised_value_list ], [ 'authorised_value_list' ] ) );
1768     foreach my $this_authorised_value ( @$authorised_value_list ) {
1769         if ( exists $authorised_values->{ $this_authorised_value->{'category'} }
1770              && $authorised_values->{ $this_authorised_value->{'category'} } eq $this_authorised_value->{'authorised_value'} ) {
1771             # warn ( Data::Dumper->Dump( [ $this_authorised_value ], [ 'this_authorised_value' ] ) );
1772             if ( defined $this_authorised_value->{'imageurl'} ) {
1773                 push @imagelist, { imageurl => C4::Koha::getitemtypeimagelocation( 'intranet', $this_authorised_value->{'imageurl'} ),
1774                                    label    => $this_authorised_value->{'lib'},
1775                                    category => $this_authorised_value->{'category'},
1776                                    value    => $this_authorised_value->{'authorised_value'}, };
1777             }
1778         }
1779     }
1780
1781     # warn ( Data::Dumper->Dump( [ \@imagelist ], [ 'imagelist' ] ) );
1782     return \@imagelist;
1783
1784 }
1785
1786 =head1 LIMITED USE FUNCTIONS
1787
1788 The following functions, while part of the public API,
1789 are not exported.  This is generally because they are
1790 meant to be used by only one script for a specific
1791 purpose, and should not be used in any other context
1792 without careful thought.
1793
1794 =cut
1795
1796 =head2 GetMarcItem
1797
1798   my $item_marc = GetMarcItem($biblionumber, $itemnumber);
1799
1800 Returns MARC::Record of the item passed in parameter.
1801 This function is meant for use only in C<cataloguing/additem.pl>,
1802 where it is needed to support that script's MARC-like
1803 editor.
1804
1805 =cut
1806
1807 sub GetMarcItem {
1808     my ( $biblionumber, $itemnumber ) = @_;
1809
1810     # GetMarcItem has been revised so that it does the following:
1811     #  1. Gets the item information from the items table.
1812     #  2. Converts it to a MARC field for storage in the bib record.
1813     #
1814     # The previous behavior was:
1815     #  1. Get the bib record.
1816     #  2. Return the MARC tag corresponding to the item record.
1817     #
1818     # The difference is that one treats the items row as authoritative,
1819     # while the other treats the MARC representation as authoritative
1820     # under certain circumstances.
1821
1822     my $itemrecord = GetItem($itemnumber);
1823
1824     # Tack on 'items.' prefix to column names so that TransformKohaToMarc will work.
1825     # Also, don't emit a subfield if the underlying field is blank.
1826
1827     
1828     return Item2Marc($itemrecord,$biblionumber);
1829
1830 }
1831 sub Item2Marc {
1832         my ($itemrecord,$biblionumber)=@_;
1833     my $mungeditem = { 
1834         map {  
1835             defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : ()  
1836         } keys %{ $itemrecord } 
1837     };
1838     my $itemmarc = TransformKohaToMarc($mungeditem);
1839     my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber",GetFrameworkCode($biblionumber)||'');
1840
1841     my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'});
1842     if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) {
1843                 foreach my $field ($itemmarc->field($itemtag)){
1844             $field->add_subfields(@$unlinked_item_subfields);
1845         }
1846     }
1847         return $itemmarc;
1848 }
1849
1850 =head1 PRIVATE FUNCTIONS AND VARIABLES
1851
1852 The following functions are not meant to be called
1853 directly, but are documented in order to explain
1854 the inner workings of C<C4::Items>.
1855
1856 =cut
1857
1858 =head2 %derived_columns
1859
1860 This hash keeps track of item columns that
1861 are strictly derived from other columns in
1862 the item record and are not meant to be set
1863 independently.
1864
1865 Each key in the hash should be the name of a
1866 column (as named by TransformMarcToKoha).  Each
1867 value should be hashref whose keys are the
1868 columns on which the derived column depends.  The
1869 hashref should also contain a 'BUILDER' key
1870 that is a reference to a sub that calculates
1871 the derived value.
1872
1873 =cut
1874
1875 my %derived_columns = (
1876     'items.cn_sort' => {
1877         'itemcallnumber' => 1,
1878         'items.cn_source' => 1,
1879         'BUILDER' => \&_calc_items_cn_sort,
1880     }
1881 );
1882
1883 =head2 _set_derived_columns_for_add 
1884
1885   _set_derived_column_for_add($item);
1886
1887 Given an item hash representing a new item to be added,
1888 calculate any derived columns.  Currently the only
1889 such column is C<items.cn_sort>.
1890
1891 =cut
1892
1893 sub _set_derived_columns_for_add {
1894     my $item = shift;
1895
1896     foreach my $column (keys %derived_columns) {
1897         my $builder = $derived_columns{$column}->{'BUILDER'};
1898         my $source_values = {};
1899         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1900             next if $source_column eq 'BUILDER';
1901             $source_values->{$source_column} = $item->{$source_column};
1902         }
1903         $builder->($item, $source_values);
1904     }
1905 }
1906
1907 =head2 _set_derived_columns_for_mod 
1908
1909   _set_derived_column_for_mod($item);
1910
1911 Given an item hash representing a new item to be modified.
1912 calculate any derived columns.  Currently the only
1913 such column is C<items.cn_sort>.
1914
1915 This routine differs from C<_set_derived_columns_for_add>
1916 in that it needs to handle partial item records.  In other
1917 words, the caller of C<ModItem> may have supplied only one
1918 or two columns to be changed, so this function needs to
1919 determine whether any of the columns to be changed affect
1920 any of the derived columns.  Also, if a derived column
1921 depends on more than one column, but the caller is not
1922 changing all of then, this routine retrieves the unchanged
1923 values from the database in order to ensure a correct
1924 calculation.
1925
1926 =cut
1927
1928 sub _set_derived_columns_for_mod {
1929     my $item = shift;
1930
1931     foreach my $column (keys %derived_columns) {
1932         my $builder = $derived_columns{$column}->{'BUILDER'};
1933         my $source_values = {};
1934         my %missing_sources = ();
1935         my $must_recalc = 0;
1936         foreach my $source_column (keys %{ $derived_columns{$column} }) {
1937             next if $source_column eq 'BUILDER';
1938             if (exists $item->{$source_column}) {
1939                 $must_recalc = 1;
1940                 $source_values->{$source_column} = $item->{$source_column};
1941             } else {
1942                 $missing_sources{$source_column} = 1;
1943             }
1944         }
1945         if ($must_recalc) {
1946             foreach my $source_column (keys %missing_sources) {
1947                 $source_values->{$source_column} = _get_single_item_column($source_column, $item->{'itemnumber'});
1948             }
1949             $builder->($item, $source_values);
1950         }
1951     }
1952 }
1953
1954 =head2 _do_column_fixes_for_mod
1955
1956   _do_column_fixes_for_mod($item);
1957
1958 Given an item hashref containing one or more
1959 columns to modify, fix up certain values.
1960 Specifically, set to 0 any passed value
1961 of C<notforloan>, C<damaged>, C<itemlost>, or
1962 C<wthdrawn> that is either undefined or
1963 contains the empty string.
1964
1965 =cut
1966
1967 sub _do_column_fixes_for_mod {
1968     my $item = shift;
1969
1970     if (exists $item->{'notforloan'} and
1971         (not defined $item->{'notforloan'} or $item->{'notforloan'} eq '')) {
1972         $item->{'notforloan'} = 0;
1973     }
1974     if (exists $item->{'damaged'} and
1975         (not defined $item->{'damaged'} or $item->{'damaged'} eq '')) {
1976         $item->{'damaged'} = 0;
1977     }
1978     if (exists $item->{'itemlost'} and
1979         (not defined $item->{'itemlost'} or $item->{'itemlost'} eq '')) {
1980         $item->{'itemlost'} = 0;
1981     }
1982     if (exists $item->{'wthdrawn'} and
1983         (not defined $item->{'wthdrawn'} or $item->{'wthdrawn'} eq '')) {
1984         $item->{'wthdrawn'} = 0;
1985     }
1986     if (exists $item->{'location'} && !exists $item->{'permanent_location'}) {
1987         $item->{'permanent_location'} = $item->{'location'};
1988     }
1989     if (exists $item->{'timestamp'}) {
1990         delete $item->{'timestamp'};
1991     }
1992 }
1993
1994 =head2 _get_single_item_column
1995
1996   _get_single_item_column($column, $itemnumber);
1997
1998 Retrieves the value of a single column from an C<items>
1999 row specified by C<$itemnumber>.
2000
2001 =cut
2002
2003 sub _get_single_item_column {
2004     my $column = shift;
2005     my $itemnumber = shift;
2006     
2007     my $dbh = C4::Context->dbh;
2008     my $sth = $dbh->prepare("SELECT $column FROM items WHERE itemnumber = ?");
2009     $sth->execute($itemnumber);
2010     my ($value) = $sth->fetchrow();
2011     return $value; 
2012 }
2013
2014 =head2 _calc_items_cn_sort
2015
2016   _calc_items_cn_sort($item, $source_values);
2017
2018 Helper routine to calculate C<items.cn_sort>.
2019
2020 =cut
2021
2022 sub _calc_items_cn_sort {
2023     my $item = shift;
2024     my $source_values = shift;
2025
2026     $item->{'items.cn_sort'} = GetClassSort($source_values->{'items.cn_source'}, $source_values->{'itemcallnumber'}, "");
2027 }
2028
2029 =head2 _set_defaults_for_add 
2030
2031   _set_defaults_for_add($item_hash);
2032
2033 Given an item hash representing an item to be added, set
2034 correct default values for columns whose default value
2035 is not handled by the DBMS.  This includes the following
2036 columns:
2037
2038 =over 2
2039
2040 =item * 
2041
2042 C<items.dateaccessioned>
2043
2044 =item *
2045
2046 C<items.notforloan>
2047
2048 =item *
2049
2050 C<items.damaged>
2051
2052 =item *
2053
2054 C<items.itemlost>
2055
2056 =item *
2057
2058 C<items.wthdrawn>
2059
2060 =back
2061
2062 =cut
2063
2064 sub _set_defaults_for_add {
2065     my $item = shift;
2066     $item->{dateaccessioned} ||= C4::Dates->new->output('iso');
2067     $item->{$_} ||= 0 for (qw( notforloan damaged itemlost wthdrawn));
2068 }
2069
2070 =head2 _koha_new_item
2071
2072   my ($itemnumber,$error) = _koha_new_item( $item, $barcode );
2073
2074 Perform the actual insert into the C<items> table.
2075
2076 =cut
2077
2078 sub _koha_new_item {
2079     my ( $item, $barcode ) = @_;
2080     my $dbh=C4::Context->dbh;  
2081     my $error;
2082     my $query =
2083            "INSERT INTO items SET
2084             biblionumber        = ?,
2085             biblioitemnumber    = ?,
2086             barcode             = ?,
2087             dateaccessioned     = ?,
2088             booksellerid        = ?,
2089             homebranch          = ?,
2090             price               = ?,
2091             replacementprice    = ?,
2092             replacementpricedate = ?,
2093             datelastborrowed    = ?,
2094             datelastseen        = ?,
2095             stack               = ?,
2096             notforloan          = ?,
2097             damaged             = ?,
2098             itemlost            = ?,
2099             wthdrawn            = ?,
2100             itemcallnumber      = ?,
2101             restricted          = ?,
2102             itemnotes           = ?,
2103             holdingbranch       = ?,
2104             paidfor             = ?,
2105             location            = ?,
2106             permanent_location            = ?,
2107             onloan              = ?,
2108             issues              = ?,
2109             renewals            = ?,
2110             reserves            = ?,
2111             cn_source           = ?,
2112             cn_sort             = ?,
2113             ccode               = ?,
2114             itype               = ?,
2115             materials           = ?,
2116             uri = ?,
2117             enumchron           = ?,
2118             more_subfields_xml  = ?,
2119             copynumber          = ?,
2120             stocknumber         = ?
2121           ";
2122     my $sth = $dbh->prepare($query);
2123     my $today = C4::Dates->today('iso');
2124    $sth->execute(
2125             $item->{'biblionumber'},
2126             $item->{'biblioitemnumber'},
2127             $barcode,
2128             $item->{'dateaccessioned'},
2129             $item->{'booksellerid'},
2130             $item->{'homebranch'},
2131             $item->{'price'},
2132             $item->{'replacementprice'},
2133             $item->{'replacementpricedate'} || $today,
2134             $item->{datelastborrowed},
2135             $item->{datelastseen} || $today,
2136             $item->{stack},
2137             $item->{'notforloan'},
2138             $item->{'damaged'},
2139             $item->{'itemlost'},
2140             $item->{'wthdrawn'},
2141             $item->{'itemcallnumber'},
2142             $item->{'restricted'},
2143             $item->{'itemnotes'},
2144             $item->{'holdingbranch'},
2145             $item->{'paidfor'},
2146             $item->{'location'},
2147             $item->{'permanent_location'},
2148             $item->{'onloan'},
2149             $item->{'issues'},
2150             $item->{'renewals'},
2151             $item->{'reserves'},
2152             $item->{'items.cn_source'},
2153             $item->{'items.cn_sort'},
2154             $item->{'ccode'},
2155             $item->{'itype'},
2156             $item->{'materials'},
2157             $item->{'uri'},
2158             $item->{'enumchron'},
2159             $item->{'more_subfields_xml'},
2160             $item->{'copynumber'},
2161             $item->{'stocknumber'},
2162     );
2163     my $itemnumber = $dbh->{'mysql_insertid'};
2164     if ( defined $sth->errstr ) {
2165         $error.="ERROR in _koha_new_item $query".$sth->errstr;
2166     }
2167     return ( $itemnumber, $error );
2168 }
2169
2170 =head2 MoveItemFromBiblio
2171
2172   MoveItemFromBiblio($itenumber, $frombiblio, $tobiblio);
2173
2174 Moves an item from a biblio to another
2175
2176 Returns undef if the move failed or the biblionumber of the destination record otherwise
2177
2178 =cut
2179
2180 sub MoveItemFromBiblio {
2181     my ($itemnumber, $frombiblio, $tobiblio) = @_;
2182     my $dbh = C4::Context->dbh;
2183     my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = ?");
2184     $sth->execute( $tobiblio );
2185     my ( $tobiblioitem ) = $sth->fetchrow();
2186     $sth = $dbh->prepare("UPDATE items SET biblioitemnumber = ?, biblionumber = ? WHERE itemnumber = ? AND biblionumber = ?");
2187     my $return = $sth->execute($tobiblioitem, $tobiblio, $itemnumber, $frombiblio);
2188     if ($return == 1) {
2189         ModZebra( $tobiblio, "specialUpdate", "biblioserver", undef, undef );
2190         ModZebra( $frombiblio, "specialUpdate", "biblioserver", undef, undef );
2191             # Checking if the item we want to move is in an order 
2192         my $order = GetOrderFromItemnumber($itemnumber);
2193             if ($order) {
2194                     # Replacing the biblionumber within the order if necessary
2195                     $order->{'biblionumber'} = $tobiblio;
2196                 ModOrder($order);
2197             }
2198         return $tobiblio;
2199         }
2200     return;
2201 }
2202
2203 =head2 DelItemCheck
2204
2205    DelItemCheck($dbh, $biblionumber, $itemnumber);
2206
2207 Exported function (core API) for deleting an item record in Koha if there no current issue.
2208
2209 =cut
2210
2211 sub DelItemCheck {
2212     my ( $dbh, $biblionumber, $itemnumber ) = @_;
2213     my $error;
2214
2215         my $countanalytics=GetAnalyticsCount($itemnumber);
2216
2217
2218     # check that there is no issue on this item before deletion.
2219     my $sth=$dbh->prepare("select * from issues i where i.itemnumber=?");
2220     $sth->execute($itemnumber);
2221
2222     my $item = GetItem($itemnumber);
2223     my $onloan=$sth->fetchrow;
2224
2225     if ($onloan){
2226         $error = "book_on_loan" 
2227     }
2228     elsif ( C4::Context->userenv->{flags} & 1 and
2229             C4::Context->preference("IndependantBranches") and
2230            (C4::Context->userenv->{branch} ne
2231              $item->{C4::Context->preference("HomeOrHoldingBranch")||'homebranch'}) )
2232     {
2233         $error = "not_same_branch";
2234     }
2235         else{
2236         # check it doesnt have a waiting reserve
2237         $sth=$dbh->prepare("SELECT * FROM reserves WHERE (found = 'W' or found = 'T') AND itemnumber = ?");
2238         $sth->execute($itemnumber);
2239         my $reserve=$sth->fetchrow;
2240         if ($reserve){
2241             $error = "book_reserved";
2242         } elsif ($countanalytics > 0){
2243                 $error = "linked_analytics";
2244         } else {
2245             DelItem($dbh, $biblionumber, $itemnumber);
2246             return 1;
2247         }
2248     }
2249     return $error;
2250 }
2251
2252 =head2 _koha_modify_item
2253
2254   my ($itemnumber,$error) =_koha_modify_item( $item );
2255
2256 Perform the actual update of the C<items> row.  Note that this
2257 routine accepts a hashref specifying the columns to update.
2258
2259 =cut
2260
2261 sub _koha_modify_item {
2262     my ( $item ) = @_;
2263     my $dbh=C4::Context->dbh;  
2264     my $error;
2265
2266     my $query = "UPDATE items SET ";
2267     my @bind;
2268     for my $key ( keys %$item ) {
2269         $query.="$key=?,";
2270         push @bind, $item->{$key};
2271     }
2272     $query =~ s/,$//;
2273     $query .= " WHERE itemnumber=?";
2274     push @bind, $item->{'itemnumber'};
2275     my $sth = C4::Context->dbh->prepare($query);
2276     $sth->execute(@bind);
2277     if ( C4::Context->dbh->errstr ) {
2278         $error.="ERROR in _koha_modify_item $query".$dbh->errstr;
2279         warn $error;
2280     }
2281     return ($item->{'itemnumber'},$error);
2282 }
2283
2284 =head2 _koha_delete_item
2285
2286   _koha_delete_item( $dbh, $itemnum );
2287
2288 Internal function to delete an item record from the koha tables
2289
2290 =cut
2291
2292 sub _koha_delete_item {
2293     my ( $dbh, $itemnum ) = @_;
2294
2295     # save the deleted item to deleteditems table
2296     my $sth = $dbh->prepare("SELECT * FROM items WHERE itemnumber=?");
2297     $sth->execute($itemnum);
2298     my $data = $sth->fetchrow_hashref();
2299     my $query = "INSERT INTO deleteditems SET ";
2300     my @bind  = ();
2301     foreach my $key ( keys %$data ) {
2302         $query .= "$key = ?,";
2303         push( @bind, $data->{$key} );
2304     }
2305     $query =~ s/\,$//;
2306     $sth = $dbh->prepare($query);
2307     $sth->execute(@bind);
2308
2309     # delete from items table
2310     $sth = $dbh->prepare("DELETE FROM items WHERE itemnumber=?");
2311     $sth->execute($itemnum);
2312     return undef;
2313 }
2314
2315 =head2 _marc_from_item_hash
2316
2317   my $item_marc = _marc_from_item_hash($item, $frameworkcode[, $unlinked_item_subfields]);
2318
2319 Given an item hash representing a complete item record,
2320 create a C<MARC::Record> object containing an embedded
2321 tag representing that item.
2322
2323 The third, optional parameter C<$unlinked_item_subfields> is
2324 an arrayref of subfields (not mapped to C<items> fields per the
2325 framework) to be added to the MARC representation
2326 of the item.
2327
2328 =cut
2329
2330 sub _marc_from_item_hash {
2331     my $item = shift;
2332     my $frameworkcode = shift;
2333     my $unlinked_item_subfields;
2334     if (@_) {
2335         $unlinked_item_subfields = shift;
2336     }
2337    
2338     # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work
2339     # Also, don't emit a subfield if the underlying field is blank.
2340     my $mungeditem = { map {  (defined($item->{$_}) and $item->{$_} ne '') ? 
2341                                 (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) 
2342                                 : ()  } keys %{ $item } }; 
2343
2344     my $item_marc = MARC::Record->new();
2345     foreach my $item_field ( keys %{$mungeditem} ) {
2346         my ( $tag, $subfield ) = GetMarcFromKohaField( $item_field, $frameworkcode );
2347         next unless defined $tag and defined $subfield;    # skip if not mapped to MARC field
2348         my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1);
2349         foreach my $value (@values){
2350             if ( my $field = $item_marc->field($tag) ) {
2351                     $field->add_subfields( $subfield => $value );
2352             } else {
2353                 my $add_subfields = [];
2354                 if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2355                     $add_subfields = $unlinked_item_subfields;
2356             }
2357             $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields );
2358             }
2359         }
2360     }
2361
2362     return $item_marc;
2363 }
2364
2365 =head2 _repack_item_errors
2366
2367 Add an error message hash generated by C<CheckItemPreSave>
2368 to a list of errors.
2369
2370 =cut
2371
2372 sub _repack_item_errors {
2373     my $item_sequence_num = shift;
2374     my $item_ref = shift;
2375     my $error_ref = shift;
2376
2377     my @repacked_errors = ();
2378
2379     foreach my $error_code (sort keys %{ $error_ref }) {
2380         my $repacked_error = {};
2381         $repacked_error->{'item_sequence'} = $item_sequence_num;
2382         $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : '';
2383         $repacked_error->{'error_code'} = $error_code;
2384         $repacked_error->{'error_information'} = $error_ref->{$error_code};
2385         push @repacked_errors, $repacked_error;
2386     } 
2387
2388     return @repacked_errors;
2389 }
2390
2391 =head2 _get_unlinked_item_subfields
2392
2393   my $unlinked_item_subfields = _get_unlinked_item_subfields($original_item_marc, $frameworkcode);
2394
2395 =cut
2396
2397 sub _get_unlinked_item_subfields {
2398     my $original_item_marc = shift;
2399     my $frameworkcode = shift;
2400
2401     my $marcstructure = GetMarcStructure(1, $frameworkcode);
2402
2403     # assume that this record has only one field, and that that
2404     # field contains only the item information
2405     my $subfields = [];
2406     my @fields = $original_item_marc->fields();
2407     if ($#fields > -1) {
2408         my $field = $fields[0];
2409             my $tag = $field->tag();
2410         foreach my $subfield ($field->subfields()) {
2411             if (defined $subfield->[1] and
2412                 $subfield->[1] ne '' and
2413                 !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) {
2414                 push @$subfields, $subfield->[0] => $subfield->[1];
2415             }
2416         }
2417     }
2418     return $subfields;
2419 }
2420
2421 =head2 _get_unlinked_subfields_xml
2422
2423   my $unlinked_subfields_xml = _get_unlinked_subfields_xml($unlinked_item_subfields);
2424
2425 =cut
2426
2427 sub _get_unlinked_subfields_xml {
2428     my $unlinked_item_subfields = shift;
2429
2430     my $xml;
2431     if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) {
2432         my $marc = MARC::Record->new();
2433         # use of tag 999 is arbitrary, and doesn't need to match the item tag
2434         # used in the framework
2435         $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields));
2436         $marc->encoding("UTF-8");    
2437         $xml = $marc->as_xml("USMARC");
2438     }
2439
2440     return $xml;
2441 }
2442
2443 =head2 _parse_unlinked_item_subfields_from_xml
2444
2445   my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($whole_item->{'more_subfields_xml'}):
2446
2447 =cut
2448
2449 sub  _parse_unlinked_item_subfields_from_xml {
2450     my $xml = shift;
2451
2452     return unless defined $xml and $xml ne "";
2453     my $marc = MARC::Record->new_from_xml(StripNonXmlChars($xml),'UTF-8');
2454     my $unlinked_subfields = [];
2455     my @fields = $marc->fields();
2456     if ($#fields > -1) {
2457         foreach my $subfield ($fields[0]->subfields()) {
2458             push @$unlinked_subfields, $subfield->[0] => $subfield->[1];
2459         }
2460     }
2461     return $unlinked_subfields;
2462 }
2463
2464 =head2 GetAnalyticsCount
2465
2466   $count= &GetAnalyticsCount($itemnumber)
2467
2468 counts Usage of itemnumber in Analytical bibliorecords. 
2469
2470 =cut
2471
2472 sub GetAnalyticsCount {
2473     my ($itemnumber) = @_;
2474     if (C4::Context->preference('NoZebra')) {
2475         # Read the index Koha-Auth-Number for this authid and count the lines
2476         my $result = C4::Search::NZanalyse("hi=$itemnumber");
2477         my @tab = split /;/,$result;
2478         return scalar @tab;
2479     } else {
2480         ### ZOOM search here
2481         my $query;
2482         $query= "hi=".$itemnumber;
2483                 my ($err,$res,$result) = C4::Search::SimpleSearch($query,0,10);
2484         return ($result);
2485     }
2486 }
2487
2488 =head2 GetItemHolds
2489
2490 =over 4
2491 $holds = &GetItemHolds($biblionumber, $itemnumber);
2492
2493 =back
2494
2495 This function return the count of holds with $biblionumber and $itemnumber
2496
2497 =cut
2498
2499 sub GetItemHolds {
2500     my ($biblionumber, $itemnumber) = @_;
2501     my $holds;
2502     my $dbh            = C4::Context->dbh;
2503     my $query          = "SELECT count(*)
2504         FROM  reserves
2505         WHERE biblionumber=? AND itemnumber=?";
2506     my $sth = $dbh->prepare($query);
2507     $sth->execute($biblionumber, $itemnumber);
2508     $holds = $sth->fetchrow;
2509     return $holds;
2510 }
2511 1;