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