Bug 14697: Enhance the return claims feature
[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 ) =
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 @checkouts_today;
144 my @checkouts_previous;
145 while ( my $c = $sth->fetchrow_hashref() ) {
146     my ($charge) = GetIssuingCharges( $c->{itemnumber}, $c->{borrowernumber} );
147     my $fine = GetFine( $c->{itemnumber}, $c->{borrowernumber} );
148
149     my ( $can_renew, $can_renew_error ) =
150       CanBookBeRenewed( $c->{borrowernumber}, $c->{itemnumber} );
151     my $can_renew_date =
152       $can_renew_error && $can_renew_error eq 'too_soon'
153       ? output_pref(
154         {
155             dt => GetSoonestRenewDate( $c->{borrowernumber}, $c->{itemnumber} ),
156             as_due_date => 1
157         }
158       )
159       : undef;
160
161     my ( $renewals_count, $renewals_allowed, $renewals_remaining ) =
162       GetRenewCount( $c->{borrowernumber}, $c->{itemnumber} );
163
164     my $itemtype = Koha::ItemTypes->find( $item_level_itypes ? $c->{itype} : $c->{itemtype} );
165     my $location;
166     if ( $c->{location} ) {
167         my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $c->{location} });
168         $location = $av->count ? $av->next->lib : '';
169     }
170     my $collection;
171     if ( $c->{collection} ) {
172         my $av = Koha::AuthorisedValues->search({ category => 'CCODE', authorised_value => $c->{collection} });
173         $collection = $av->count ? $av->next->lib : '';
174     }
175     my $lost;
176     my $claims_returned;
177     if ( $c->{itemlost} ) {
178         my $av = Koha::AuthorisedValues->search({ category => 'LOST', authorised_value => $c->{itemlost} });
179         $lost = $av->count ? $av->next->lib : '';
180         $claims_returned = $c->{itemlost} eq $claims_returned_lost_value;
181     }
182     my $damaged;
183     if ( $c->{damaged} ) {
184         my $av = Koha::AuthorisedValues->search({ category => 'DAMAGED', authorised_value => $c->{damaged} });
185         $damaged = $av->count ? $av->next->lib : '';
186     }
187     my @subtitles = split(/ \| /, $c->{'subtitle'} // '' );
188     my $checkout = {
189         DT_RowId             => $c->{itemnumber} . '-' . $c->{borrowernumber},
190         title                => $c->{title},
191         subtitle             => \@subtitles,
192         medium               => $c->{medium} // '',
193         part_number          => $c->{part_number} // '',
194         part_name            => $c->{part_name} // '',
195         author               => $c->{author},
196         barcode              => $c->{barcode},
197         itemtype             => $item_level_itypes ? $c->{itype} : $c->{itemtype},
198         itemtype_description => $itemtype ? $itemtype->translated_description : q{},
199         collection           => $collection,
200         location             => $location,
201         homebranch           => $c->{homebranch},
202         itemnotes            => $c->{itemnotes},
203         itemnotes_nonpublic  => $c->{itemnotes_nonpublic},
204         branchcode           => $c->{branchcode},
205         branchname           => $c->{branchname},
206         itemcallnumber => $c->{itemcallnumber}   || q{},
207         charge         => $charge,
208         fine           => $fine,
209         price          => $c->{replacementprice} || q{},
210         can_renew      => $can_renew,
211         can_renew_error     => $can_renew_error,
212         can_renew_date      => $can_renew_date,
213         itemnumber          => $c->{itemnumber},
214         borrowernumber      => $c->{borrowernumber},
215         biblionumber        => $c->{biblionumber},
216         issuedate           => $c->{issuedate},
217         date_due            => $c->{date_due},
218         date_due_overdue    => $c->{date_due_overdue} ? JSON::true : JSON::false,
219         timestamp           => $c->{timestamp},
220         onsite_checkout     => $c->{onsite_checkout},
221         enumchron           => $c->{enumchron},
222         renewals_count      => $renewals_count,
223         renewals_allowed    => $renewals_allowed,
224         renewals_remaining  => $renewals_remaining,
225
226         return_claim_id         => $c->{return_claim_id},
227         return_claim_notes      => $c->{return_claim_notes},
228         return_claim_created_on => $c->{return_claim_created_on},
229         return_claim_updated_on => $c->{return_claim_updated_on},
230         return_claim_created_on_formatted => $c->{return_claim_created_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_created_on} ) }) : undef,
231         return_claim_updated_on_formatted => $c->{return_claim_updated_on} ? output_pref({ dt => dt_from_string( $c->{return_claim_updated_on} ) }) : undef,
232
233         issuedate_formatted => output_pref(
234             {
235                 dt          => dt_from_string( $c->{issuedate} ),
236                 as_due_date => 1
237             }
238         ),
239         date_due_formatted => output_pref(
240             {
241                 dt          => dt_from_string( $c->{date_due} ),
242                 as_due_date => 1
243             }
244         ),
245         lost    => $lost,
246         claims_returned => $claims_returned,
247         damaged => $damaged,
248         borrower => {
249             surname    => $c->{surname},
250             firstname  => $c->{firstname},
251             cardnumber => $c->{cardnumber},
252         },
253         issued_today => !$c->{not_issued_today},
254     };
255
256     if ( $c->{not_issued_today} ) {
257         push( @checkouts_previous, $checkout );
258     }
259     else {
260         push( @checkouts_today, $checkout );
261     }
262 }
263
264
265 @checkouts_today = sort { $a->{timestamp} cmp $b->{timestamp} } @checkouts_today;
266 @checkouts_today = reverse(@checkouts_today)
267   unless ( C4::Context->preference('todaysIssuesDefaultSortOrder') eq 'desc' );
268
269 @checkouts_previous = sort { $a->{date_due} cmp $b->{date_due} } @checkouts_previous;
270 @checkouts_previous = reverse(@checkouts_previous)
271   if ( C4::Context->preference('previousIssuesDefaultSortOrder') eq 'desc' );
272
273 my @checkouts = ( @checkouts_today, @checkouts_previous );
274
275 my $i = 1;
276 map { $_->{sort_order} = $i++ } @checkouts;
277
278
279 my $data;
280 $data->{'iTotalRecords'}        = scalar @checkouts;
281 $data->{'iTotalDisplayRecords'} = scalar @checkouts;
282 $data->{'sEcho'}                = $input->param('sEcho') || undef;
283 $data->{'aaData'}               = \@checkouts;
284
285 print to_json($data);