KRT-4338 -- generate stocknumbers only for FFZG home branch
[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
46 use Koha::Virtualshelves;
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.tt',
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 my $partnum         = GetRecordValue('partnum', $record, $fw);
120 my $partname         = GetRecordValue('partname', $record, $fw);
121 my $medium         = GetRecordValue('medium', $record, $fw);
122 my $responsibility         = GetRecordValue('responsibility', $record, $fw);
123 my $impressum         = GetRecordValue('impressum', $record, $fw);
124 my $oldcall         = GetRecordValue('oldcall', $record, $fw);
125 my $udc         = GetRecordValue('udc', $record, $fw);
126 my $textholding         = GetRecordValue('textholding', $record, $fw);
127
128 # Get Branches, Itemtypes and Locations
129 my $branches = GetBranches();
130 my $itemtypes = GetItemTypes();
131 my $dbh = C4::Context->dbh;
132
133 my @all_items = GetItemsInfo( $biblionumber );
134 my @items;
135 for my $itm (@all_items) {
136     push @items, $itm unless ( $itm->{itemlost} && GetHideLostItemsPreference($borrowernumber) && !$showallitems);
137 }
138
139 # flag indicating existence of at least one item linked via a host record
140 my $hostrecords;
141 # adding items linked via host biblios
142 my @hostitems = GetHostItemsInfo($record);
143 if (@hostitems){
144         $hostrecords =1;
145         push (@items,@hostitems);
146 }
147
148 my $dat = &GetBiblioData($biblionumber);
149
150 #coping with subscriptions
151 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
152 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
153 my @subs;
154
155 foreach my $subscription (@subscriptions) {
156     my %cell;
157         my $serials_to_display;
158     $cell{subscriptionid}    = $subscription->{subscriptionid};
159     $cell{subscriptionnotes} = $subscription->{internalnotes};
160     $cell{missinglist}       = $subscription->{missinglist};
161     $cell{librariannote}     = $subscription->{librariannote};
162     $cell{branchcode}        = $subscription->{branchcode};
163     $cell{branchname}        = GetBranchName($subscription->{branchcode});
164     $cell{hasalert}          = $subscription->{hasalert};
165     $cell{callnumber}        = $subscription->{callnumber};
166     $cell{closed}            = $subscription->{closed};
167     #get the three latest serials.
168         $serials_to_display = $subscription->{staffdisplaycount};
169         $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
170         $cell{staffdisplaycount} = $serials_to_display;
171     $cell{latestserials} =
172       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
173     push @subs, \%cell;
174 }
175
176
177 # Get acquisition details
178 if ( C4::Context->preference('AcquisitionDetails') ) {
179     my $orders = C4::Acquisition::GetHistory( biblionumber => $biblionumber, get_canceled_order => 1 );
180     $template->param(
181         orders => $orders,
182     );
183 }
184
185 if ( defined $dat->{'itemtype'} ) {
186     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
187 }
188
189 $dat->{'count'} = scalar @all_items + @hostitems;
190 $dat->{'showncount'} = scalar @items + @hostitems;
191 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
192
193 my $shelflocations = GetKohaAuthorisedValues('items.location', $fw);
194 my $collections    = GetKohaAuthorisedValues('items.ccode'   , $fw);
195 my $copynumbers    = GetKohaAuthorisedValues('items.copynumber', $fw);
196 my (@itemloop, @otheritemloop, %itemfields);
197 my $norequests = 1;
198 my $authvalcode_items_itemlost = GetAuthValCode('items.itemlost',$fw);
199 my $authvalcode_items_damaged  = GetAuthValCode('items.damaged', $fw);
200
201 my $analytics_flag;
202 my $materials_flag; # set this if the items have anything in the materials field
203 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
204 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
205     $template->param(SeparateHoldings => 1);
206 }
207 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
208 foreach my $item (@items) {
209     my $itembranchcode = $item->{$separatebranch};
210
211     # can place holds defaults to yes
212     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
213
214     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
215                                                : '';
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 stocknumber itemnotes uri)) {
232         $itemfields{$_} = 1 if ( $item->{$_} );
233     }
234
235     # checking for holds
236     my ($reservedate,$reservedfor,$expectedAt,undef,$wait) = GetReservesFromItemnumber($item->{itemnumber});
237     my $ItemBorrowerReserveInfo = C4::Members::GetMember( borrowernumber => $reservedfor);
238     
239     if (C4::Context->preference('HidePatronName')){
240         $item->{'hidepatronname'} = 1;
241     }
242
243     if ( defined $reservedate ) {
244         $item->{backgroundcolor} = 'reserved';
245         $item->{reservedate}     = $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         # Check waiting status
252         $item->{waitingdate} = $wait;
253     }
254
255
256         # Check the transit status
257     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
258     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
259         $item->{transfertwhen} = $transfertwhen;
260         $item->{transfertfrom} = $branches->{$transfertfrom}{branchname};
261         $item->{transfertto}   = $branches->{$transfertto}{branchname};
262         $item->{nocancel} = 1;
263     }
264
265     # item has a host number if its biblio number does not match the current bib
266     if ($item->{biblionumber} ne $biblionumber){
267         $item->{hostbiblionumber} = $item->{biblionumber};
268         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
269     }
270         
271     #count if item is used in analytical bibliorecords
272     my $countanalytics= GetAnalyticsCount($item->{itemnumber});
273     if ($countanalytics > 0){
274         $analytics_flag=1;
275         $item->{countanalytics} = $countanalytics;
276     }
277
278     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
279         $materials_flag = 1;
280     }
281
282     if ( C4::Context->preference('UseCourseReserves') ) {
283         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
284     }
285
286     if ( C4::Context->preference('IndependentBranches') ) {
287         my $userenv = C4::Context->userenv();
288         if ( not C4::Context->IsSuperLibrarian()
289             and $userenv->{branch} ne $item->{homebranch} ) {
290             $item->{cannot_be_edited} = 1;
291         }
292     }
293
294     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
295     and C4::Context->preference('SeparateHoldings')) {
296         if ($itembranchcode and $itembranchcode eq $currentbranch) {
297             push @itemloop, $item;
298         } else {
299             push @otheritemloop, $item;
300         }
301     } else {
302         push @itemloop, $item;
303     }
304 }
305
306 # Display only one tab if one items list is empty
307 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
308     $template->param(SeparateHoldings => 0);
309     if (scalar(@itemloop) == 0) {
310         @itemloop = @otheritemloop;
311     }
312 }
313
314 $template->param( norequests => $norequests );
315 $template->param(
316         MARCNOTES   => $marcnotesarray,
317         MARCSUBJCTS => $marcsubjctsarray,
318         MARCAUTHORS => $marcauthorsarray,
319         MARCSERIES  => $marcseriesarray,
320         MARCURLS => $marcurlsarray,
321     MARCISBNS => $marcisbnsarray,
322         MARCHOSTS => $marchostsarray,
323         subtitle    => $subtitle,
324         partnum         => $partnum,
325         partname    => $partname,
326         medium          => $medium,
327         responsibility    => $responsibility,
328         impressum       => $impressum,
329         oldcall         => $oldcall,
330         udc                     => $udc,
331         textholding     => $textholding,
332         itemdata_ccode      => $itemfields{ccode},
333         itemdata_enumchron  => $itemfields{enumchron},
334         itemdata_uri        => $itemfields{uri},
335         itemdata_copynumber => $itemfields{copynumber},
336         itemdata_stocknumber => $itemfields{stocknumber},
337         volinfo                         => $itemfields{enumchron},
338     itemdata_itemnotes  => $itemfields{itemnotes},
339         z3950_search_params     => C4::Search::z3950_search_args($dat),
340         hostrecords         => $hostrecords,
341         analytics_flag  => $analytics_flag,
342         C4::Search::enabled_staff_search_views,
343         materials       => $materials_flag,
344 );
345
346 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
347     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
348     my $subfields = substr $fieldspec, 3;
349     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
350     my @alternateholdingsinfo = ();
351     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
352
353     for my $field (@holdingsfields) {
354         my %holding = ( holding => '' );
355         my $havesubfield = 0;
356         for my $subfield ($field->subfields()) {
357             if ((index $subfields, $$subfield[0]) >= 0) {
358                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
359                 $holding{'holding'} .= $$subfield[1];
360                 $havesubfield++;
361             }
362         }
363         if ($havesubfield) {
364             push(@alternateholdingsinfo, \%holding);
365         }
366     }
367
368     $template->param(
369         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
370         );
371 }
372
373 my @results = ( $dat, );
374 foreach ( keys %{$dat} ) {
375     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
376 }
377
378 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
379 # method query not found?!?!
380 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
381 $template->param(
382     itemloop        => \@itemloop,
383     otheritemloop   => \@otheritemloop,
384     biblionumber        => $biblionumber,
385     ($analyze? 'analyze':'detailview') =>1,
386     subscriptions       => \@subs,
387     subscriptionsnumber => $subscriptionsnumber,
388     subscriptiontitle   => $dat->{title},
389     searchid            => $query->param('searchid'),
390 );
391
392 # $debug and $template->param(debug_display => 1);
393
394 # Lists
395
396 if (C4::Context->preference("virtualshelves") ) {
397     my $shelves = Koha::Virtualshelves->search(
398         {
399             biblionumber => $biblionumber,
400             category => 2,
401         },
402         {
403             join => 'virtualshelfcontents',
404         }
405     );
406     $template->param( 'shelves' => $shelves );
407 }
408
409 # XISBN Stuff
410 if (C4::Context->preference("FRBRizeEditions")==1) {
411     eval {
412         $template->param(
413             XISBNS => get_xisbns($isbn)
414         );
415     };
416     if ($@) { warn "XISBN Failed $@"; }
417 }
418
419 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
420     my @images = ListImagesForBiblio($biblionumber);
421     $template->{VARS}->{localimages} = \@images;
422 }
423
424 # HTML5 Media
425 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
426     $template->param( C4::HTML5Media->gethtml5media($record));
427 }
428
429 # Displaying tags
430
431 my $tag_quantity;
432 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
433     $template->param(
434         TagsEnabled => 1,
435         TagsShowOnDetail => $tag_quantity
436     );
437     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
438                                 'sort'=>'-weight', limit=>$tag_quantity}));
439 }
440
441 #we only need to pass the number of holds to the template
442 my $holds = C4::Reserves::GetReservesFromBiblionumber({ biblionumber => $biblionumber, all_dates => 1 });
443 $template->param( holdcount => scalar ( @$holds ) );
444
445 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
446 if ($StaffDetailItemSelection) {
447     # Only enable item selection if user can execute at least one action
448     if (
449         $flags->{superlibrarian}
450         || (
451             ref $flags->{tools} eq 'HASH' && (
452                 $flags->{tools}->{items_batchmod}       # Modify selected items
453                 || $flags->{tools}->{items_batchdel}    # Delete selected items
454             )
455         )
456         || ( ref $flags->{tools} eq '' && $flags->{tools} )
457       )
458     {
459         $template->param(
460             StaffDetailItemSelection => $StaffDetailItemSelection );
461     }
462 }
463
464 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
465 my @deletedorders_using_biblio;
466 my @orders_using_biblio;
467 my @baskets_orders;
468 my @baskets_deletedorders;
469
470 foreach my $myorder (@allorders_using_biblio) {
471     my $basket = $myorder->{'basketno'};
472     if ((defined $myorder->{'datecancellationprinted'}) and  ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
473         push @deletedorders_using_biblio, $myorder;
474         unless (grep(/^$basket$/, @baskets_deletedorders)){
475             push @baskets_deletedorders,$myorder->{'basketno'};
476         }
477     }
478     else {
479         push @orders_using_biblio, $myorder;
480         unless (grep(/^$basket$/, @baskets_orders)){
481             push @baskets_orders,$myorder->{'basketno'};
482             }
483     }
484 }
485
486 my $count_orders_using_biblio = scalar @orders_using_biblio ;
487 $template->param (countorders => $count_orders_using_biblio);
488
489 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
490 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
491
492 $template->param (basketsorders => \@baskets_orders);
493 $template->param (basketsdeletedorders => \@baskets_deletedorders);
494
495 output_html_with_http_headers $query, $cookie, $template->output;