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