885c88e622e481dcf2bf9fc53d054b41aa896a59
[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   $form->{selectcustomer} .= "<option value=\"\"></option>\n" if $form->{vc} eq "customer";
76
77   if ($form->{"all_$form->{vc}"}) {
78     # s.o. jb 12.10.2010
79     $form->{"$form->{vc}_id"} = $form->{"all_$form->{vc}"}->[0]->{id};
80     map { $form->{"select$form->{vc}"} .= "<option value=\"$_->{name}--$_->{id}\">$_->{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 = split(/:/, $form->{currencies});
113   chomp $curr[0];
114   $form->{defaultcurrency} = $form->{currency} = $form->{oldcurrency} =
115     $curr[0];
116
117   # Entsprechend präventiv die Auswahlliste für Währungen 
118   # auch mit value= zusammenbauen (s.a. oben bugfix 1771)
119   $form->{selectcurrency} = "";
120   map { $form->{selectcurrency} .= "<option value=\"$_\">$_</option>\n" } @curr;
121
122
123   &form_header;
124   &form_footer;
125
126   $lxdebug->leave_sub();
127 }
128
129 sub form_header {
130   $lxdebug->enter_sub;
131
132   $auth->assert('cash');
133
134   my ($vc, $arap, $exchangerate);
135   my ($onload);
136
137   if ($form->{ $form->{vc} } eq "") {
138     map { $form->{"addr$_"} = "" } (1 .. 4);
139   }
140
141   # sometimes it happens that values in customer arrive without the signs '--'
142   # but in order to select the right option field we need values with '--'
143   if ($form->{vc} eq "customer"){
144     my ($customername) = split /--/, $form->{ $form->{vc} };
145     $form->{ $form->{vc} } = $customername . "--" . $form->{customer_id};
146   }
147   # bugfix 1771
148   # geändert von <option>asdf--2929
149   # nach:
150   #              <option value="asdf--2929">asdf--2929</option>
151   # offen: $form->{ARAP} kann raus?
152   for my $item ($form->{vc}, "account", "currency", $form->{ARAP}) {
153     $form->{"select$item"} =~ s/ selected//;
154     $form->{"select$item"} =~ s/option value="\Q$form->{$item}\E">\Q$form->{$item}\E/option selected value="$form->{$item}">$form->{$item}/;
155   }
156
157   $vc =
158     ($form->{"select$form->{vc}"})
159     ? qq|<select name=$form->{vc}>$form->{"select$form->{vc}"}\n</select>|
160     : qq|<input name=$form->{vc} size=35 value="$form->{$form->{vc}}">|;
161
162   $form->{openinvoices} = $form->{all_vc} ? "" : 1;
163
164   # $locale->text('AR')
165   # $locale->text('AP')
166
167   $form->header;
168
169   $arap = lc $form->{ARAP};
170   $onload = qq|focus()|;
171   $onload .= qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
172   $onload .= qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
173
174   print $::form->parse_html_template('cp/form_header', {
175     is_customer => $form->{vc}   eq 'customer',
176     is_receipt  => $form->{type} eq 'receipt',
177     onload      => $onload,
178     arap        => $arap,
179     vccontent   => $vc,
180   });
181
182   $lxdebug->leave_sub;
183 }
184
185 sub list_invoices {
186   $::lxdebug->enter_sub;
187   $::auth->assert('cash');
188
189   my @columns = qw(amount due paid invnumber id transdate checked);
190   my (@invoices, %total);
191   for my $i (1 .. $::form->{rowcount}) {
192     push @invoices, +{ map { $_ => $::form->{"$_\_$i"} } @columns };
193     $total{$_} += $invoices[-1]{$_} = $::form->parse_amount(\%::myconfig, $invoices[-1]{$_}) for qw(amount due paid);
194   }
195
196   print $::form->parse_html_template('cp/invoices', {
197     invoices => \@invoices,
198     totals   => \%total,
199   });
200
201   $::lxdebug->leave_sub;
202 }
203
204 sub form_footer {
205   $::lxdebug->enter_sub;
206   $::auth->assert('cash');
207
208   print $::form->parse_html_template('cp/form_footer');
209
210   $::lxdebug->leave_sub;
211 }
212
213 sub update {
214   $lxdebug->enter_sub();
215
216   $auth->assert('cash');
217
218   my ($new_name_selected) = @_;
219
220   my ($buysell, $newvc, $updated, $exchangerate, $amount);
221
222   if ($form->{vc} eq 'customer') {
223     $buysell = "buy";
224   } else {
225     $buysell = "sell";
226   }
227
228   # if we switched to all_vc
229   # funktioniert derzeit nicht 12.10.2010 jb
230   if ($form->{all_vc} ne $form->{oldall_vc}) {
231
232     $form->{openinvoices} = ($form->{all_vc}) ? 0 : 1;
233
234     $form->{"select$form->{vc}"} = "";
235
236     if ($form->{all_vc}) {
237       $form->all_vc(\%myconfig, $form->{vc}, $form->{ARAP});
238
239       if ($form->{"all_$form->{vc}"}) {
240         map {
241           $form->{"select$form->{vc}"} .=
242             "<option>$_->{name}--$_->{id}\n"
243         } @{ $form->{"all_$form->{vc}"} };
244       }
245     } else {  # ab hier wieder ausgeführter code (s.o.):
246       CP->get_openvc(\%myconfig, \%$form);
247
248       if ($form->{"all_$form->{vc}"}) {
249         $newvc =
250           qq|$form->{"all_$form->{vc}"}[0]->{name}--$form->{"all_$form->{vc}"}[0]->{id}|;
251         map {
252           $form->{"select$form->{vc}"} .=
253             "<option>$_->{name}--$_->{id}\n"
254         } @{ $form->{"all_$form->{vc}"} };
255       }
256
257       # if the name is not the same
258       if ($form->{"select$form->{vc}"} !~ /$form->{$form->{vc}}/) {
259         $form->{ $form->{vc} } = $newvc;
260       }
261     }
262   }
263
264   # search by customernumber
265   # the customernumber has to be correct otherwise nothing is found
266   if ($form->{vc} eq 'customer' and $form->{customernumber} and $form->{ARAP} eq 'AR') {
267     $form->{open} ='Y'; # only open invoices
268     # ar_transactions automatically searches by $form->{customer_id} or else
269     # $form->{customer} if available, and these variables will always be set
270     # so we have to empty these values first
271     $form->{customer_id} = '';
272     $form->{customer} = '';
273     AR->ar_transactions(\%myconfig, \%$form);
274
275     # Here we just take the first returned value even if the custumernumber
276     # may not be unique
277     $form->{customer} = $form->{AR}[0]{name};
278     $form->{customer_id} = $form->{AR}[0]{customer_id};
279   }
280
281   # search by invoicenumber, 
282   if ($form->{invnumber}) { 
283     $form->{open} ='Y'; # only open invoices
284     if ($form->{ARAP} eq 'AR'){
285       # ar_transactions automatically searches by $form->{customer_id} or else
286       # $form->{customer} if available, and these variables will always be set
287       # so we have to empty these values first
288       $form->{customer_id} = '';
289       $form->{customer} = '';
290       AR->ar_transactions(\%myconfig, \%$form);
291
292       # if you search for invoice '11' ar_transactions will also match invoices
293       # 112, 211, ... due to the LIKE
294
295       # so there is now an extra loop that tries to match the invoice number
296       # exactly among all returned results, and then passes the customer_id instead of the name
297       # because the name may not be unique
298
299       my $found_exact_invnumber_match = 0;
300       foreach my $i ( @{ $form->{AR} } ) {
301         next unless $i->{invnumber} eq $form->{invnumber};
302         # found exactly matching invnumber
303         $form->{$form->{vc}} = $i->{name};
304         $form->{customer_id} = $i->{customer_id};
305         #$form->{"old${form->{vc}"} = $i->{customer_id};
306         $found_exact_invnumber_match = 1;
307       };
308
309       unless ( $found_exact_invnumber_match ) {
310         # use first returned entry, may not be the correct one if invnumber doesn't
311         # match uniquely
312         $form->{$form->{vc}} = $form->{AR}[0]{name};
313         $form->{customer_id} = $form->{AR}[0]{customer_id};
314       };
315     } else {
316       # s.o. nur für zahlungsausgang
317       AP->ap_transactions(\%myconfig, \%$form);
318       $form->{$form->{vc}} = $form->{AP}[0]{name};
319     }
320   }
321
322   # determine customer/vendor
323   if ( $form->{customer_id} and ($form->{invnumber} or $form->{customernumber}) ) {
324     # we already know the exact customer_id, so fill $form with customer data
325     IS->get_customer(\%myconfig, \%$form);
326     $updated = 1;
327   } else {
328     # check_name is called with "customer" or "vendor" and otherwise uses contents of $form
329     # check_name also runs get_customer/get_vendor
330     $updated = &check_name($form->{vc});
331   };
332
333   if ($new_name_selected || $updated) {
334     # get open invoices from ar/ap using $form->{vc} and a.${vc}_id, i.e. customer_id
335     CP->get_openinvoices(\%myconfig, \%$form);
336     ($newvc) = split /--/, $form->{ $form->{vc} };
337     $form->{"old$form->{vc}"} = qq|$newvc--$form->{"$form->{vc}_id"}|;
338     $updated = 1;
339   }
340
341   if ($form->{currency} ne $form->{oldcurrency}) {
342     $form->{oldcurrency} = $form->{currency};
343     if (!$updated) {
344       CP->get_openinvoices(\%myconfig, \%$form);
345       $updated = 1;
346     }
347   }
348
349   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{datepaid}, $buysell);
350   $form->{exchangerate} = $form->{forex} if $form->{forex};
351
352   $amount = $form->{amount} = $form->parse_amount(\%myconfig, $form->{amount});
353
354   if ($updated) {
355     $form->{rowcount} = 0;
356
357     $form->{queued} = "";
358
359     my $i = 0;
360     foreach my $ref (@{ $form->{PR} }) {
361       $i++;
362       $form->{"id_$i"}        = $ref->{id};
363       $form->{"invnumber_$i"} = $ref->{invnumber};
364       $form->{"transdate_$i"} = $ref->{transdate};
365       $ref->{exchangerate} = 1 unless $ref->{exchangerate};
366       $form->{"amount_$i"} = $ref->{amount} / $ref->{exchangerate};
367       $form->{"due_$i"}    =
368         ($ref->{amount} - $ref->{paid}) / $ref->{exchangerate};
369       $form->{"checked_$i"} = "";
370       $form->{"paid_$i"}    = "";
371
372       # need to format
373       map {
374         $form->{"${_}_$i"} =
375           $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
376       } qw(amount due);
377
378     }
379     $form->{rowcount} = $i;
380   }
381
382   # recalculate
383
384   # Modified from $amount = $form->{amount} by J.Zach to update amount to total
385   # payment amount in Zahlungsausgang
386   $amount = 0;
387   for my $i (1 .. $form->{rowcount}) {
388
389     map {
390       $form->{"${_}_$i"} =
391         $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
392     } qw(amount due paid);
393
394     if ($form->{"checked_$i"}) {
395
396       # calculate paid_$i
397       if (!$form->{"paid_$i"}) {
398         $form->{"paid_$i"} = $form->{"due_$i"};
399       }
400
401       # Modified by J.Zach, see abovev
402       $amount += $form->{"paid_$i"};
403
404     } else {
405       $form->{"paid_$i"} = "";
406     }
407
408     map {
409       $form->{"${_}_$i"} =
410         $form->format_amount(\%myconfig, $form->{"${_}_$i"}, 2)
411     } qw(amount due paid);
412
413   }
414
415   # Line added by J.Zach, see above
416   $form->{amount}=$amount;
417
418   &form_header;
419   &list_invoices;
420   &form_footer;
421
422   $lxdebug->leave_sub();
423 }
424
425 sub post {
426   $lxdebug->enter_sub();
427
428   $auth->assert('cash');
429
430   &check_form;
431
432   if ($form->{currency} ne $form->{defaultcurrency}) {
433     $form->error($locale->text('Exchangerate missing!'))
434       unless $form->{exchangerate};
435   }
436
437   # Beim Aktualisieren wird das Konto übernommen
438   # und jetzt auch Beleg und Datum
439   $form->{callback} = "cp.pl?action=payment&vc=$form->{vc}&type=$form->{type}&account=$form->{account}&$form->{currency}" .
440                       "&datepaid=$form->{datepaid}&source=$form->{source}";
441
442   my $msg1 = $::form->{type} eq 'receipt' ? $::locale->text("Receipt posted!") : $::locale->text("Payment posted!");
443   my $msg2 = $::form->{type} eq 'receipt' ? $::locale->text("Cannot post Receipt!") : $::locale->text("Cannot post Payment!");
444
445   # Die Nachrichten (Receipt posted!) werden nicht angezeigt.
446   # Entweder wieder aktivieren oder komplett rausnehmen
447   $form->redirect($msg1) if (CP->process_payment(\%::myconfig, $::form));
448   $form->error($msg2);
449
450   $lxdebug->leave_sub();
451 }
452
453 sub check_form {
454   $lxdebug->enter_sub();
455
456   $auth->assert('cash');
457
458   my ($closedto, $datepaid, $amount);
459
460   &check_name($form->{vc});
461
462   if ($form->{currency} ne $form->{oldcurrency}) {
463     &update;
464     ::end_of_request();
465   }
466   $form->error($locale->text('Date missing!')) unless $form->{datepaid};
467   my $selected_check = 1;
468   for my $i (1 .. $form->{rowcount}) {
469     if ($form->{"checked_$i"}) {
470       if ($form->parse_amount(\%myconfig, $form->{"paid_$i"}, 2) <= 0) { # negativen Betrag eingegeben
471           $form->error($locale->text('Amount has to be greater then zero! Wrong row number: ') . $i);
472       }
473         undef($selected_check);
474         # last; # ich muss doch über alle buchungen laufen, da ich noch
475         # die freitext-eingabe der werte prüfen will
476     }
477   }
478   $form->error($locale->text('No transaction selected!')) if $selected_check;
479
480   $closedto = $form->datetonum($form->{closedto}, \%myconfig);
481   $datepaid = $form->datetonum($form->{datepaid}, \%myconfig);
482
483   $form->error($locale->text('Cannot process payment for a closed period!'))
484     if ($form->date_closed($form->{"datepaid"}, \%myconfig));
485
486   $amount = $form->parse_amount(\%myconfig, $form->{amount});
487   $form->{amount} = $amount;
488
489   for my $i (1 .. $form->{rowcount}) {
490     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
491       $amount -= $form->parse_amount(\%myconfig, $form->{"paid_$i"});
492
493       push(@{ $form->{paid}      ||= [] }, $form->{"paid_$i"});
494       push(@{ $form->{due}       ||= [] }, $form->{"due_$i"});
495       push(@{ $form->{invnumber} ||= [] }, $form->{"invnumber_$i"});
496       push(@{ $form->{invdate}   ||= [] }, $form->{"transdate_$i"});
497     }
498   }
499
500   if ($form->round_amount($amount, 2) != 0) {
501     push(@{ $form->{paid} }, $form->format_amount(\%myconfig, $amount, 2));
502     push(@{ $form->{due} }, $form->format_amount(\%myconfig, 0, "0"));
503     push(@{ $form->{invnumber} },
504          ($form->{ARAP} eq 'AR')
505          ? $locale->text('Deposit')
506          : $locale->text('Prepayment'));
507     push(@{ $form->{invdate} }, $form->{datepaid});
508   }
509
510   $lxdebug->leave_sub();
511 }