Bug 27770: ES: Deprecated aggregation order key [_term] used, replaced by [_key]
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 get_session);
26 use C4::Circulation qw(GetIssuingCharges CanBookBeRenewed GetRenewCount GetSoonestRenewDate);
27 use C4::Overdues qw(GetFine);
28 use C4::Context;
29
30 use Koha::AuthorisedValues;
31 use Koha::DateUtils;
32 use Koha::ItemTypes;
33
34 my $input = new CGI;
35
36 my ( $auth_status, $sessionID ) = check_cookie_auth( $input->cookie('CGISESSID'));
37 if( $auth_status ne 'ok' ) {
38     print CGI::header( '-status' => '401' );
39     exit 0;
40 }
41
42 my $session   = get_session($sessionID);
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.replacementprice,
92
93         issues.branchcode,
94         branches.branchname,
95
96         items.itype,
97         biblioitems.itemtype,
98
99         items.ccode AS collection,
100
101         borrowers.borrowernumber,
102         borrowers.surname,
103         borrowers.firstname,
104         borrowers.cardnumber,
105
106         items.itemlost,
107         items.damaged,
108         items.location,
109         items.enumchron,
110
111         DATEDIFF( issues.issuedate, CURRENT_DATE() ) AS not_issued_today,
112
113         return_claims.id AS return_claim_id,
114         return_claims.notes AS return_claim_notes,
115         return_claims.created_on AS return_claim_created_on,
116         return_claims.updated_on AS return_claim_updated_on
117
118     FROM issues
119         LEFT JOIN items USING ( itemnumber )
120         LEFT JOIN biblio USING ( biblionumber )
121         LEFT JOIN biblioitems USING ( biblionumber )
122         LEFT JOIN borrowers USING ( borrowernumber )
123         LEFT JOIN branches ON ( issues.branchcode = branches.branchcode )
124         LEFT JOIN branches branches2 ON ( items.homebranch = branches2.branchcode )
125         LEFT JOIN return_claims USING ( issue_id )
126     WHERE issues.borrowernumber
127 ';
128
129 if ( @borrowernumber == 1 ) {
130     $sql .= '= ?';
131 }
132 else {
133     $sql .= ' IN (' . join( ',', ('?') x @borrowernumber ) . ') ';
134 }
135 push( @parameters, @borrowernumber );
136
137 $sql .= " ORDER BY $sorting_column $sorting_direction ";
138
139 my $dbh = C4::Context->dbh();
140 my $sth = $dbh->prepare($sql);
141 $sth->execute(@parameters);
142
143 my $item_level_itypes = C4::Context->preference('item-level_itypes');
144 my $claims_returned_lost_value = C4::Context->preference('ClaimReturnedLostValue');
145
146 my @checkouts_today;
147 my @checkouts_previous;
148 while ( my $c = $sth->fetchrow_hashref() ) {
149     my ($charge) = GetIssuingCharges( $c->{itemnumber}, $c->{borrowernumber} );
150     my $fine = GetFine( $c->{itemnumber}, $c->{borrowernumber} );
151
152     my ( $can_renew, $can_renew_error ) =
153       CanBookBeRenewed( $c->{borrowernumber}, $c->{itemnumber} );
154     my $can_renew_date =
155       $can_renew_error && $can_renew_error eq 'too_soon'
156       ? output_pref(
157         {
158             dt => GetSoonestRenewDate( $c->{borrowernumber}, $c->{itemnumber} ),
159             as_due_date => 1
160         }
161       )
162       : undef;
163
164     my ( $renewals_count, $renewals_allowed, $renewals_remaining ) =
165       GetRenewCount( $c->{borrowernumber}, $c->{itemnumber} );
166
167     my $type_for_stat = Koha::ItemTypes->find( $item_level_itypes ? $c->{itype} : $c->{itemtype} );
168     my $itemtype = Koha::ItemTypes->find( $c->{itype} );
169     my $recordtype = Koha::ItemTypes->find( $c->{itemtype} );
170     my $location;
171     if ( $c->{location} ) {
172         my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $c->{location} });
173         $location = $av->count ? $av->next->lib : '';
174     }
175     my $collection;
176     if ( $c->{collection} ) {
177         my $av = Koha::AuthorisedValues->search({ category => 'CCODE', authorised_value => $c->{collection} });
178         $collection = $av->count ? $av->next->lib : '';
179     }
180     my $lost;
181     my $claims_returned;
182     if ( $c->{itemlost} ) {
183         my $av = Koha::AuthorisedValues->search({ category => 'LOST', authorised_value => $c->{itemlost} });
184         $lost = $av->count ? $av->next->lib : '';
185         $claims_returned = $c->{itemlost} eq $claims_returned_lost_value;
186     }
187     my $damaged;
188     if ( $c->{damaged} ) {
189         my $av = Koha::AuthorisedValues->search({ category => 'DAMAGED', authorised_value => $c->{damaged} });
190         $damaged = $av->count ? $av->next->lib : '';
191     }
192     my @subtitles = split(/ \| /, $c->{'subtitle'} // '' );
193     my $checkout = {
194         DT_RowId             => $c->{itemnumber} . '-' . $c->{borrowernumber},
195         title                => $c->{title},
196         subtitle             => \@subtitles,
197         medium               => $c->{medium} // '',
198         part_number          => $c->{part_number} // '',
199         part_name            => $c->{part_name} // '',
200         author               => $c->{author},
201         barcode              => $c->{barcode},
202         type_for_stat        => $type_for_stat ? $type_for_stat->translated_description : q{},
203         itemtype_description => $itemtype ? $itemtype->translated_description : q{},
204         recordtype_description => $recordtype ? $recordtype->translated_description : q{},
205         collection           => $collection,
206         location             => $location,
207         homebranch           => $c->{homebranch},
208         itemnotes            => $c->{itemnotes},
209         itemnotes_nonpublic  => $c->{itemnotes_nonpublic},
210         branchcode           => $c->{branchcode},
211         branchname           => $c->{branchname},
212         itemcallnumber => $c->{itemcallnumber}   || q{},
213         charge         => $charge,
214         fine           => $fine,
215         price          => $c->{replacementprice} || q{},
216         can_renew      => $can_renew,
217         can_renew_error     => $can_renew_error,
218         can_renew_date      => $can_renew_date,
219         itemnumber          => $c->{itemnumber},
220         borrowernumber      => $c->{borrowernumber},
221         biblionumber        => $c->{biblionumber},
222         issuedate           => $c->{issuedate},
223         date_due            => $c->{date_due},
224         date_due_overdue    => $c->{date_due_overdue} ? JSON::true : JSON::false,
225         timestamp           => $c->{timestamp},
226         onsite_checkout     => $c->{onsite_checkout},
227         enumchron           => $c->{enumchron},
228         renewals_count      => $renewals_count,
229         renewals_allowed    => $renewals_allowed,
230         renewals_remaining  => $renewals_remaining,
231
232         return_claim_id         => $c->{return_claim_id},
233         return_claim_notes      => $c->{return_claim_notes},
234         return_claim_created_on => $c->{return_claim_created_on},
235         return_claim_updated_on => $c->{return_claim_updated_on},
236         return_claim_created_on_formatted => $c->{return_claim_created_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_created_on} ) }) : undef,
237         return_claim_updated_on_formatted => $c->{return_claim_updated_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_updated_on} ) }) : undef,
238
239         issuedate_formatted => output_pref(
240             {
241                 dt          => dt_from_string( $c->{issuedate} ),
242                 as_due_date => 1
243             }
244         ),
245         date_due_formatted => output_pref(
246             {
247                 dt          => dt_from_string( $c->{date_due} ),
248                 as_due_date => 1
249             }
250         ),
251         lost    => $lost,
252         claims_returned => $claims_returned,
253         damaged => $damaged,
254         borrower => {
255             surname    => $c->{surname},
256             firstname  => $c->{firstname},
257             cardnumber => $c->{cardnumber},
258         },
259         issued_today => !$c->{not_issued_today},
260     };
261
262     if ( $c->{not_issued_today} ) {
263         push( @checkouts_previous, $checkout );
264     }
265     else {
266         push( @checkouts_today, $checkout );
267     }
268 }
269
270
271 @checkouts_today = sort { $a->{timestamp} cmp $b->{timestamp} } @checkouts_today;    # latest to earliest
272 @checkouts_today = reverse(@checkouts_today)
273   if ( C4::Context->preference('todaysIssuesDefaultSortOrder') eq 'desc' );      # earliest to latest
274
275 @checkouts_previous =
276   sort { $a->{date_due} cmp $b->{date_due} || $a->{timestamp} cmp $b->{timestamp} }
277   @checkouts_previous;                                                               # latest to earliest
278 @checkouts_previous = reverse(@checkouts_previous)
279   if ( C4::Context->preference('previousIssuesDefaultSortOrder') eq 'desc' );    # earliest to latest
280
281 my @checkouts = ( @checkouts_today, @checkouts_previous );
282
283 my $i = 1;
284 map { $_->{sort_order} = $i++ } @checkouts;
285
286
287 my $data;
288 $data->{'iTotalRecords'}        = scalar @checkouts;
289 $data->{'iTotalDisplayRecords'} = scalar @checkouts;
290 $data->{'sEcho'}                = $input->param('sEcho') || undef;
291 $data->{'aaData'}               = \@checkouts;
292
293 print to_json($data);