Bug 30907: Fix incorrect uses of Koha::Recall->item_level_recall
[koha.git] / svc / checkouts
1 #!/usr/bin/perl
2
3 # Copyright 2014 ByWater Solutions
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use CGI;
23 use JSON qw(to_json);
24
25 use C4::Auth qw(check_cookie_auth haspermission);
26 use C4::Circulation qw(GetIssuingCharges CanBookBeRenewed GetRenewCount );
27 use C4::Overdues qw(GetFine);
28 use C4::Context;
29
30 use Koha::AuthorisedValues;
31 use Koha::DateUtils qw( dt_from_string output_pref );
32 use Koha::Items;
33 use Koha::ItemTypes;
34
35 my $input = CGI->new;
36
37 my ( $auth_status, $session ) = check_cookie_auth( $input->cookie('CGISESSID'));
38 if( $auth_status ne 'ok' ) {
39     print CGI::header( '-status' => '401' );
40     exit 0;
41 }
42
43 my $userid   = $session->param('id');
44
45 unless (haspermission($userid, { circulate => 'circulate_remaining_permissions' })
46     || haspermission($userid, { borrowers => 'edit_borrowers' })) {
47     exit 0;
48 }
49
50 my @sort_columns = qw/date_due title itype issuedate branchcode itemcallnumber/;
51
52 my @borrowernumber   = $input->multi_param('borrowernumber');
53 my $offset           = $input->param('iDisplayStart');
54 my $results_per_page = $input->param('iDisplayLength') || -1;
55
56 my $sorting_column = $input->param('iSortCol_0') || q{};
57 $sorting_column = ( $sorting_column && $sort_columns[$sorting_column] ) ? $sort_columns[$sorting_column] : 'issuedate';
58
59 my $sorting_direction = $input->param('sSortDir_0') || q{};
60 $sorting_direction = $sorting_direction eq 'asc' ? 'asc' : 'desc';
61
62 $results_per_page = undef if ( $results_per_page == -1 );
63
64 binmode STDOUT, ":encoding(UTF-8)";
65 print $input->header( -type => 'text/plain', -charset => 'UTF-8' );
66
67 my @parameters;
68 my $sql = '
69     SELECT
70         issues.issuedate,
71         issues.date_due,
72         issues.date_due < now() as date_due_overdue,
73         issues.timestamp,
74
75         issues.onsite_checkout,
76
77         biblio.biblionumber,
78         biblio.title,
79         biblio.subtitle,
80         biblio.medium,
81         biblio.part_number,
82         biblio.part_name,
83         biblio.author,
84
85         items.itemnumber,
86         items.barcode,
87         branches2.branchname AS homebranch,
88         items.itemnotes,
89         items.itemnotes_nonpublic,
90         items.itemcallnumber,
91         items.copynumber,
92         items.replacementprice,
93
94         issues.branchcode,
95         branches.branchname,
96
97         items.itype,
98         biblioitems.itemtype,
99
100         items.ccode AS collection,
101
102         borrowers.borrowernumber,
103         borrowers.surname,
104         borrowers.firstname,
105         borrowers.cardnumber,
106
107         items.itemlost,
108         items.damaged,
109         items.location,
110         items.enumchron,
111         items.materials,
112
113         DATEDIFF( issues.issuedate, CURRENT_DATE() ) AS not_issued_today,
114
115         return_claims.id AS return_claim_id,
116         return_claims.notes AS return_claim_notes,
117         return_claims.created_on AS return_claim_created_on,
118         return_claims.updated_on AS return_claim_updated_on
119
120     FROM issues
121         LEFT JOIN items USING ( itemnumber )
122         LEFT JOIN biblio USING ( biblionumber )
123         LEFT JOIN biblioitems USING ( biblionumber )
124         LEFT JOIN borrowers USING ( borrowernumber )
125         LEFT JOIN branches ON ( issues.branchcode = branches.branchcode )
126         LEFT JOIN branches branches2 ON ( items.homebranch = branches2.branchcode )
127         LEFT JOIN return_claims USING ( issue_id )
128     WHERE issues.borrowernumber
129 ';
130
131 if ( @borrowernumber == 1 ) {
132     $sql .= '= ?';
133 }
134 else {
135     $sql .= ' IN (' . join( ',', ('?') x @borrowernumber ) . ') ';
136 }
137 push( @parameters, @borrowernumber );
138
139 $sql .= " ORDER BY $sorting_column $sorting_direction ";
140
141 my $dbh = C4::Context->dbh();
142 my $sth = $dbh->prepare($sql);
143 $sth->execute(@parameters);
144
145 my $item_level_itypes = C4::Context->preference('item-level_itypes');
146 my $claims_returned_lost_value = C4::Context->preference('ClaimReturnedLostValue');
147 my $confirm_parts_required = C4::Context->preference("CircConfirmItemParts");
148
149 my $itemtypes = { map { $_->{itemtype} => $_->{translated_description} } @{ Koha::ItemTypes->search_with_localization->unblessed } };
150
151 my @checkouts_today;
152 my @checkouts_previous;
153 while ( my $c = $sth->fetchrow_hashref() ) {
154     my ($charge) = GetIssuingCharges( $c->{itemnumber}, $c->{borrowernumber} );
155     my $fine = GetFine( $c->{itemnumber}, $c->{borrowernumber} );
156
157     my ( $can_renew, $can_renew_error, $info ) =
158       CanBookBeRenewed( $c->{borrowernumber}, $c->{itemnumber} );
159     my $can_renew_date =
160       $can_renew_error && $can_renew_error eq 'too_soon'
161       ? output_pref(
162         {
163             dt => $info->{soonest_renew_date},
164             as_due_date => 1
165         }
166       )
167       : undef;
168
169     my (
170         $renewals_count,
171         $renewals_allowed,
172         $renewals_remaining,
173         $unseen_count,
174         $unseen_allowed,
175         $unseen_remaining
176     ) =
177       GetRenewCount( $c->{borrowernumber}, $c->{itemnumber} );
178
179     my ( $itemtype, $recordtype, $type_for_stat );
180     $itemtype      = $itemtypes->{ $c->{itype} }    if $c->{itype};
181     $recordtype    = $itemtypes->{ $c->{itemtype} } if $c->{itemtype};
182     $type_for_stat = $item_level_itypes ? $itemtype : $recordtype;
183
184     my $location;
185     if ( $c->{location} ) {
186         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
187             { kohafield => 'items.location', authorised_value => $c->{location} } );
188         $location = $av->{lib} ? $av->{lib} : '';
189     }
190     my $collection;
191     if ( $c->{collection} ) {
192         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
193             { kohafield => 'items.ccode', authorised_value => $c->{collection} } );
194         $collection = $av->{lib} ? $av->{lib} : '';
195     }
196     my $lost;
197     my $claims_returned;
198     if ( $c->{itemlost} ) {
199         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
200             { kohafield => 'items.itemlost', authorised_value => $c->{itemlost} } );
201         $lost            = $av->{lib} ? $av->{lib} : '';
202         $claims_returned = $c->{itemlost} eq $claims_returned_lost_value;
203     }
204     my $damaged;
205     if ( $c->{damaged} ) {
206         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
207             { kohafield => 'items.damaged', authorised_value => $c->{damaged} } );
208         $damaged = $av->{lib} ? $av->{lib} : '';
209     }
210     my $materials;
211     if ( $c->{materials} && $confirm_parts_required ) {
212         my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $c->{materials} });
213         $materials = $descriptions->{lib} // $c->{materials};
214     }
215     my @subtitles = split(/ \| /, $c->{'subtitle'} // '' );
216
217     my $item = Koha::Items->find( $c->{itemnumber} );
218     my $recalled = 0;
219     if ( C4::Context->preference('UseRecalls') ) {
220         my $recall = undef;
221         $recall = $item->check_recalls if $item->can_be_waiting_recall;
222         if ( defined $recall ) {
223             if ( $recall->item_level ) {
224                 if ( $recall->itemnumber == $c->{itemnumber} ) {
225                     # item-level recall on this item
226                     $recalled = 1;
227                 } else {
228                     $recalled = 0;
229                 }
230             } else {
231                 # biblio-level recall, but don't want to mark recalled if the recall has been allocated a different item
232                 if ( !$recall->waiting ) {
233                     $recalled = 1;
234                 }
235             }
236         }
237     }
238
239     my $checkout = {
240         DT_RowId             => $c->{itemnumber} . '-' . $c->{borrowernumber},
241         title                => $c->{title},
242         subtitle             => \@subtitles,
243         medium               => $c->{medium} // '',
244         part_number          => $c->{part_number} // '',
245         part_name            => $c->{part_name} // '',
246         author               => $c->{author},
247         barcode              => $c->{barcode},
248         type_for_stat          => $type_for_stat || q{},
249         itemtype_description   => $itemtype || q{},
250         recordtype_description => $recordtype || q{},
251         collection           => $collection,
252         location             => $location,
253         homebranch           => $c->{homebranch},
254         itemnotes            => $c->{itemnotes},
255         itemnotes_nonpublic  => $c->{itemnotes_nonpublic},
256         branchcode           => $c->{branchcode},
257         branchname           => $c->{branchname},
258         itemcallnumber       => $c->{itemcallnumber} || q{},
259         copynumber           => $c->{copynumber} || q{},
260         charge         => $charge,
261         fine           => $fine,
262         price          => $c->{replacementprice} || q{},
263         can_renew      => $can_renew,
264         can_renew_error     => $can_renew_error,
265         can_renew_date      => $can_renew_date,
266         itemnumber          => $c->{itemnumber},
267         borrowernumber      => $c->{borrowernumber},
268         biblionumber        => $c->{biblionumber},
269         issuedate           => $c->{issuedate},
270         date_due            => $c->{date_due},
271         date_due_overdue    => $c->{date_due_overdue} ? JSON::true : JSON::false,
272         timestamp           => $c->{timestamp},
273         onsite_checkout     => $c->{onsite_checkout},
274         enumchron           => $c->{enumchron},
275         renewals_count      => $renewals_count,
276         renewals_allowed    => $renewals_allowed || 0,
277         renewals_remaining  => $renewals_remaining,
278         unseen_count        => $unseen_count,
279         unseen_allowed      => $unseen_allowed,
280         unseen_remaining    => $unseen_remaining,
281
282         return_claim_id         => $c->{return_claim_id},
283         return_claim_notes      => $c->{return_claim_notes},
284         return_claim_created_on => $c->{return_claim_created_on},
285         return_claim_updated_on => $c->{return_claim_updated_on},
286         return_claim_created_on_formatted => $c->{return_claim_created_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_created_on} ) }) : undef,
287         return_claim_updated_on_formatted => $c->{return_claim_updated_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_updated_on} ) }) : undef,
288
289         issuedate_formatted => output_pref(
290             {
291                 dt          => dt_from_string( $c->{issuedate} ),
292                 as_due_date => 1
293             }
294         ),
295         date_due_formatted => output_pref(
296             {
297                 dt          => dt_from_string( $c->{date_due} ),
298                 as_due_date => 1
299             }
300         ),
301         lost    => $lost,
302         claims_returned => $claims_returned,
303         damaged => $damaged,
304         materials => $materials,
305         borrower => {
306             surname    => $c->{surname},
307             firstname  => $c->{firstname},
308             cardnumber => $c->{cardnumber},
309         },
310         issued_today => !$c->{not_issued_today},
311         recalled => $recalled,
312     };
313
314     if ( $c->{not_issued_today} ) {
315         push( @checkouts_previous, $checkout );
316     }
317     else {
318         push( @checkouts_today, $checkout );
319     }
320 }
321
322
323 @checkouts_today = sort { $a->{timestamp} cmp $b->{timestamp} } @checkouts_today;    # latest to earliest
324 @checkouts_today = reverse(@checkouts_today)
325   if ( C4::Context->preference('todaysIssuesDefaultSortOrder') eq 'desc' );      # earliest to latest
326
327 @checkouts_previous =
328   sort { $a->{date_due} cmp $b->{date_due} || $a->{timestamp} cmp $b->{timestamp} }
329   @checkouts_previous;                                                               # latest to earliest
330 @checkouts_previous = reverse(@checkouts_previous)
331   if ( C4::Context->preference('previousIssuesDefaultSortOrder') eq 'desc' );    # earliest to latest
332
333 my @checkouts = ( @checkouts_today, @checkouts_previous );
334
335 my $i = 1;
336 map { $_->{sort_order} = $i++ } @checkouts;
337
338
339 my $data;
340 $data->{'iTotalRecords'}        = scalar @checkouts;
341 $data->{'iTotalDisplayRecords'} = scalar @checkouts;
342 $data->{'sEcho'}                = $input->param('sEcho') || undef;
343 $data->{'aaData'}               = \@checkouts;
344
345 print to_json($data);