Bug 26424: Better performance of svc/checkouts
[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 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 ) =
37   check_cookie_auth( $input->cookie('CGISESSID'));
38
39 my $session   = get_session($sessionID);
40 my $userid   = $session->param('id');
41
42 unless (haspermission($userid, { circulate => 'circulate_remaining_permissions' })
43     || haspermission($userid, { borrowers => 'edit_borrowers' })) {
44     exit 0;
45 }
46
47 my @sort_columns = qw/date_due title itype issuedate branchcode itemcallnumber/;
48
49 my @borrowernumber   = $input->multi_param('borrowernumber');
50 my $offset           = $input->param('iDisplayStart');
51 my $results_per_page = $input->param('iDisplayLength') || -1;
52
53 my $sorting_column = $input->param('iSortCol_0') || q{};
54 $sorting_column = ( $sorting_column && $sort_columns[$sorting_column] ) ? $sort_columns[$sorting_column] : 'issuedate';
55
56 my $sorting_direction = $input->param('sSortDir_0') || q{};
57 $sorting_direction = $sorting_direction eq 'asc' ? 'asc' : 'desc';
58
59 $results_per_page = undef if ( $results_per_page == -1 );
60
61 binmode STDOUT, ":encoding(UTF-8)";
62 print $input->header( -type => 'text/plain', -charset => 'UTF-8' );
63
64 my @parameters;
65 my $sql = '
66     SELECT
67         issues.issuedate,
68         issues.date_due,
69         issues.date_due < now() as date_due_overdue,
70         issues.timestamp,
71
72         issues.onsite_checkout,
73
74         biblio.biblionumber,
75         biblio.title,
76         biblio.subtitle,
77         biblio.medium,
78         biblio.part_number,
79         biblio.part_name,
80         biblio.author,
81
82         items.itemnumber,
83         items.barcode,
84         branches2.branchname AS homebranch,
85         items.itemnotes,
86         items.itemnotes_nonpublic,
87         items.itemcallnumber,
88         items.replacementprice,
89
90         issues.branchcode,
91         branches.branchname,
92
93         items.itype,
94         biblioitems.itemtype,
95
96         items.ccode AS collection,
97
98         borrowers.borrowernumber,
99         borrowers.surname,
100         borrowers.firstname,
101         borrowers.cardnumber,
102
103         items.itemlost,
104         items.damaged,
105         items.location,
106         items.enumchron,
107
108         DATEDIFF( issues.issuedate, CURRENT_DATE() ) AS not_issued_today,
109
110         return_claims.id AS return_claim_id,
111         return_claims.notes AS return_claim_notes,
112         return_claims.created_on AS return_claim_created_on,
113         return_claims.updated_on AS return_claim_updated_on
114
115     FROM issues
116         LEFT JOIN items USING ( itemnumber )
117         LEFT JOIN biblio USING ( biblionumber )
118         LEFT JOIN biblioitems USING ( biblionumber )
119         LEFT JOIN borrowers USING ( borrowernumber )
120         LEFT JOIN branches ON ( issues.branchcode = branches.branchcode )
121         LEFT JOIN branches branches2 ON ( items.homebranch = branches2.branchcode )
122         LEFT JOIN return_claims USING ( issue_id )
123     WHERE issues.borrowernumber
124 ';
125
126 if ( @borrowernumber == 1 ) {
127     $sql .= '= ?';
128 }
129 else {
130     $sql .= ' IN (' . join( ',', ('?') x @borrowernumber ) . ') ';
131 }
132 push( @parameters, @borrowernumber );
133
134 $sql .= " ORDER BY $sorting_column $sorting_direction ";
135
136 my $dbh = C4::Context->dbh();
137 my $sth = $dbh->prepare($sql);
138 $sth->execute(@parameters);
139
140 my $item_level_itypes = C4::Context->preference('item-level_itypes');
141 my $claims_returned_lost_value = C4::Context->preference('ClaimReturnedLostValue');
142
143 my $itemtypes = { map { $_->{itemtype} => $_->{translated_description} } @{ Koha::ItemTypes->search_with_localization->unblessed } };
144
145 my @checkouts_today;
146 my @checkouts_previous;
147 while ( my $c = $sth->fetchrow_hashref() ) {
148     my ($charge) = GetIssuingCharges( $c->{itemnumber}, $c->{borrowernumber} );
149     my $fine = GetFine( $c->{itemnumber}, $c->{borrowernumber} );
150
151     my ( $can_renew, $can_renew_error ) =
152       CanBookBeRenewed( $c->{borrowernumber}, $c->{itemnumber} );
153     my $can_renew_date =
154       $can_renew_error && $can_renew_error eq 'too_soon'
155       ? output_pref(
156         {
157             dt => GetSoonestRenewDate( $c->{borrowernumber}, $c->{itemnumber} ),
158             as_due_date => 1
159         }
160       )
161       : undef;
162
163     my ( $renewals_count, $renewals_allowed, $renewals_remaining ) =
164       GetRenewCount( $c->{borrowernumber}, $c->{itemnumber} );
165
166     my ( $itemtype, $recordtype, $type_for_stat );
167     $itemtype      = $itemtypes->{ $c->{itype} }    if $c->{itype};
168     $recordtype    = $itemtypes->{ $c->{itemtype} } if $c->{itemtype};
169     $type_for_stat = $item_level_itypes ? $itemtype : $recordtype;
170
171     my $location;
172     if ( $c->{location} ) {
173         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
174             { kohafield => 'items.location', authorised_value => $c->{location} } );
175         $location = $av->{lib} ? $av->{lib} : '';
176     }
177     my $collection;
178     if ( $c->{collection} ) {
179         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
180             { kohafield => 'items.ccode', authorised_value => $c->{collection} } );
181         $collection = $av->{lib} ? $av->{lib} : '';
182     }
183     my $lost;
184     my $claims_returned;
185     if ( $c->{itemlost} ) {
186         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
187             { kohafield => 'items.itemlost', authorised_value => $c->{itemlost} } );
188         $lost            = $av->{lib} ? $av->{lib} : '';
189         $claims_returned = $c->{itemlost} eq $claims_returned_lost_value;
190     }
191     my $damaged;
192     if ( $c->{damaged} ) {
193         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
194             { kohafield => 'items.damaged', authorised_value => $c->{damaged} } );
195         $damaged = $av->{lib} ? $av->{lib} : '';
196     }
197     my @subtitles = split(/ \| /, $c->{'subtitle'} // '' );
198     my $checkout = {
199         DT_RowId             => $c->{itemnumber} . '-' . $c->{borrowernumber},
200         title                => $c->{title},
201         subtitle             => \@subtitles,
202         medium               => $c->{medium} // '',
203         part_number          => $c->{part_number} // '',
204         part_name            => $c->{part_name} // '',
205         author               => $c->{author},
206         barcode              => $c->{barcode},
207         type_for_stat          => $type_for_stat || q{},
208         itemtype_description   => $itemtype || q{},
209         recordtype_description => $recordtype || q{},
210         collection           => $collection,
211         location             => $location,
212         homebranch           => $c->{homebranch},
213         itemnotes            => $c->{itemnotes},
214         itemnotes_nonpublic  => $c->{itemnotes_nonpublic},
215         branchcode           => $c->{branchcode},
216         branchname           => $c->{branchname},
217         itemcallnumber => $c->{itemcallnumber}   || q{},
218         charge         => $charge,
219         fine           => $fine,
220         price          => $c->{replacementprice} || q{},
221         can_renew      => $can_renew,
222         can_renew_error     => $can_renew_error,
223         can_renew_date      => $can_renew_date,
224         itemnumber          => $c->{itemnumber},
225         borrowernumber      => $c->{borrowernumber},
226         biblionumber        => $c->{biblionumber},
227         issuedate           => $c->{issuedate},
228         date_due            => $c->{date_due},
229         date_due_overdue    => $c->{date_due_overdue} ? JSON::true : JSON::false,
230         timestamp           => $c->{timestamp},
231         onsite_checkout     => $c->{onsite_checkout},
232         enumchron           => $c->{enumchron},
233         renewals_count      => $renewals_count,
234         renewals_allowed    => $renewals_allowed,
235         renewals_remaining  => $renewals_remaining,
236
237         return_claim_id         => $c->{return_claim_id},
238         return_claim_notes      => $c->{return_claim_notes},
239         return_claim_created_on => $c->{return_claim_created_on},
240         return_claim_updated_on => $c->{return_claim_updated_on},
241         return_claim_created_on_formatted => $c->{return_claim_created_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_created_on} ) }) : undef,
242         return_claim_updated_on_formatted => $c->{return_claim_updated_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_updated_on} ) }) : undef,
243
244         issuedate_formatted => output_pref(
245             {
246                 dt          => dt_from_string( $c->{issuedate} ),
247                 as_due_date => 1
248             }
249         ),
250         date_due_formatted => output_pref(
251             {
252                 dt          => dt_from_string( $c->{date_due} ),
253                 as_due_date => 1
254             }
255         ),
256         lost    => $lost,
257         claims_returned => $claims_returned,
258         damaged => $damaged,
259         borrower => {
260             surname    => $c->{surname},
261             firstname  => $c->{firstname},
262             cardnumber => $c->{cardnumber},
263         },
264         issued_today => !$c->{not_issued_today},
265     };
266
267     if ( $c->{not_issued_today} ) {
268         push( @checkouts_previous, $checkout );
269     }
270     else {
271         push( @checkouts_today, $checkout );
272     }
273 }
274
275
276 @checkouts_today = sort { $a->{timestamp} cmp $b->{timestamp} } @checkouts_today;    # latest to earliest
277 @checkouts_today = reverse(@checkouts_today)
278   if ( C4::Context->preference('todaysIssuesDefaultSortOrder') eq 'desc' );      # earliest to latest
279
280 @checkouts_previous =
281   sort { $a->{date_due} cmp $b->{date_due} || $a->{timestamp} cmp $b->{timestamp} }
282   @checkouts_previous;                                                               # latest to earliest
283 @checkouts_previous = reverse(@checkouts_previous)
284   if ( C4::Context->preference('previousIssuesDefaultSortOrder') eq 'desc' );    # earliest to latest
285
286 my @checkouts = ( @checkouts_today, @checkouts_previous );
287
288 my $i = 1;
289 map { $_->{sort_order} = $i++ } @checkouts;
290
291
292 my $data;
293 $data->{'iTotalRecords'}        = scalar @checkouts;
294 $data->{'iTotalDisplayRecords'} = scalar @checkouts;
295 $data->{'sEcho'}                = $input->param('sEcho') || undef;
296 $data->{'aaData'}               = \@checkouts;
297
298 print to_json($data);