Bug 9004 - Talking Tech doesn't account for holidays when calculating a holds last...
[koha.git] / catalogue / detail.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18
19 use strict;
20 use warnings;
21
22 use CGI qw ( -utf8 );
23 use C4::Acquisition qw( GetHistory );
24 use C4::Auth;
25 use C4::Koha;
26 use C4::Serials;    #uses getsubscriptionfrom biblionumber
27 use C4::Output;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Circulation;
31 use C4::Branch;
32 use C4::Reserves;
33 use C4::Members; # to use GetMember
34 use C4::Serials;
35 use C4::XISBN qw(get_xisbns get_biblionumber_from_isbn);
36 use C4::External::Amazon;
37 use C4::Search;         # enabled_staff_search_views
38 use C4::Tags qw(get_tags);
39 use C4::XSLT;
40 use C4::Images;
41 use Koha::DateUtils;
42 use C4::HTML5Media;
43 use C4::CourseReserves qw(GetItemCourseReservesInfo);
44 use C4::Acquisition qw(GetOrdersByBiblionumber);
45 use Koha::Virtualshelves;
46
47 my $query = CGI->new();
48
49 my $analyze = $query->param('analyze');
50
51 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
52     {
53     template_name   =>  'catalogue/detail.tt',
54         query           => $query,
55         type            => "intranet",
56         authnotrequired => 0,
57         flagsrequired   => { catalogue => 1 },
58     }
59 );
60
61 my $biblionumber = $query->param('biblionumber');
62 my $record       = GetMarcBiblio($biblionumber);
63
64 if ( not defined $record ) {
65     # biblionumber invalid -> report and exit
66     $template->param( unknownbiblionumber => 1,
67                       biblionumber => $biblionumber );
68     output_html_with_http_headers $query, $cookie, $template->output;
69     exit;
70 }
71
72 if($query->cookie("holdfor")){ 
73     my $holdfor_patron = GetMember('borrowernumber' => $query->cookie("holdfor"));
74     $template->param(
75         holdfor => $query->cookie("holdfor"),
76         holdfor_surname => $holdfor_patron->{'surname'},
77         holdfor_firstname => $holdfor_patron->{'firstname'},
78         holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
79     );
80 }
81
82 my $fw           = GetFrameworkCode($biblionumber);
83 my $showallitems = $query->param('showallitems');
84 my $marcflavour  = C4::Context->preference("marcflavour");
85
86 # XSLT processing of some stuff
87 if (C4::Context->preference("XSLTDetailsDisplay") ) {
88     $template->param('XSLTDetailsDisplay' =>'1',
89         'XSLTBloc' => XSLTParse4Display($biblionumber, $record, "XSLTDetailsDisplay") );
90 }
91
92 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
93 $template->param( ocoins => GetCOinSBiblio($record) );
94
95 # some useful variables for enhanced content;
96 # in each case, we're grabbing the first value we find in
97 # the record and normalizing it
98 my $upc = GetNormalizedUPC($record,$marcflavour);
99 my $ean = GetNormalizedEAN($record,$marcflavour);
100 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
101 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
102
103 $template->param(
104     normalized_upc => $upc,
105     normalized_ean => $ean,
106     normalized_oclc => $oclc,
107     normalized_isbn => $isbn,
108 );
109
110 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
111 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
112 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
113 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
114 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
115 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
116 my $marchostsarray  = GetMarcHosts($record,$marcflavour);
117 my $subtitle         = GetRecordValue('subtitle', $record, $fw);
118
119 # Get Branches, Itemtypes and Locations
120 my $branches = GetBranches();
121 my $itemtypes = GetItemTypes();
122 my $dbh = C4::Context->dbh;
123
124 my @all_items = GetItemsInfo( $biblionumber );
125 my @items;
126 for my $itm (@all_items) {
127     push @items, $itm unless ( $itm->{itemlost} && GetHideLostItemsPreference($borrowernumber) && !$showallitems);
128 }
129
130 # flag indicating existence of at least one item linked via a host record
131 my $hostrecords;
132 # adding items linked via host biblios
133 my @hostitems = GetHostItemsInfo($record);
134 if (@hostitems){
135         $hostrecords =1;
136         push (@items,@hostitems);
137 }
138
139 my $dat = &GetBiblioData($biblionumber);
140
141 #coping with subscriptions
142 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
143 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
144 my @subs;
145
146 foreach my $subscription (@subscriptions) {
147     my %cell;
148         my $serials_to_display;
149     $cell{subscriptionid}    = $subscription->{subscriptionid};
150     $cell{subscriptionnotes} = $subscription->{internalnotes};
151     $cell{missinglist}       = $subscription->{missinglist};
152     $cell{librariannote}     = $subscription->{librariannote};
153     $cell{branchcode}        = $subscription->{branchcode};
154     $cell{branchname}        = GetBranchName($subscription->{branchcode});
155     $cell{hasalert}          = $subscription->{hasalert};
156     $cell{callnumber}        = $subscription->{callnumber};
157     $cell{closed}            = $subscription->{closed};
158     #get the three latest serials.
159         $serials_to_display = $subscription->{staffdisplaycount};
160         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
161         $cell{staffdisplaycount} = $serials_to_display;
162     $cell{latestserials} =
163       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
164     push @subs, \%cell;
165 }
166
167
168 # Get acquisition details
169 if ( C4::Context->preference('AcquisitionDetails') ) {
170     my $orders = C4::Acquisition::GetHistory( biblionumber => $biblionumber, get_canceled_order => 1 );
171     $template->param(
172         orders => $orders,
173     );
174 }
175
176 if ( defined $dat->{'itemtype'} ) {
177     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
178 }
179
180 $dat->{'count'} = scalar @all_items + @hostitems;
181 $dat->{'showncount'} = scalar @items + @hostitems;
182 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
183
184 my $shelflocations = GetKohaAuthorisedValues('items.location', $fw);
185 my $collections    = GetKohaAuthorisedValues('items.ccode'   , $fw);
186 my $copynumbers    = GetKohaAuthorisedValues('items.copynumber', $fw);
187 my (@itemloop, @otheritemloop, %itemfields);
188 my $norequests = 1;
189
190 if ( my $lost_av = GetAuthValCode('items.itemlost', $fw) ) {
191     $template->param( itemlostloop => GetAuthorisedValues( $lost_av ) );
192 }
193 if ( my $damaged_av = GetAuthValCode('items.damaged', $fw) ) {
194     $template->param( itemdamagedloop => GetAuthorisedValues( $damaged_av ) );
195 }
196
197 my $materials_authvalcode = GetAuthValCode('items.materials', $fw);
198 my %materials_map;
199 if ($materials_authvalcode) {
200     my $materials_authvals = GetAuthorisedValues($materials_authvalcode);
201     if ($materials_authvals) {
202         foreach my $value (@$materials_authvals) {
203             $materials_map{$value->{authorised_value}} = $value->{lib};
204         }
205     }
206 }
207
208 my $analytics_flag;
209 my $materials_flag; # set this if the items have anything in the materials field
210 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
211 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
212     $template->param(SeparateHoldings => 1);
213 }
214 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
215 foreach my $item (@items) {
216     my $itembranchcode = $item->{$separatebranch};
217
218     # can place holds defaults to yes
219     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
220
221     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
222                                                : '';
223
224     $item->{datedue} = format_sqldatetime($item->{datedue});
225
226     #get shelf location and collection code description if they are authorised value.
227     # same thing for copy number
228     my $shelfcode = $item->{'location'};
229     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
230     my $ccode = $item->{'ccode'};
231     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
232     my $copynumber = $item->{'copynumber'};
233     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
234     foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri)) {
235         $itemfields{$_} = 1 if ( $item->{$_} );
236     }
237
238     # checking for holds
239     my ($reservedate,$reservedfor,$expectedAt,undef,$wait) = GetReservesFromItemnumber($item->{itemnumber});
240     my $ItemBorrowerReserveInfo = C4::Members::GetMember( borrowernumber => $reservedfor);
241     
242     if (C4::Context->preference('HidePatronName')){
243         $item->{'hidepatronname'} = 1;
244     }
245
246     if ( defined $reservedate ) {
247         $item->{backgroundcolor} = 'reserved';
248         $item->{reservedate}     = $reservedate;
249         $item->{ReservedForBorrowernumber}     = $reservedfor;
250         $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
251         $item->{ReservedForFirstname}   = $ItemBorrowerReserveInfo->{'firstname'};
252         $item->{ExpectedAtLibrary}      = $branches->{$expectedAt}{branchname};
253         $item->{Reservedcardnumber}             = $ItemBorrowerReserveInfo->{'cardnumber'};
254         # Check waiting status
255         $item->{waitingdate} = $wait;
256     }
257
258
259         # Check the transit status
260     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
261     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
262         $item->{transfertwhen} = $transfertwhen;
263         $item->{transfertfrom} = $branches->{$transfertfrom}{branchname};
264         $item->{transfertto}   = $branches->{$transfertto}{branchname};
265         $item->{nocancel} = 1;
266     }
267
268     foreach my $f (qw( itemnotes )) {
269         if ($item->{$f}) {
270             $item->{$f} =~ s|\n|<br />|g;
271             $itemfields{$f} = 1;
272         }
273     }
274
275     #item has a host number if its biblio number does not match the current bib
276
277     if ($item->{biblionumber} ne $biblionumber){
278         $item->{hostbiblionumber} = $item->{biblionumber};
279         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
280     }
281         
282     #count if item is used in analytical bibliorecords
283     my $countanalytics= GetAnalyticsCount($item->{itemnumber});
284     if ($countanalytics > 0){
285         $analytics_flag=1;
286         $item->{countanalytics} = $countanalytics;
287     }
288
289     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
290         $materials_flag = 1;
291         if (defined $materials_map{ $item->{materials} }) {
292             $item->{materials} = $materials_map{ $item->{materials} };
293         }
294     }
295
296     if ( C4::Context->preference('UseCourseReserves') ) {
297         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
298     }
299
300     if ( C4::Context->preference('IndependentBranches') ) {
301         my $userenv = C4::Context->userenv();
302         if ( not C4::Context->IsSuperLibrarian()
303             and $userenv->{branch} ne $item->{homebranch} ) {
304             $item->{cannot_be_edited} = 1;
305         }
306     }
307
308     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
309     and C4::Context->preference('SeparateHoldings')) {
310         if ($itembranchcode and $itembranchcode eq $currentbranch) {
311             push @itemloop, $item;
312         } else {
313             push @otheritemloop, $item;
314         }
315     } else {
316         push @itemloop, $item;
317     }
318 }
319
320 # Display only one tab if one items list is empty
321 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
322     $template->param(SeparateHoldings => 0);
323     if (scalar(@itemloop) == 0) {
324         @itemloop = @otheritemloop;
325     }
326 }
327
328 $template->param( norequests => $norequests );
329 $template->param(
330         MARCNOTES   => $marcnotesarray,
331         MARCSUBJCTS => $marcsubjctsarray,
332         MARCAUTHORS => $marcauthorsarray,
333         MARCSERIES  => $marcseriesarray,
334         MARCURLS => $marcurlsarray,
335     MARCISBNS => $marcisbnsarray,
336         MARCHOSTS => $marchostsarray,
337         subtitle    => $subtitle,
338         itemdata_ccode      => $itemfields{ccode},
339         itemdata_enumchron  => $itemfields{enumchron},
340         itemdata_uri        => $itemfields{uri},
341         itemdata_copynumber => $itemfields{copynumber},
342         itemdata_stocknumber => $itemfields{stocknumber},
343         volinfo                         => $itemfields{enumchron},
344         itemdata_itemnotes  => $itemfields{itemnotes},
345         itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
346         z3950_search_params     => C4::Search::z3950_search_args($dat),
347         hostrecords         => $hostrecords,
348         analytics_flag  => $analytics_flag,
349         C4::Search::enabled_staff_search_views,
350         materials       => $materials_flag,
351 );
352
353 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
354     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
355     my $subfields = substr $fieldspec, 3;
356     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
357     my @alternateholdingsinfo = ();
358     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
359
360     for my $field (@holdingsfields) {
361         my %holding = ( holding => '' );
362         my $havesubfield = 0;
363         for my $subfield ($field->subfields()) {
364             if ((index $subfields, $$subfield[0]) >= 0) {
365                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
366                 $holding{'holding'} .= $$subfield[1];
367                 $havesubfield++;
368             }
369         }
370         if ($havesubfield) {
371             push(@alternateholdingsinfo, \%holding);
372         }
373     }
374
375     $template->param(
376         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
377         );
378 }
379
380 my @results = ( $dat, );
381 foreach ( keys %{$dat} ) {
382     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
383 }
384
385 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
386 # method query not found?!?!
387 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
388 $template->param(
389     itemloop        => \@itemloop,
390     otheritemloop   => \@otheritemloop,
391     biblionumber        => $biblionumber,
392     ($analyze? 'analyze':'detailview') =>1,
393     subscriptions       => \@subs,
394     subscriptionsnumber => $subscriptionsnumber,
395     subscriptiontitle   => $dat->{title},
396     searchid            => scalar $query->param('searchid'),
397 );
398
399 # $debug and $template->param(debug_display => 1);
400
401 # Lists
402
403 if (C4::Context->preference("virtualshelves") ) {
404     my $shelves = Koha::Virtualshelves->search(
405         {
406             biblionumber => $biblionumber,
407             category => 2,
408         },
409         {
410             join => 'virtualshelfcontents',
411         }
412     );
413     $template->param( 'shelves' => $shelves );
414 }
415
416 # XISBN Stuff
417 if (C4::Context->preference("FRBRizeEditions")==1) {
418     eval {
419         $template->param(
420             XISBNS => get_xisbns($isbn)
421         );
422     };
423     if ($@) { warn "XISBN Failed $@"; }
424 }
425
426 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
427     my @images = ListImagesForBiblio($biblionumber);
428     $template->{VARS}->{localimages} = \@images;
429 }
430
431 # HTML5 Media
432 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
433     $template->param( C4::HTML5Media->gethtml5media($record));
434 }
435
436 # Displaying tags
437
438 my $tag_quantity;
439 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
440     $template->param(
441         TagsEnabled => 1,
442         TagsShowOnDetail => $tag_quantity
443     );
444     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
445                                 'sort'=>'-weight', limit=>$tag_quantity}));
446 }
447
448 #we only need to pass the number of holds to the template
449 my $holds = C4::Reserves::GetReservesFromBiblionumber({ biblionumber => $biblionumber, all_dates => 1 });
450 $template->param( holdcount => scalar ( @$holds ) );
451
452 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
453 if ($StaffDetailItemSelection) {
454     # Only enable item selection if user can execute at least one action
455     if (
456         $flags->{superlibrarian}
457         || (
458             ref $flags->{tools} eq 'HASH' && (
459                 $flags->{tools}->{items_batchmod}       # Modify selected items
460                 || $flags->{tools}->{items_batchdel}    # Delete selected items
461             )
462         )
463         || ( ref $flags->{tools} eq '' && $flags->{tools} )
464       )
465     {
466         $template->param(
467             StaffDetailItemSelection => $StaffDetailItemSelection );
468     }
469 }
470
471 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
472 my @deletedorders_using_biblio;
473 my @orders_using_biblio;
474 my @baskets_orders;
475 my @baskets_deletedorders;
476
477 foreach my $myorder (@allorders_using_biblio) {
478     my $basket = $myorder->{'basketno'};
479     if ((defined $myorder->{'datecancellationprinted'}) and  ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
480         push @deletedorders_using_biblio, $myorder;
481         unless (grep(/^$basket$/, @baskets_deletedorders)){
482             push @baskets_deletedorders,$myorder->{'basketno'};
483         }
484     }
485     else {
486         push @orders_using_biblio, $myorder;
487         unless (grep(/^$basket$/, @baskets_orders)){
488             push @baskets_orders,$myorder->{'basketno'};
489             }
490     }
491 }
492
493 my $count_orders_using_biblio = scalar @orders_using_biblio ;
494 $template->param (countorders => $count_orders_using_biblio);
495
496 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
497 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
498
499 $template->param (basketsorders => \@baskets_orders);
500 $template->param (basketsdeletedorders => \@baskets_deletedorders);
501
502 output_html_with_http_headers $query, $cookie, $template->output;