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