Bug 36792: Limit POSIX imports
[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.issue_id,
71         issues.issuedate,
72         issues.date_due,
73         issues.date_due < now() as date_due_overdue,
74         issues.timestamp,
75
76         issues.onsite_checkout,
77
78         biblio.biblionumber,
79         biblio.title,
80         biblio.subtitle,
81         biblio.medium,
82         biblio.part_number,
83         biblio.part_name,
84         biblio.author,
85
86         items.itemnumber,
87         items.barcode,
88         branches2.branchname AS homebranch,
89         items.itemnotes,
90         items.itemnotes_nonpublic,
91         items.itemcallnumber,
92         items.copynumber,
93         items.replacementprice,
94
95         issues.branchcode,
96         branches.branchname,
97
98         items.itype,
99         biblioitems.itemtype,
100
101         items.ccode AS collection,
102
103         borrowers.borrowernumber,
104         borrowers.surname,
105         borrowers.firstname,
106         borrowers.cardnumber,
107
108         items.itemlost,
109         items.damaged,
110         items.location,
111         items.enumchron,
112         items.materials,
113
114         DATEDIFF( issues.issuedate, CURRENT_DATE() ) AS not_issued_today,
115
116         return_claims.id AS return_claim_id,
117         return_claims.notes AS return_claim_notes,
118         return_claims.created_on AS return_claim_created_on,
119         return_claims.updated_on AS return_claim_updated_on
120
121     FROM issues
122         LEFT JOIN items USING ( itemnumber )
123         LEFT JOIN biblio USING ( biblionumber )
124         LEFT JOIN biblioitems USING ( biblionumber )
125         LEFT JOIN borrowers USING ( borrowernumber )
126         LEFT JOIN branches ON ( issues.branchcode = branches.branchcode )
127         LEFT JOIN branches branches2 ON ( items.homebranch = branches2.branchcode )
128         LEFT JOIN return_claims USING ( issue_id )
129     WHERE issues.borrowernumber
130 ';
131
132 if ( @borrowernumber == 1 ) {
133     $sql .= '= ?';
134 }
135 else {
136     $sql .= ' IN (' . join( ',', ('?') x @borrowernumber ) . ') ';
137 }
138 push( @parameters, @borrowernumber );
139
140 $sql .= " ORDER BY $sorting_column $sorting_direction ";
141
142 my $dbh = C4::Context->dbh();
143 my $sth = $dbh->prepare($sql);
144 $sth->execute(@parameters);
145
146 my $item_level_itypes = C4::Context->preference('item-level_itypes');
147 my $claims_returned_lost_value = C4::Context->preference('ClaimReturnedLostValue');
148 my $confirm_parts_required = C4::Context->preference("CircConfirmItemParts");
149
150 my $itemtypes = { map { $_->{itemtype} => $_->{translated_description} } @{ Koha::ItemTypes->search_with_localization->unblessed } };
151
152 my @checkouts_today;
153 my @checkouts_previous;
154 while ( my $c = $sth->fetchrow_hashref() ) {
155     my ($charge) = GetIssuingCharges( $c->{itemnumber}, $c->{borrowernumber} );
156     my $fine = GetFine( $c->{itemnumber}, $c->{borrowernumber} );
157
158     my $checkout_obj = Koha::Checkouts->find( $c->{issue_id} );
159     my ( $can_renew, $can_renew_error, $info ) =
160       CanBookBeRenewed( $checkout_obj->patron, $checkout_obj );
161     my $can_renew_date =
162       $can_renew_error && $can_renew_error eq 'too_soon'
163       ? output_pref(
164         {
165             dt => $info->{soonest_renew_date},
166             as_due_date => 1
167         }
168       )
169       : undef;
170
171     my (
172         $renewals_count,
173         $renewals_allowed,
174         $renewals_remaining,
175         $unseen_count,
176         $unseen_allowed,
177         $unseen_remaining
178     ) =
179       GetRenewCount( $c->{borrowernumber}, $c->{itemnumber} );
180
181     my ( $itemtype, $recordtype, $type_for_stat );
182     $itemtype      = $itemtypes->{ $c->{itype} }    if $c->{itype};
183     $recordtype    = $itemtypes->{ $c->{itemtype} } if $c->{itemtype};
184     $type_for_stat = $item_level_itypes ? $itemtype : $recordtype;
185
186     my $location;
187     if ( $c->{location} ) {
188         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
189             { kohafield => 'items.location', authorised_value => $c->{location} } );
190         $location = $av->{lib} ? $av->{lib} : '';
191     }
192     my $collection;
193     if ( $c->{collection} ) {
194         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
195             { kohafield => 'items.ccode', authorised_value => $c->{collection} } );
196         $collection = $av->{lib} ? $av->{lib} : '';
197     }
198     my $lost;
199     my $claims_returned;
200     if ( $c->{itemlost} ) {
201         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
202             { kohafield => 'items.itemlost', authorised_value => $c->{itemlost} } );
203         $lost            = $av->{lib} ? $av->{lib} : '';
204         $claims_returned = $c->{itemlost} eq $claims_returned_lost_value;
205     }
206     my $damaged;
207     if ( $c->{damaged} ) {
208         my $av = Koha::AuthorisedValues->get_description_by_koha_field(
209             { kohafield => 'items.damaged', authorised_value => $c->{damaged} } );
210         $damaged = $av->{lib} ? $av->{lib} : '';
211     }
212     my $materials;
213     if ( $c->{materials} && $confirm_parts_required ) {
214         my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $c->{materials} });
215         $materials = $descriptions->{lib} // $c->{materials};
216     }
217     my @subtitles = split(/ \| /, $c->{'subtitle'} // '' );
218
219     my $recalled = 0;
220     if ( C4::Context->preference('UseRecalls') ) {
221         my $item = Koha::Items->find( $c->{itemnumber} );
222         my $recall = undef;
223         $recall = $item->check_recalls if $item->can_be_waiting_recall;
224         if ( defined $recall ) {
225             if ( $recall->item_level ) {
226                 if ( $recall->item_id == $c->{itemnumber} ) {
227                     # item-level recall on this item
228                     $recalled = 1;
229                 } else {
230                     $recalled = 0;
231                 }
232             } else {
233                 # biblio-level recall, but don't want to mark recalled if the recall has been allocated a different item
234                 if ( !$recall->waiting ) {
235                     $recalled = 1;
236                 }
237             }
238         }
239     }
240
241     my $checkout = {
242         DT_RowId             => $c->{itemnumber} . '-' . $c->{borrowernumber},
243         title                => $c->{title},
244         subtitle             => \@subtitles,
245         medium               => $c->{medium} // '',
246         part_number          => $c->{part_number} // '',
247         part_name            => $c->{part_name} // '',
248         author               => $c->{author},
249         barcode              => $c->{barcode},
250         type_for_stat          => $type_for_stat || q{},
251         itemtype_description   => $itemtype || q{},
252         recordtype_description => $recordtype || q{},
253         collection           => $collection,
254         location             => $location,
255         homebranch           => $c->{homebranch},
256         itemnotes            => $c->{itemnotes},
257         itemnotes_nonpublic  => $c->{itemnotes_nonpublic},
258         branchcode           => $c->{branchcode},
259         branchname           => $c->{branchname},
260         itemcallnumber       => $c->{itemcallnumber} || q{},
261         copynumber           => $c->{copynumber} || q{},
262         charge         => $charge,
263         fine           => $fine,
264         price          => $c->{replacementprice} || q{},
265         can_renew      => $can_renew,
266         can_renew_error     => $can_renew_error,
267         can_renew_date      => $can_renew_date,
268         itemnumber          => $c->{itemnumber},
269         borrowernumber      => $c->{borrowernumber},
270         biblionumber        => $c->{biblionumber},
271         issuedate           => $c->{issuedate},
272         date_due            => $c->{date_due},
273         date_due_overdue    => $c->{date_due_overdue} ? JSON::true : JSON::false,
274         timestamp           => $c->{timestamp},
275         onsite_checkout     => $c->{onsite_checkout},
276         enumchron           => $c->{enumchron},
277         renewals_count      => $renewals_count,
278         renewals_allowed    => $renewals_allowed || 0,
279         renewals_remaining  => $renewals_remaining,
280         unseen_count        => $unseen_count,
281         unseen_allowed      => $unseen_allowed,
282         unseen_remaining    => $unseen_remaining,
283
284         return_claim_id         => $c->{return_claim_id},
285         return_claim_notes      => $c->{return_claim_notes},
286         return_claim_created_on => $c->{return_claim_created_on},
287         return_claim_updated_on => $c->{return_claim_updated_on},
288         return_claim_created_on_formatted => $c->{return_claim_created_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_created_on} ) }) : undef,
289         return_claim_updated_on_formatted => $c->{return_claim_updated_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_updated_on} ) }) : undef,
290
291         issuedate_formatted => output_pref(
292             {
293                 dt          => dt_from_string( $c->{issuedate} ),
294                 as_due_date => 1
295             }
296         ),
297         date_due_formatted => output_pref(
298             {
299                 dt          => dt_from_string( $c->{date_due} ),
300                 as_due_date => 1
301             }
302         ),
303         lost    => $lost,
304         claims_returned => $claims_returned,
305         damaged => $damaged,
306         materials => $materials,
307         borrower => {
308             surname    => $c->{surname},
309             firstname  => $c->{firstname},
310             cardnumber => $c->{cardnumber},
311         },
312         issued_today => !$c->{not_issued_today},
313         recalled => $recalled,
314     };
315
316     if ( $c->{not_issued_today} ) {
317         push( @checkouts_previous, $checkout );
318     }
319     else {
320         push( @checkouts_today, $checkout );
321     }
322 }
323
324
325 @checkouts_today = sort { $a->{timestamp} cmp $b->{timestamp} } @checkouts_today;    # latest to earliest
326 @checkouts_today = reverse(@checkouts_today)
327   if ( C4::Context->preference('todaysIssuesDefaultSortOrder') eq 'desc' );      # earliest to latest
328
329 @checkouts_previous =
330   sort { $a->{date_due} cmp $b->{date_due} || $a->{timestamp} cmp $b->{timestamp} }
331   @checkouts_previous;                                                               # latest to earliest
332 @checkouts_previous = reverse(@checkouts_previous)
333   if ( C4::Context->preference('previousIssuesDefaultSortOrder') eq 'desc' );    # earliest to latest
334
335 my @checkouts = ( @checkouts_today, @checkouts_previous );
336
337 my $i = 1;
338 map { $_->{sort_order} = $i++ } @checkouts;
339
340
341 my $data;
342 $data->{'iTotalRecords'}        = scalar @checkouts;
343 $data->{'iTotalDisplayRecords'} = scalar @checkouts;
344 $data->{'sEcho'}                = $input->param('sEcho') || undef;
345 $data->{'aaData'}               = \@checkouts;
346
347 print to_json($data);