Bug 32401: Remove x-koha-query support
[koha.git] / members / paycollect.pl
1 #!/usr/bin/perl
2 # Copyright 2009,2010 PTFS Inc.
3 # Copyright 2011 PTFS-Europe Ltd
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 use URI::Escape qw( uri_escape uri_unescape );
22 use CGI qw ( -utf8 );
23
24 use C4::Context;
25 use C4::Auth qw( get_template_and_user );
26 use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers );
27 use C4::Accounts;
28 use C4::Koha;
29
30 use Koha::Cash::Registers;
31 use Koha::Patrons;
32 use Koha::Patron::Categories;
33 use Koha::AuthorisedValues;
34 use Koha::Account;
35 use Koha::Account::Lines;
36 use Koha::AdditionalFields;
37 use Koha::Token;
38 use Koha::DateUtils qw( output_pref );
39
40 my $input = CGI->new();
41
42 my $payment_id          = $input->param('payment_id');
43 my $writeoff_individual = $input->param('writeoff_individual');
44 my $change_given        = $input->param('change_given');
45 my $type                = scalar $input->param('type') || 'PAYMENT';
46
47 my $updatecharges_permissions = ($writeoff_individual || $type eq 'WRITEOFF') ? 'writeoff' : 'remaining_permissions';
48 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
49     {   template_name   => 'members/paycollect.tt',
50         query           => $input,
51         type            => 'intranet',
52         flagsrequired   => { borrowers => 'edit_borrowers', updatecharges => $updatecharges_permissions },
53     }
54 );
55
56 # get borrower details
57 my $borrowernumber = $input->param('borrowernumber');
58 my $logged_in_user = Koha::Patrons->find( $loggedinuser );
59 my $patron         = Koha::Patrons->find( $borrowernumber );
60 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
61
62 my $account        = $patron->account;
63 my $category       = $patron->category;
64 my $user           = $input->remote_user;
65
66 my $library_id = C4::Context->userenv->{'branch'};
67 my $total_due  = $account->outstanding_debits->total_outstanding;
68
69 my $total_paid      = $input->param('paid');
70 my $total_collected = $input->param('collected');
71
72 my $selected_lines = $input->param('selected'); # comes from pay.pl
73 my $pay_individual   = $input->param('pay_individual');
74 my $selected_accts   = $input->param('selected_accts'); # comes from paycollect.pl
75 my $payment_note = uri_unescape scalar $input->param('payment_note');
76 my $payment_type = scalar $input->param('payment_type');
77 my $accountlines_id;
78
79 my $cash_register_id = $input->param('cash_register');
80 if ( $pay_individual || $writeoff_individual ) {
81     if ($pay_individual) {
82         $template->param( pay_individual => 1 );
83     } elsif ($writeoff_individual) {
84         $template->param( writeoff_individual => 1 );
85     }
86     my $debit_type_code   = $input->param('debit_type_code');
87     $accountlines_id      = $input->param('accountlines_id');
88     my $amount            = $input->param('amount');
89     my $amountoutstanding = $input->param('amountoutstanding');
90     my $itemnumber  = $input->param('itemnumber');
91     my $description  = $input->param('description');
92     $total_due = $amountoutstanding;
93     $template->param(
94         debit_type_code    => $debit_type_code,
95         accountlines_id    => $accountlines_id,
96         amount            => $amount,
97         amountoutstanding => $amountoutstanding,
98         itemnumber        => $itemnumber,
99         individual_description => $description,
100         payment_note    => $payment_note,
101     );
102 } elsif ($selected_lines) {
103     $total_due = $input->param('amt');
104     $template->param(
105         selected_accts => $selected_lines,
106         amt            => $total_due,
107         selected_accts_notes => scalar $input->param('notes'),
108     );
109 }
110
111 my @selected_accountlines;
112 if ( $selected_accts ) {
113     if ( $selected_accts =~ /^([\d,]*).*/ ) {
114         $selected_accts = $1;    # ensure passing no junk
115     }
116     my @acc = split /,/, $selected_accts;
117
118     my $search_params = {
119         borrowernumber    => $borrowernumber,
120             amountoutstanding => { '<>' => 0 },
121             accountlines_id   => { 'in' => \@acc },
122     };
123
124     @selected_accountlines = Koha::Account::Lines->search(
125         $search_params,
126         { order_by => 'date' }
127     )->as_list;
128
129     my $sum = Koha::Account::Lines->search(
130         $search_params,
131         {
132             select => [ { sum => 'amountoutstanding' } ],
133             as     => [ 'total_amountoutstanding'],
134         }
135     );
136     $total_due = $sum->_resultset->first->get_column('total_amountoutstanding');
137 }
138
139 if ( $total_paid and $total_paid ne '0.00' ) {
140     $total_paid = $total_due if (abs($total_paid - $total_due) < 0.01) && C4::Context->preference('RoundFinesAtPayment');
141     if ( $total_paid < 0 or $total_paid > $total_due ) {
142         $template->param(
143             error_over => 1,
144             total_due => $total_due
145         );
146     } elsif ( $total_collected < $total_paid && !( $writeoff_individual || $type eq 'WRITEOFF' ) ) {
147         $template->param(
148             error_under => 1,
149             total_paid => $total_paid
150         );
151     } else {
152         output_and_exit( $input, $cookie, $template,  'wrong_csrf_token' )
153             unless Koha::Token->new->check_csrf( {
154                 session_id => $input->cookie('CGISESSID'),
155                 token  => scalar $input->param('csrf_token'),
156             });
157
158         my $url;
159         my $pay_result;
160         if ($pay_individual) {
161             my $line = Koha::Account::Lines->find($accountlines_id);
162             $pay_result = $account->pay(
163                 {
164                     lines        => [$line],
165                     amount       => $total_paid,
166                     library_id   => $library_id,
167                     note         => $payment_note,
168                     interface    => C4::Context->interface,
169                     payment_type => $payment_type,
170                     cash_register => $cash_register_id
171                 }
172             );
173             $payment_id = $pay_result->{payment_id};
174
175             my @additional_fields;
176             my $accountline_fields = Koha::AdditionalFields->search({ tablename => 'accountlines:credit' });
177             while ( my $field = $accountline_fields->next ) {
178                 my $value = $input->param('additional_field_' . $field->id);
179                 if (defined $value) {
180                     push @additional_fields, {
181                         id => $field->id,
182                         value => $value,
183                     };
184                 }
185             }
186             if (@additional_fields) {
187                 my $payment = Koha::Account::Lines->find($payment_id);
188                 $payment->set_additional_fields(\@additional_fields);
189             }
190
191
192             $url = "/cgi-bin/koha/members/pay.pl";
193         } else {
194             if ($selected_accts) {
195                 if ( $total_paid > $total_due ) {
196                     $template->param(
197                         error_over => 1,
198                         total_due => $total_due
199                     );
200                 } else {
201                     my $note = $input->param('selected_accts_notes');
202
203                     $pay_result = $account->pay(
204                         {
205                             type         => $type,
206                             amount       => $total_paid,
207                             library_id   => $library_id,
208                             lines        => \@selected_accountlines,
209                             note         => $note,
210                             interface    => C4::Context->interface,
211                             payment_type => $payment_type,
212                             cash_register => $cash_register_id
213                         }
214                     );
215                 }
216                 $payment_id = $pay_result->{payment_id};
217             }
218             else {
219                 my $note = $input->param('selected_accts_notes');
220                 $pay_result = $account->pay(
221                     {
222                         amount       => $total_paid,
223                         library_id   => $library_id,
224                         note         => $note,
225                         payment_type => $payment_type,
226                         interface    => C4::Context->interface,
227                         payment_type => $payment_type,
228                         cash_register => $cash_register_id
229                     }
230                 );
231                 $payment_id = $pay_result->{payment_id};
232             }
233             $payment_id = $pay_result->{payment_id};
234
235             my @additional_fields;
236             my $accountline_fields = Koha::AdditionalFields->search({ tablename => 'accountlines:credit' });
237             while ( my $field = $accountline_fields->next ) {
238                 my $value = $input->param('additional_field_' . $field->id);
239                 if (defined $value) {
240                     push @additional_fields, {
241                         id => $field->id,
242                         value => $value,
243                     };
244                 }
245             }
246             if (@additional_fields) {
247                 my $payment = Koha::Account::Lines->find($payment_id);
248                 $payment->set_additional_fields(\@additional_fields);
249             }
250
251             $url = "/cgi-bin/koha/members/boraccount.pl";
252         }
253         # It's possible renewals took place, parse any renew results
254         # and pass on
255         my @renew_result = ();
256         foreach my $ren( @{$pay_result->{renew_result}} ) {
257             my $str = "renew_result=$ren->{itemnumber},$ren->{success},";
258             my $app = $ren->{success} ?
259                 uri_escape(
260                     output_pref({ dt => $ren->{due_date}, as_due_date => 1 })
261                 ) : $ren->{error};
262                 push @renew_result, "${str}${app}";
263         }
264         my $append = scalar @renew_result ? '&' . join('&', @renew_result) : '';
265
266         $url .= "?borrowernumber=$borrowernumber&payment_id=$payment_id&change_given=${change_given}${append}";
267
268         print $input->redirect($url);
269     }
270 } else {
271     $total_paid = '0.00';    #TODO not right with pay_individual
272 }
273
274 if ( $input->param('error_over') ) {
275     $template->param( error_over => 1, total_due => scalar $input->param('amountoutstanding') );
276 }
277
278 $template->param(
279     payment_id => $payment_id,
280
281     type           => $type,
282     borrowernumber => $borrowernumber,    # some templates require global
283     patron         => $patron,
284     total          => $total_due,
285
286     csrf_token => Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID') } ),
287     available_additional_fields => [ Koha::AdditionalFields->search({ tablename => 'accountlines:credit' })->as_list ],
288 );
289
290 output_html_with_http_headers $input, $cookie, $template->output;