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