Revert "Zahlungseingang: Offene Rechnungen immer beim Update laden."
[kivitendo-erp.git] / bin / mozilla / cp.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Payment module
31 #
32 #======================================================================
33
34 use SL::CP;
35 use SL::IS;
36 use SL::IR;
37 use SL::AR;
38 use SL::AP;
39 use Data::Dumper;
40 use strict;
41 #use warnings;
42
43 require "bin/mozilla/arap.pl";
44 require "bin/mozilla/common.pl";
45
46 our ($form, %myconfig, $lxdebug, $locale, $auth);
47
48 1;
49
50 # end of main
51
52 sub payment {
53   $lxdebug->enter_sub();
54
55   $auth->assert('cash');
56
57   my (@curr);
58
59   $form->{ARAP} = ($form->{type} eq 'receipt') ? "AR" : "AP";
60   $form->{arap} = lc $form->{ARAP};
61
62   # setup customer/vendor selection for open invoices
63   if ($form->{all_vc}) {
64     # Dieser Zweig funktioniert derzeit NIE. Ggf. ganz raus oder
65     # alle offenen Zahlungen wieder korrekt anzeigen. jb 12.10.2010
66     $form->all_vc(\%myconfig, $form->{vc}, $form->{ARAP});
67   } else {
68     CP->get_openvc(\%myconfig, \%$form);
69   }
70   # Auswahlliste für vc zusammenbauen
71   # Erweiterung für schliessende option und erweiterung um value
72   # für bugfix 1771 (doppelte Leerzeichen werden nicht 'gepostet')
73   $form->{"select$form->{vc}"} = "";
74
75   if ($form->{"all_$form->{vc}"}) {
76     $form->{"select$form->{vc}"} .= "<option value=\"\"></option>\n";
77     # s.o. jb 12.10.2010
78     $form->{"$form->{vc}_id"} = $form->{"all_$form->{vc}"}->[0]->{id};
79     # hotfix for 2450. TODO remove legacy code and use L
80     map { $form->{"select$form->{vc}"} .= "<option value=\"$_->{name}--$_->{id}\">" . H($_->{name}) . "--$_->{id}</option>\n" }
81       @{ $form->{"all_$form->{vc}"} };
82   }
83   CP->paymentaccounts(\%myconfig, \%$form);
84
85   # Standard Konto für Umlaufvermögen
86   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
87   # Entsprechend präventiv die Auswahlliste für Kontonummer
88   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
89   # Wichtig: Auch das Template anpassen, damit hidden input korrekt die "
90   # escaped.
91   $form->{selectaccount} = "";
92   $form->{"select$form->{ARAP}"} = "";
93
94   map { $form->{selectaccount} .= "<option value=\"$_->{accno}--$_->{description}\">$_->{accno}--$_->{description}</option>\n";
95         $form->{account}        = "$_->{accno}--$_->{description}" if ($_->{accno} eq $accno_arap) } @{ $form->{PR}{"$form->{ARAP}_paid"} };
96
97   # Braucht man das hier überhaupt? Erstmal auskommentieren .. jan 18.12.2010
98   #  map {
99   #    $form->{"select$form->{ARAP}"} .=
100   #      "<option>$_->{accno}--$_->{description}\n"
101   #  } @{ $form->{PR}{ $form->{ARAP} } };
102   # ENDE LOESCHMICH in 2012
103
104   # currencies
105   # oldcurrency ist zwar noch hier als fragment enthalten, wird aber bei
106   # der aktualisierung der form auch nicht mitübernommen. das konzept
107   # old_$FOO habe ich auch noch nicht verstanden ...
108   # Ok. Wenn currency übernommen werden, dann in callback-string über-
109   # geben und hier reinparsen, oder besser multibox oder html auslagern?
110   # Antwort: form->currency wird mit oldcurrency oder curr[0] überschrieben
111   # Wofür macht das Sinn?
112   @curr = $form->get_all_currencies();
113   $form->{defaultcurrency} = $form->{currency} = $form->{oldcurrency} =
114     $form->get_default_currency(\%myconfig);
115
116   # Entsprechend präventiv die Auswahlliste für Währungen
117   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
118   $form->{selectcurrency} = "";
119   map { $form->{selectcurrency} .= "<option value=\"$_\">$_</option>\n" } @curr;
120
121
122   &form_header;
123   &form_footer;
124
125   $lxdebug->leave_sub();
126 }
127
128 sub form_header {
129   $lxdebug->enter_sub;
130
131   $auth->assert('cash');
132
133   my ($vc, $arap, $exchangerate);
134
135   if ($form->{ $form->{vc} } eq "") {
136     map { $form->{"addr$_"} = "" } (1 .. 4);
137   }
138
139   # sometimes it happens that values in customer arrive without the signs '--'
140   # but in order to select the right option field we need values with '--'
141   if ($form->{vc} eq "customer" && $form->{"all_$form->{vc}"}){
142     my ($customername) = split /--/, $form->{ $form->{vc} };
143     $form->{ $form->{vc} } = $customername . "--" . $form->{customer_id};
144   }
145   # bugfix 1771
146   # geändert von <option>asdf--2929
147   # nach:
148   #              <option value="asdf--2929">asdf--2929</option>
149   # offen: $form->{ARAP} kann raus?
150   for my $item ($form->{vc}, "account", "currency", $form->{ARAP}) {
151     $form->{"select$item"} =~ s/ selected//;
152     $form->{"select$item"} =~ s/option value="\Q$form->{$item}\E">\Q$form->{$item}\E/option selected value="$form->{$item}">$form->{$item}/;
153   }
154
155   $vc =
156     ($form->{"select$form->{vc}"})
157     ? qq|<select name=$form->{vc}>$form->{"select$form->{vc}"}\n</select>|
158     : qq|<input name=$form->{vc} size=35 value="$form->{$form->{vc}}">|;
159
160   $form->{openinvoices} = $form->{all_vc} ? "" : 1;
161
162   # $locale->text('AR')
163   # $locale->text('AP')
164
165   $form->header;
166
167   $arap = lc $form->{ARAP};
168
169   print $::form->parse_html_template('cp/form_header', {
170     is_customer => $form->{vc}   eq 'customer',
171     is_receipt  => $form->{type} eq 'receipt',
172     arap        => $arap,
173     vccontent   => $vc,
174   });
175
176   $lxdebug->leave_sub;
177 }
178
179 sub list_invoices {
180   $::lxdebug->enter_sub;
181   $::auth->assert('cash');
182
183   my @columns = qw(amount due paid invnumber id transdate checked);
184   my (@invoices, %total);
185   for my $i (1 .. $::form->{rowcount}) {
186     push @invoices, +{ map { $_ => $::form->{"$_\_$i"} } @columns };
187     $total{$_} += $invoices[-1]{$_} = $::form->parse_amount(\%::myconfig, $invoices[-1]{$_}) for qw(amount due paid);
188   }
189
190   print $::form->parse_html_template('cp/invoices', {
191     invoices => \@invoices,
192     totals   => \%total,
193   });
194
195   $::lxdebug->leave_sub;
196 }
197
198 sub form_footer {
199   $::lxdebug->enter_sub;
200   $::auth->assert('cash');
201
202   print $::form->parse_html_template('cp/form_footer');
203
204   $::lxdebug->leave_sub;
205 }
206
207 sub update {
208   $lxdebug->enter_sub();
209
210   $auth->assert('cash');
211
212   my ($new_name_selected) = @_;
213
214   my ($buysell, $newvc, $updated, $exchangerate, $amount);
215
216   if ($form->{vc} eq 'customer') {
217     $buysell = "buy";
218   } else {
219     $buysell = "sell";
220   }
221
222   # if we switched to all_vc
223   # funktioniert derzeit nicht 12.10.2010 jb
224   if ($form->{all_vc} ne $form->{oldall_vc}) {
225
226     $form->{openinvoices} = ($form->{all_vc}) ? 0 : 1;
227
228     $form->{"select$form->{vc}"} = "";
229
230     if ($form->{all_vc}) {
231       $form->all_vc(\%myconfig, $form->{vc}, $form->{ARAP});
232
233       if ($form->{"all_$form->{vc}"}) {
234         map {
235           $form->{"select$form->{vc}"} .=
236             "<option>$_->{name}--$_->{id}\n"
237         } @{ $form->{"all_$form->{vc}"} };
238       }
239     } else {  # ab hier wieder ausgeführter code (s.o.):
240       CP->get_openvc(\%myconfig, \%$form);
241
242       if ($form->{"all_$form->{vc}"}) {
243         $newvc =
244           qq|$form->{"all_$form->{vc}"}[0]->{name}--$form->{"all_$form->{vc}"}[0]->{id}|;
245         map {
246           $form->{"select$form->{vc}"} .=
247             "<option>$_->{name}--$_->{id}\n"
248         } @{ $form->{"all_$form->{vc}"} };
249       }
250
251       # if the name is not the same
252       if ($form->{"select$form->{vc}"} !~ /$form->{$form->{vc}}/) {
253         $form->{ $form->{vc} } = $newvc;
254       }
255     }
256   }
257
258   # search by customernumber
259   # the customernumber has to be correct otherwise nothing is found
260   if ($form->{vc} eq 'customer' and $form->{customernumber} and $form->{ARAP} eq 'AR') {
261     $form->{open} ='Y'; # only open invoices
262     # ar_transactions automatically searches by $form->{customer_id} or else
263     # $form->{customer} if available, and these variables will always be set
264     # so we have to empty these values first
265     $form->{customer_id} = '';
266     $form->{customer} = '';
267     AR->ar_transactions(\%myconfig, \%$form);
268
269     # Here we just take the first returned value even if the custumernumber
270     # may not be unique
271     $form->{customer} = $form->{AR}[0]{name};
272     $form->{customer_id} = $form->{AR}[0]{customer_id};
273   }
274
275   # search by invoicenumber,
276   if ($form->{invnumber}) {
277     $form->{open} ='Y'; # only open invoices
278     if ($form->{ARAP} eq 'AR'){
279       # ar_transactions automatically searches by $form->{customer_id} or else
280       # $form->{customer} if available, and these variables will always be set
281       # so we have to empty these values first
282       $form->{customer_id} = '';
283       $form->{customer} = '';
284       AR->ar_transactions(\%myconfig, \%$form);
285
286       # if you search for invoice '11' ar_transactions will also match invoices
287       # 112, 211, ... due to the LIKE
288
289       # so there is now an extra loop that tries to match the invoice number
290       # exactly among all returned results, and then passes the customer_id instead of the name
291       # because the name may not be unique
292
293       my $found_exact_invnumber_match = 0;
294       foreach my $i ( @{ $form->{AR} } ) {
295         next unless $i->{invnumber} eq $form->{invnumber};
296         # found exactly matching invnumber
297         $form->{$form->{vc}} = $i->{name};
298         $form->{customer_id} = $i->{customer_id};
299         #$form->{"old${form->{vc}"} = $i->{customer_id};
300         $found_exact_invnumber_match = 1;
301       };
302
303       unless ( $found_exact_invnumber_match ) {
304         # use first returned entry, may not be the correct one if invnumber doesn't
305         # match uniquely
306         $form->{$form->{vc}} = $form->{AR}[0]{name};
307         $form->{customer_id} = $form->{AR}[0]{customer_id};
308       };
309     } else {
310       # s.o. nur für zahlungsausgang
311       AP->ap_transactions(\%myconfig, \%$form);
312       $form->{$form->{vc}} = $form->{AP}[0]{name};
313     }
314   }
315
316   # determine customer/vendor
317   if ( $form->{customer_id} and ($form->{invnumber} or $form->{customernumber}) ) {
318     # we already know the exact customer_id, so fill $form with customer data
319     IS->get_customer(\%myconfig, \%$form);
320     $updated = 1;
321   } else {
322     # check_name is called with "customer" or "vendor" and otherwise uses contents of $form
323     # check_name also runs get_customer/get_vendor
324     $updated = &check_name($form->{vc});
325   };
326
327   if ($new_name_selected || $updated) {
328     # get open invoices from ar/ap using $form->{vc} and a.${vc}_id, i.e. customer_id
329     CP->get_openinvoices(\%myconfig, \%$form);
330     ($newvc) = split /--/, $form->{ $form->{vc} };
331     $form->{"old$form->{vc}"} = qq|$newvc--$form->{"$form->{vc}_id"}|;
332     $updated = 1;
333   }
334
335   if ($form->{currency} ne $form->{oldcurrency}) {
336     $form->{oldcurrency} = $form->{currency};
337     if (!$updated) {
338       CP->get_openinvoices(\%myconfig, \%$form);
339       $updated = 1;
340     }
341   }
342
343   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
344     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
345   }
346   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{datepaid}, $buysell);
347   $form->{exchangerate} = $form->{forex} if $form->{forex};
348
349   $amount = $form->{amount} = $form->parse_amount(\%myconfig, $form->{amount});
350
351   if ($updated) {
352     $form->{rowcount} = 0;
353
354     $form->{queued} = "";
355
356     my $i = 0;
357     foreach my $ref (@{ $form->{PR} }) {
358       $i++;
359       $form->{"id_$i"}        = $ref->{id};
360       $form->{"invnumber_$i"} = $ref->{invnumber};
361       $form->{"transdate_$i"} = $ref->{transdate};
362       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
363       $form->{"amount_$i"} = $ref->{amount} / $ref->{exchangerate};
364       $form->{"due_$i"}    =
365         ($ref->{amount} - $ref->{paid}) / $ref->{exchangerate};
366       $form->{"checked_$i"} = "";
367       $form->{"paid_$i"}    = "";
368
369       # need to format
370       map {
371         $form->{"${_}_$i"} =
372           $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
373       } qw(amount due);
374
375     }
376     $form->{rowcount} = $i;
377   }
378
379   # recalculate
380
381   # Modified from $amount = $form->{amount} by J.Zach to update amount to total
382   # payment amount in Zahlungsausgang
383   $amount = 0;
384   for my $i (1 .. $form->{rowcount}) {
385
386     map {
387       $form->{"${_}_$i"} =
388         $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
389     } qw(amount due paid);
390
391     if ($form->{"checked_$i"}) {
392
393       # calculate paid_$i
394       if (!$form->{"paid_$i"}) {
395         $form->{"paid_$i"} = $form->{"due_$i"};
396       }
397
398       # Modified by J.Zach, see abovev
399       $amount += $form->{"paid_$i"};
400
401     } else {
402       $form->{"paid_$i"} = "";
403     }
404
405     map {
406       $form->{"${_}_$i"} =
407         $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
408     } qw(amount due paid);
409
410   }
411
412   # Line added by J.Zach, see above
413   $form->{amount}=$amount;
414
415   &form_header;
416   &list_invoices;
417   &form_footer;
418
419   $lxdebug->leave_sub();
420 }
421
422 sub post {
423   $lxdebug->enter_sub();
424
425   $auth->assert('cash');
426
427   &check_form;
428
429   if ($form->{currency} ne $form->{defaultcurrency}) {
430     $form->error($locale->text('Exchangerate missing!'))
431       unless $form->{exchangerate};
432   }
433
434   # Beim Aktualisieren wird das Konto übernommen
435   # und jetzt auch Beleg und Datum
436   $form->{callback} = "cp.pl?action=payment&vc=$form->{vc}&type=$form->{type}&account=$form->{account}&$form->{currency}" .
437                       "&datepaid=$form->{datepaid}&source=$form->{source}";
438
439   my $msg1 = $::form->{type} eq 'receipt' ? $::locale->text("Receipt posted!") : $::locale->text("Payment posted!");
440   my $msg2 = $::form->{type} eq 'receipt' ? $::locale->text("Cannot post Receipt!") : $::locale->text("Cannot post Payment!");
441
442   # Die Nachrichten (Receipt posted!) werden nicht angezeigt.
443   # Entweder wieder aktivieren oder komplett rausnehmen
444   $form->redirect($msg1) if (CP->process_payment(\%::myconfig, $::form));
445   $form->error($msg2);
446
447   $lxdebug->leave_sub();
448 }
449
450 sub check_form {
451   $lxdebug->enter_sub();
452
453   $auth->assert('cash');
454
455   my ($closedto, $datepaid, $amount);
456
457   &check_name($form->{vc});
458
459   if ($form->{currency} ne $form->{oldcurrency}) {
460     &update;
461     ::end_of_request();
462   }
463   $form->error($locale->text('Date missing!')) unless $form->{datepaid};
464   my $selected_check = 1;
465   for my $i (1 .. $form->{rowcount}) {
466     next unless $form->{"checked_$i"};
467     if (abs($form->parse_amount(\%myconfig, $form->{"paid_$i"}, 2)) < 0.01) {
468       $form->error($locale->text('Row #1: amount has to be different from zero.', $i));
469     }
470     undef $selected_check;
471   }
472   $form->error($locale->text('No transaction selected!')) if $selected_check;
473
474   $closedto = $form->datetonum($form->{closedto}, \%myconfig);
475   $datepaid = $form->datetonum($form->{datepaid}, \%myconfig);
476
477   $form->error($locale->text('Cannot process payment for a closed period!'))
478     if ($form->date_closed($form->{"datepaid"}, \%myconfig));
479
480   $amount = $form->parse_amount(\%myconfig, $form->{amount});
481   $form->{amount} = $amount;
482
483   for my $i (1 .. $form->{rowcount}) {
484     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
485       $amount -= $form->parse_amount(\%myconfig, $form->{"paid_$i"});
486
487       push(@{ $form->{paid}      ||= [] }, $form->{"paid_$i"});
488       push(@{ $form->{due}       ||= [] }, $form->{"due_$i"});
489       push(@{ $form->{invnumber} ||= [] }, $form->{"invnumber_$i"});
490       push(@{ $form->{invdate}   ||= [] }, $form->{"transdate_$i"});
491     }
492   }
493
494   if ($form->round_amount($amount, 2) != 0) {
495     push(@{ $form->{paid} }, $form->format_amount(\%myconfig, $amount, 2));
496     push(@{ $form->{due} }, $form->format_amount(\%myconfig, 0, "0"));
497     push(@{ $form->{invnumber} },
498          ($form->{ARAP} eq 'AR')
499          ? $locale->text('Deposit')
500          : $locale->text('Prepayment'));
501     push(@{ $form->{invdate} }, $form->{datepaid});
502   }
503
504   $lxdebug->leave_sub();
505 }