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