Bugfix 1771 - Zahlungsausgang: Lieferant wird nicht ausgewählt, wenn Name 2 Leerzeich...
[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 strict;
40 #use warnings;
41
42 require "bin/mozilla/arap.pl";
43 require "bin/mozilla/common.pl";
44
45 our ($form, %myconfig, $lxdebug, $locale, $auth);
46
47 1;
48
49 # end of main
50
51 sub payment {
52   $lxdebug->enter_sub();
53
54   $auth->assert('cash');
55
56   my (@curr);
57
58   $form->{ARAP} = ($form->{type} eq 'receipt') ? "AR" : "AP";
59   $form->{arap} = lc $form->{ARAP};
60
61   # setup customer/vendor selection for open invoices
62   if ($form->{all_vc}) {
63     # Dieser Zweig funktioniert derzeit NIE. Ggf. ganz raus oder
64     # alle offenen Zahlungen wieder korrekt anzeigen. jb 12.10.2010
65     $form->all_vc(\%myconfig, $form->{vc}, $form->{ARAP});
66   } else {
67     CP->get_openvc(\%myconfig, \%$form);
68   }
69   # Auswahlliste für vc zusammenbauen
70   # Erweiterung für schliessende option und erweiterung um value
71   # für bugfix 1771 (doppelte Leerzeichen werden nicht 'gepostet')
72   $form->{"select$form->{vc}"} = "";
73
74   if ($form->{"all_$form->{vc}"}) {
75     # s.o. jb 12.10.2010
76     $form->{"$form->{vc}_id"} = $form->{"all_$form->{vc}"}->[0]->{id};
77     map { $form->{"select$form->{vc}"} .= "<option value=\"$_->{name}--$_->{id}\">$_->{name}--$_->{id}</option>\n" }
78       @{ $form->{"all_$form->{vc}"} };
79   }
80
81   CP->paymentaccounts(\%myconfig, \%$form);
82
83   # Standard Konto für Umlaufvermögen
84   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
85   # Entsprechend präventiv die Auswahlliste für Kontonummer 
86   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
87   # Wichtig: Auch das Template anpassen, damit hidden input korrekt die "
88   # escaped.
89   $form->{selectaccount} = "";
90   $form->{"select$form->{ARAP}"} = "";
91
92   map { $form->{selectaccount} .= "<option value=\"$_->{accno}--$_->{description}\">$_->{accno}--$_->{description}</option>\n";
93         $form->{account}        = "$_->{accno}--$_->{description}" if ($_->{accno} eq $accno_arap) } @{ $form->{PR}{"$form->{ARAP}_paid"} };
94
95   # Braucht man das hier überhaupt? Erstmal auskommentieren .. jan 18.12.2010
96   #  map {
97   #    $form->{"select$form->{ARAP}"} .=
98   #      "<option>$_->{accno}--$_->{description}\n"
99   #  } @{ $form->{PR}{ $form->{ARAP} } };
100   # ENDE LOESCHMICH in 2012
101
102   # currencies
103   # oldcurrency ist zwar noch hier als fragment enthalten, wird aber bei
104   # der aktualisierung der form auch nicht mitübernommen. das konzept
105   # old_$FOO habe ich auch noch nicht verstanden ...
106   # Ok. Wenn currency übernommen werden, dann in callback-string über-
107   # geben und hier reinparsen, oder besser multibox oder html auslagern?
108   # Antwort: form->currency wird mit oldcurrency oder curr[0] überschrieben
109   # Wofür macht das Sinn?
110   @curr = split(/:/, $form->{currencies});
111   chomp $curr[0];
112   $form->{defaultcurrency} = $form->{currency} = $form->{oldcurrency} =
113     $curr[0];
114
115   # Entsprechend präventiv die Auswahlliste für Währungen 
116   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
117   $form->{selectcurrency} = "";
118   map { $form->{selectcurrency} .= "<option value=\"$_\">$_</option>\n" } @curr;
119
120
121   &form_header;
122   &form_footer;
123
124   $lxdebug->leave_sub();
125 }
126
127 sub form_header {
128   $lxdebug->enter_sub;
129
130   $auth->assert('cash');
131
132   my ($vc, $arap, $exchangerate);
133   my ($onload);
134
135   if ($form->{ $form->{vc} } eq "") {
136     map { $form->{"addr$_"} = "" } (1 .. 4);
137   }
138   # bugfix 1771
139   # geändert von <option>asdf--2929
140   # nach:
141   #              <option value="asdf--2929">asdf--2929</option>
142   # offen: $form->{ARAP} kann raus?
143   for my $item ($form->{vc}, "account", "currency", $form->{ARAP}) {
144     $form->{"select$item"} =~ s/ selected//;
145     $form->{"select$item"} =~ s/option value="\Q$form->{$item}\E">\Q$form->{$item}\E/option selected value="$form->{$item}">$form->{$item}/;
146   }
147
148   $vc =
149     ($form->{"select$form->{vc}"})
150     ? qq|<select name=$form->{vc}>$form->{"select$form->{vc}"}\n</select>|
151     : qq|<input name=$form->{vc} size=35 value="$form->{$form->{vc}}">|;
152
153   $form->{openinvoices} = $form->{all_vc} ? "" : 1;
154
155   # $locale->text('AR')
156   # $locale->text('AP')
157
158   $form->header;
159
160   $arap = lc $form->{ARAP};
161   $onload = qq|focus()|;
162   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
163   $onload .= qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
164
165   print $::form->parse_html_template('cp/form_header', {
166     is_customer => $form->{vc}   eq 'customer',
167     is_receipt  => $form->{type} eq 'receipt',
168     onload      => $onload,
169     arap        => $arap,
170     vccontent   => $vc,
171   });
172
173   $lxdebug->leave_sub;
174 }
175
176 sub list_invoices {
177   $::lxdebug->enter_sub;
178   $::auth->assert('cash');
179
180   my @columns = qw(amount due paid invnumber id transdate checked);
181   my (@invoices, %total);
182   for my $i (1 .. $::form->{rowcount}) {
183     push @invoices, +{ map { $_ => $::form->{"$_\_$i"} } @columns };
184     $total{$_} += $invoices[-1]{$_} = $::form->parse_amount(\%::myconfig, $invoices[-1]{$_}) for qw(amount due paid);
185   }
186
187   print $::form->parse_html_template('cp/invoices', {
188     invoices => \@invoices,
189     totals   => \%total,
190   });
191
192   $::lxdebug->leave_sub;
193 }
194
195 sub form_footer {
196   $::lxdebug->enter_sub;
197   $::auth->assert('cash');
198
199   print $::form->parse_html_template('cp/form_footer');
200
201   $::lxdebug->leave_sub;
202 }
203
204 sub update {
205   $lxdebug->enter_sub();
206
207   $auth->assert('cash');
208
209   my ($new_name_selected) = @_;
210
211   my ($buysell, $newvc, $updated, $exchangerate, $amount);
212
213   if ($form->{vc} eq 'customer') {
214     $buysell = "buy";
215   } else {
216     $buysell = "sell";
217   }
218
219   # if we switched to all_vc
220   # funktioniert derzeit nicht 12.10.2010 jb
221   if ($form->{all_vc} ne $form->{oldall_vc}) {
222
223     $form->{openinvoices} = ($form->{all_vc}) ? 0 : 1;
224
225     $form->{"select$form->{vc}"} = "";
226
227     if ($form->{all_vc}) {
228       $form->all_vc(\%myconfig, $form->{vc}, $form->{ARAP});
229
230       if ($form->{"all_$form->{vc}"}) {
231         map {
232           $form->{"select$form->{vc}"} .=
233             "<option>$_->{name}--$_->{id}\n"
234         } @{ $form->{"all_$form->{vc}"} };
235       }
236     } else {  # ab hier wieder ausgeführter code (s.o.):
237       CP->get_openvc(\%myconfig, \%$form);
238
239       if ($form->{"all_$form->{vc}"}) {
240         $newvc =
241           qq|$form->{"all_$form->{vc}"}[0]->{name}--$form->{"all_$form->{vc}"}[0]->{id}|;
242         map {
243           $form->{"select$form->{vc}"} .=
244             "<option>$_->{name}--$_->{id}\n"
245         } @{ $form->{"all_$form->{vc}"} };
246       }
247
248       # if the name is not the same
249       if ($form->{"select$form->{vc}"} !~ /$form->{$form->{vc}}/) {
250         $form->{ $form->{vc} } = $newvc;
251       }
252     }
253   }
254
255   # search by invoicenumber, 
256   if ($form->{invnumber}) { 
257     $form->{open} ='Y'; # nur die offenen rechnungen
258     if ($form->{ARAP} eq 'AR'){
259
260       # ar_transactions automatically searches by $form->{customer_id} or else
261       # $form->{customer} if available, and these variables will always be set
262       # when we have a dropdown field rather than an input field, so we have to
263       # empty these values first
264       $form->{customer_id} = '';
265       $form->{customer} = '';
266       AR->ar_transactions(\%myconfig, \%$form);
267
268       # if you search for invoice '11' ar_transactions will also match invoices
269       # 112, 211, ... due to the LIKE
270
271       # so there is now an extra loop that tries to match the invoice number
272       # exactly among all returned results, and then passes the customer_id instead of the name
273       # because the name may not be unique
274
275       my $found_exact_invnumber_match = 0;
276       foreach my $i ( @{ $form->{AR} } ) {
277         next unless $i->{invnumber} eq $form->{invnumber};
278         # found exactly matching invnumber
279         $form->{$form->{vc}} = $i->{name};
280         $form->{customer_id} = $i->{customer_id};
281         #$form->{"old${form->{vc}"} = $i->{customer_id};
282         $found_exact_invnumber_match = 1;
283       };
284
285       unless ( $found_exact_invnumber_match ) {
286         # use first returned entry, may not be the correct one if invnumber doesn't
287         # match uniquely
288         $form->{$form->{vc}} = $form->{AR}[0]{name};
289         $form->{customer_id} = $form->{AR}[0]{customer_id};
290       };
291     } else {
292       # s.o. nur für zahlungsausgang
293       AP->ap_transactions(\%myconfig, \%$form);
294       $form->{$form->{vc}} = $form->{AP}[0]{name};
295     }
296   }
297
298   # determine customer/vendor
299   if ( $form->{customer_id} and $form->{invnumber} ) {
300     # we already know the exact customer_id, so fill $form with customer data
301     IS->get_customer(\%myconfig, \%$form);
302     $updated = 1;
303   } else {
304     # check_name is called with "customer" or "vendor" and otherwise uses contents of $form
305     # check_name also runs get_customer/get_vendor
306     $updated = &check_name($form->{vc});
307   };
308
309   if ($new_name_selected || $updated) {
310     # get open invoices from ar/ap using $form->{vc} and a.${vc}_id, i.e. customer_id
311     CP->get_openinvoices(\%myconfig, \%$form);
312     ($newvc) = split /--/, $form->{ $form->{vc} };
313     $form->{"old$form->{vc}"} = qq|$newvc--$form->{"$form->{vc}_id"}|;
314     $updated = 1;
315   }
316
317   if ($form->{currency} ne $form->{oldcurrency}) {
318     $form->{oldcurrency} = $form->{currency};
319     if (!$updated) {
320       CP->get_openinvoices(\%myconfig, \%$form);
321       $updated = 1;
322     }
323   }
324
325   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{datepaid}, $buysell);
326   $form->{exchangerate} = $form->{forex} if $form->{forex};
327
328   $amount = $form->{amount} = $form->parse_amount(\%myconfig, $form->{amount});
329
330   if ($updated) {
331     $form->{rowcount} = 0;
332
333     $form->{queued} = "";
334
335     my $i = 0;
336     foreach my $ref (@{ $form->{PR} }) {
337       $i++;
338       $form->{"id_$i"}        = $ref->{id};
339       $form->{"invnumber_$i"} = $ref->{invnumber};
340       $form->{"transdate_$i"} = $ref->{transdate};
341       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
342       $form->{"amount_$i"} = $ref->{amount} / $ref->{exchangerate};
343       $form->{"due_$i"}    =
344         ($ref->{amount} - $ref->{paid}) / $ref->{exchangerate};
345       $form->{"checked_$i"} = "";
346       $form->{"paid_$i"}    = "";
347
348       # need to format
349       map {
350         $form->{"${_}_$i"} =
351           $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
352       } qw(amount due);
353
354     }
355     $form->{rowcount} = $i;
356   }
357
358   # recalculate
359
360   # Modified from $amount = $form->{amount} by J.Zach to update amount to total
361   # payment amount in Zahlungsausgang
362   $amount = 0;
363   for my $i (1 .. $form->{rowcount}) {
364
365     map {
366       $form->{"${_}_$i"} =
367         $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
368     } qw(amount due paid);
369
370     if ($form->{"checked_$i"}) {
371
372       # calculate paid_$i
373       if (!$form->{"paid_$i"}) {
374         $form->{"paid_$i"} = $form->{"due_$i"};
375       }
376
377       # Modified by J.Zach, see abovev
378       $amount += $form->{"paid_$i"};
379
380     } else {
381       $form->{"paid_$i"} = "";
382     }
383
384     map {
385       $form->{"${_}_$i"} =
386         $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
387     } qw(amount due paid);
388
389   }
390
391   # Line added by J.Zach, see above
392   $form->{amount}=$amount;
393
394   &form_header;
395   &list_invoices;
396   &form_footer;
397
398   $lxdebug->leave_sub();
399 }
400
401 sub post {
402   $lxdebug->enter_sub();
403
404   $auth->assert('cash');
405
406   &check_form;
407
408   if ($form->{currency} ne $form->{defaultcurrency}) {
409     $form->error($locale->text('Exchangerate missing!'))
410       unless $form->{exchangerate};
411   }
412
413   # Beim Aktualisieren wird das Konto übernommen
414   # und jetzt auch Beleg und Datum
415   $form->{callback} = "cp.pl?action=payment&vc=$form->{vc}&type=$form->{type}&account=$form->{account}&$form->{currency}" .
416                       "&datepaid=$form->{datepaid}&source=$form->{source}";
417
418   my $msg1 = $::form->{type} eq 'receipt' ? $::locale->text("Receipt posted!") : $::locale->text("Payment posted!");
419   my $msg2 = $::form->{type} eq 'receipt' ? $::locale->text("Cannot post Receipt!") : $::locale->text("Cannot post Payment!");
420
421   # Die Nachrichten (Receipt posted!) werden nicht angezeigt.
422   # Entweder wieder aktivieren oder komplett rausnehmen
423   $form->redirect($msg1) if (CP->process_payment(\%::myconfig, $::form));
424   $form->error($msg2);
425
426   $lxdebug->leave_sub();
427 }
428
429 sub check_form {
430   $lxdebug->enter_sub();
431
432   $auth->assert('cash');
433
434   my ($closedto, $datepaid, $amount);
435
436   &check_name($form->{vc});
437
438   if ($form->{currency} ne $form->{oldcurrency}) {
439     &update;
440     ::end_of_request();
441   }
442   $form->error($locale->text('Date missing!')) unless $form->{datepaid};
443   my $selected_check = 1;
444   for my $i (1 .. $form->{rowcount}) {
445     if ($form->{"checked_$i"}) {
446       if ($form->parse_amount(\%myconfig, $form->{"paid_$i"}, 2) <= 0) { # negativen Betrag eingegeben
447           $form->error($locale->text('Amount has to be greater then zero! Wrong row number: ') . $i);
448       }
449         undef($selected_check);
450         # last; # ich muss doch über alle buchungen laufen, da ich noch
451         # die freitext-eingabe der werte prüfen will
452     }
453   }
454   $form->error($locale->text('No transaction selected!')) if $selected_check;
455
456   $closedto = $form->datetonum($form->{closedto}, \%myconfig);
457   $datepaid = $form->datetonum($form->{datepaid}, \%myconfig);
458
459   $form->error($locale->text('Cannot process payment for a closed period!'))
460     if ($form->date_closed($form->{"datepaid"}, \%myconfig));
461
462   $amount = $form->parse_amount(\%myconfig, $form->{amount});
463   $form->{amount} = $amount;
464
465   for my $i (1 .. $form->{rowcount}) {
466     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
467       $amount -= $form->parse_amount(\%myconfig, $form->{"paid_$i"});
468
469       push(@{ $form->{paid}      ||= [] }, $form->{"paid_$i"});
470       push(@{ $form->{due}       ||= [] }, $form->{"due_$i"});
471       push(@{ $form->{invnumber} ||= [] }, $form->{"invnumber_$i"});
472       push(@{ $form->{invdate}   ||= [] }, $form->{"transdate_$i"});
473     }
474   }
475
476   if ($form->round_amount($amount, 2) != 0) {
477     push(@{ $form->{paid} }, $form->format_amount(\%myconfig, $amount, 2));
478     push(@{ $form->{due} }, $form->format_amount(\%myconfig, 0, "0"));
479     push(@{ $form->{invnumber} },
480          ($form->{ARAP} eq 'AR')
481          ? $locale->text('Deposit')
482          : $locale->text('Prepayment'));
483     push(@{ $form->{invdate} }, $form->{datepaid});
484   }
485
486   $lxdebug->leave_sub();
487 }