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